我有如下所示的主机文件
[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'"}
任何帮助将不胜感激。
答案 0 :(得分:1)
您的问题是我不是索引,而是列表的元素。 试试
{% for i in groups['test1'] %}
IP{{ loop.index0 }}={{ hostvars[i]['ansible_default_ipv4']['address'] }}
{% endfor %}
尝试一个最小的例子:
主机:
[test1]
10.33.11.198
10.33.11.185
和x.yml(仅将['ansible_default_ipv4']['address']
替换为inventory_hostname
)
- hosts: localhost
tasks:
- debug: msg="{% for i in groups['test1'] %}\nIP{{ loop.index0 }}={{ hostvars[i].inventory_hostname }}\n{% endfor %}"
运行:
$ 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