这是我更新/etc/hosts 文件的 Ansible 剧本:
- 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
这是 jinja 模板:
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 %}
如果我在模板中放置一个静态值(例如组中的项目['my-server-group']),一切都会正常工作,但我想使用一个变量,通过动态地适应剧本。
我得到的错误是:
AnsibleUndefinedVariable: 'dict object' has no attribute '\"{{ target_hosts }}\"'"
通过调试消息,我确信剧本会获取参数:
> "msg": "show me the variable: my-server-group".
也许 j2 模板没有?
语法有错误吗?我尝试了引号、双引号和两者的组合。
最佳答案
Is the syntax wrong?
是的。不要嵌套 Jinja2 表达式。在您的情况下 {{
位于 {%
内。
正确语法:
{% for item in groups[target_hosts] %}
关于ansible - jinja2-AnsibleUndefinedVariable : 'dict object' has no attribute '"{{ target_hosts } }"' ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50412020/