Using {{ and }} in ansible shell command

2019-05-21 12:15发布

问题:

I have this in my playbook:

- name: Get facts about containers
  shell: "docker ps -f name=jenkins --format {%raw%}{{.Names}}{% endraw %}"
  register: container

Note, that I inserted the {%raw%} and {%endraw%} so that ansible does not evaulate the '{{'.

If I run this, I get this error:

fatal: [localhost]: FAILED! => {"failed": true, "msg": "{u'cmd': u'docker ps -f name=jenkins --format {{.Names}}', u'end': u'2017-01-19 10:04:27.491648', u'stdout': u'ecs-sde-abn-17-jenkins-ec8eccee8c9eb8e38f01', u'changed': True, u'start': u'2017-01-19 10:04:27.481090', u'delta': u'0:00:00.010558', u'stderr': u'', u'rc': 0, 'stdout_lines': [u'ecs-task-17-jenkins-ec8eccee8c9eb8e38f01'], u'warnings': []}: template error while templating string: unexpected '.'. String: docker ps -f name=jenkins --format {{.Names}}"}

In other words, the command ran succesfully (the output ecs-task-17-jenkins-ec8eccee8c9eb8e38f01 is correct), but than it tries the template the string ... again?

What is going wrong here and how can I fix this?

EDITED

Escaping the {{ like this:

shell: "docker ps -f name=jenkins --format {{ '{' }}{.Names}{{ '}' }}"

results in the same error.

回答1:

This is a problem introduced in Ansible 2.2.1: https://github.com/ansible/ansible/issues/20400. Happens when registering variable with {{ inside.

This workaround prevent {{ from appearing in registered variable:

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

Way to reproduce the bug:

- hosts: localhost
  gather_facts: no
  tasks:
    - shell: "echo '{''{.Names}''}'"
      register: myvar    
    - debug: var=myvar