ansible - jinja2-AnsibleUndefinedVariable : 'dict object' has no attribute '"{{ target_hosts } }"' "

标签 ansible jinja2

这是我更新/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/

相关文章:

git - 使用 Ansible 从 Bitbucket 克隆一个 git repo - 要求密码两次或三次

templates - 在 Ansible 模板中使用变量

python - 有没有针对视频或图片的 Jinja2/Django 扩展?

jinja2 - Ansible 使用带有 blockinfile 的模板

python - Jinja 渲染 matplotlib 图?

amazon-ec2 - Ansible EC2 动态库存最低 IAM 策略

command-line - ansible - 如何在运行 ansible-playbook 时传递本地 DNS 服务器来解析主机名

Ansible:如何从另一个变量构造一个变量,然后获取它的值

python - Jinja2 模板在 Django 1.9 中不起作用

json - saltstack 的 jinja 中的 "json"和 "tojson"过滤器之间有什么区别吗?