Loops 使用Jinja2模板遍历主机
我有如下的主机文件Loops 使用Jinja2模板遍历主机,loops,ansible,jinja2,Loops,Ansible,Jinja2,我有如下的主机文件 [test1] 10.33.11.198 10.33.11.185 {% for i in groups['test1'] %} IP{{ i }}={{ hostvars[groups['test1'][i]]['ansible_default_ipv4']['address'] }} {% endfor %} 我使用的模板如下 [test1] 10.33.11.198 10.33.11.185 {% for i in groups['test1'] %} IP{{
[test1]
10.33.11.198
10.33.11.185
{% for i in groups['test1'] %}
IP{{ i }}={{ hostvars[groups['test1'][i]]['ansible_default_ipv4']['address'] }}
{% endfor %}
我使用的模板如下
[test1]
10.33.11.198
10.33.11.185
{% for i in groups['test1'] %}
IP{{ i }}={{ hostvars[groups['test1'][i]]['ansible_default_ipv4']['address'] }}
{% endfor %}
我的期望是
IP0=10.33.11.198
IP1=10.33.11.185
但是,我得到下面的错误
fatal: [10.33.11.198]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'list object' has no attribute u'10.33.11.198'"}
fatal: [10.33.11.185]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'list object' has no attribute u'10.33.11.198'"}
任何帮助都将不胜感激 您的问题是i不是索引,而是列表中的一个元素。 试一试 检查 尝试一个简单的例子: 主持人:
[test1]
10.33.11.198
10.33.11.185
和x.yml(将您的['ansible\u default\u ipv4']['address']
替换为目录\u主机名
)
运行:
$ ansible-playbook -i hosts x.yml
PLAY [localhost] ***************************************************************************************
TASK [Gathering Facts] *********************************************************************************
ok: [localhost]
TASK [debug] *******************************************************************************************
ok: [localhost] => {
"msg": "IP0=10.33.11.198\nIP1=10.33.11.185\n"
}
PLAY RECAP *********************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0