jinja2 - AnsibleUndefinedVariable: 'dict objec

2020-04-10 21:13发布

This is my Ansible playbook to update /etc/hosts file:

- name: Update /etc/hosts file
  hosts: "{{ target_hosts }}"
  remote_user: awx
  become: yes
  become_method: sudo
  tasks:

    - debug:
        msg: 'show me the variable: {{ target_hosts }}'

    - name: Update /etc/hosts file
      template: src=../../templates/hosts.j2 dest=/etc/hosts

And this is the jinja template:

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

{% for item in groups['"{{ target_hosts }}"'] %}
{{ hostvars[item]['ansible_ssh_host'] }} {{ hostvars[item]['openstack']['name'] }}
{% endfor %}

Everything works fine if I put a static value in the template (for example for item in groups['my-server-group']), but I would like to use a variable, passed dinamically to the playbook.

The error I get is:

AnsibleUndefinedVariable: 'dict object' has no attribute '\"{{ target_hosts }}\"'"

With the debug msg I'm sure that the playbook gets the parameter:

> "msg": "show me the variable: my-server-group". 

Maybe the j2 template doesn't?
Is the syntax wrong? I tried both with quotes, double quotes and combination of two.

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-04-10 21:31

Is the syntax wrong?

Yes. Don't nest Jinja2 expressions. In your case {{ inside of {%.

Correct syntax:

{% for item in groups[target_hosts] %}
查看更多
登录 后发表回答