Reputation: 141
I have hosts file like below
[test1]
10.33.11.198
10.33.11.185
i am using a template like below
{% for i in groups['test1'] %}
IP{{ i }}={{ hostvars[groups['test1'][i]]['ansible_default_ipv4']['address'] }}
{% endfor %}
my expectation is
IP0=10.33.11.198
IP1=10.33.11.185
but, i am getting below error.
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'"}
Any help would be appreciated.
Upvotes: 0
Views: 4110
Reputation: 5102
Your problem is that i is not an index, but an element of the list. Try
{% for i in groups['test1'] %}
IP{{ loop.index0 }}={{ hostvars[i]['ansible_default_ipv4']['address'] }}
{% endfor %}
Check Jinja2 for statement
Trying a minimal example:
hosts:
[test1]
10.33.11.198
10.33.11.185
and x.yml (replaced your ['ansible_default_ipv4']['address']
with just inventory_hostname
)
- hosts: localhost
tasks:
- debug: msg="{% for i in groups['test1'] %}\nIP{{ loop.index0 }}={{ hostvars[i].inventory_hostname }}\n{% endfor %}"
running:
$ 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
Upvotes: 1