Get IP address of Docker with Ansible

2019-06-26 18:25发布

问题:

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?

回答1:

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.