Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IP address of Docker with Ansible

Tags:

docker

ansible

I have follow playbook command:

  - name: Docker | Consul | Get ip
    shell: "docker inspect --format {% raw %}'{{ .NetworkSettings.IPAddress }}' {% endraw %} consul"
    register: consul_ip

After run ansible return follow error:

fatal: [192.168.122.41]: FAILED! => {"failed": true, "msg": "{u'cmd': u\"docker inspect --format '{{ .NetworkSettings.IPAddress }}' consul\", u'end': u'2017-01-18 16:52:18.786469', u'stdout': u'172.17.0.2', u'changed': True, u'start': u'2017-01-18 16:52:18.773819', u'delta': u'0:00:00.012650', u'stderr': u'', u'rc': 0, 'stdout_lines': [u'172.17.0.2'], u'warnings': []}: template error while templating string: unexpected '.'. String: docker inspect --format '{{ .NetworkSettings.IPAddress }}' consul"}

Ansible version:

ansible 2.2.1.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides

How right way to get IP address of container?

like image 258
Rinat Mukhamedgaliev Avatar asked Jan 18 '17 13:01

Rinat Mukhamedgaliev


2 Answers

Trick with bash concatenation ability:

shell: "docker inspect --format '{''{ .NetworkSettings.IPAddress }''}' consul"

This will stick together {+{ .NetworkSettings.IPAddress }+} into single string in bash.

Update: the root cause of this behaviour is described here.

like image 100
Konstantin Suvorov Avatar answered Oct 01 '22 05:10

Konstantin Suvorov


Another way is using docker_container_info

- name: Get infos on container
  docker_container_info:
    name:{{ container_name }}
  register: result

- name: Does container exist?
  debug:
    msg: "The container {{ 'exists' if result.exists else 'does not exist' }}"

- name: Print information about container
  debug:
    var: result.container.NetworkSettings.IPAddress
  when: result.exists

Output will be like below.

enter image description here

like image 25
AnujAroshA Avatar answered Oct 01 '22 06:10

AnujAroshA