Docker – How to get the docker version of the host in the dynamic inventory and/or Ansible facts

ansibleansible-playbookdockervmware-vsphere

We would like to do different things on hosts that run Docker 1.12 than on Docker 1.10 in Ansible.

How can I obtain the version of Docker specified in my inventory, so that I can later say…

  • Fetch all hosts that run Docker 1.10 on environment Testing and run
    this Ansible playbook.

I don't know if it matters, but we mainly use VMware with CoreOS or CentOS installed on the virtual machines.

Best Answer

Here's an example how you could do what you want:

---
 - hosts: localhost
   remote_user: test
   tasks:
     - name: get docker version
       shell: "docker -v | cut -d ' ' -f 3 | cut -d ',' -f 1"
       register: version

     - debug: var=version.stdout

     - name: do something if version is 1.13.0
       shell: "echo it is 1.13.0"
       when: version.stdout == "1.13.0"

     - name: do nothing if version is 1.13.0
       shell: "echo nothing"
       when: version.stdout != "1.13.0"

You get the docker version and store it in a variable. Then with properly set conditions you can execute the tasks you need to. The output of the test playbook is:

[me@mac]$ ansible-playbook test.yml
 [WARNING]: Host file not found: /etc/ansible/hosts

 [WARNING]: provided hosts list is empty, only localhost is available


PLAY [localhost] ***************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [get docker version] ******************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "version.stdout": "1.13.0"
}

TASK [do something if version is 1.13.0] ***************************************
changed: [localhost]

TASK [do nothing if version is 1.13.0] *****************************************
skipping: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=4    changed=2    unreachable=0    failed=0

I have docker 1.13.0. The playbook was run on my Mac, but it will work on CentOS too. Depending on permissions you might need to use sudo. Ansible version in the example is 2.2.1.0, but it will work on lower versions too.

You can run a similar playbook against your inventory, and do echo $HOSTNAME for all hosts which have the desired docker version - that way you will gather the information you need. Of course you may omit the output with grep.