jinja2 - AnsibleUndefinedVariable:“dict 对象"没有属性“{{ target_hosts }}"“" [英] jinja2 - AnsibleUndefinedVariable: 'dict object' has no attribute '"{{ target_hosts }}"'"

查看:42
本文介绍了jinja2 - AnsibleUndefinedVariable:“dict 对象"没有属性“{{ target_hosts }}"“"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我更新/etc/hosts 文件的 Ansible 剧本:

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

这是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']),一切正常,但我想使用一个变量,通过动态到剧本.

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.

我得到的错误是:

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". 

也许 j2 模板没有?
语法错了吗?我用引号、双引号和两者的组合都试过了.

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

推荐答案

语法错误吗?

是的.不要嵌套 Jinja2 表达式.在您的情况下 {{{% 内.

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

正确的语法:

{% for item in groups[target_hosts] %}

这篇关于jinja2 - AnsibleUndefinedVariable:“dict 对象"没有属性“{{ target_hosts }}"“"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆