6

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?

techraf
  • 64,883
  • 27
  • 193
  • 198
Rinat Mukhamedgaliev
  • 5,401
  • 8
  • 41
  • 59

2 Answers2

10

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.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • Thanks, I also put a sample of exporting Names and Status. `shell: docker ps -a --format='{''{.Names}''}{''{.Status}''}'` – zqcolor Jun 03 '19 at 23:18
5

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

AnujAroshA
  • 4,623
  • 8
  • 56
  • 99
  • Actually I prefer this solution because it uses a module. Maybe you need to adapt accessing the actual variable depending on your network settings but just have a look at the output of your docker logs or `result.container` to find the needed value. – Ken Jiiii May 25 '20 at 10:56
  • Hi, using ansible-playbook 2.9.22 it doesn't work for me, it returns an empty string. Dumping result.container.NetworkSettings I've seen it returns a complex object with lots of fields, I tried result.container.NetworkSettings.Networks.my_network_name.IPAddress but it doesn't work. Any help will be very appreciated. – Angel Jun 07 '21 at 19:36