'ansible play_hosts template loop
I'm trying to use the play_hosts variable in an ansible template.
I'm trying to setup a master / slave domain setup for wildfly.
So I wish to loop over all hosts in the inventory group, without having to specify a group.
This is what I'm trying:
{%- for host in play_hosts %}
{%- if 'master' in hostvars[host][ansible_hostname + '_alias'] %}
<remote protocol="remote" host="{{ hostvars[host]['ansible_default_ipv4']['address'] }}" port="9999" />
{%- endif %}
{%- endfor %}
I get the below error:
failed: [atllvjksap012d.hughestelematics.net] (item=host) => {"failed": true, "item": "host", "msg": "AnsibleUndefinedVariable: Unable to look up a name or access an attribute in template string
Solution 1:[1]
Playbook:
---
# http://stackoverflow.com/questions/39005760/ansible-play-hosts-template-loop
- name: so question 39005760 version 2
hosts: all
tasks:
- name: show debug
debug: msg="target = {{ item }} default ipv4 = {{ hostvars[item]['ansible_default_ipv4']['address'] }}"
with_items: "{{ play_hosts }}"
- name: make template
template:
src: q39005760v2.j2
dest: /home/ansible/q39005760.txt
Template:
{{ play_hosts }}
{% for host in play_hosts %}
<remote protocol="remote" host="{{ hostvars[host]['ansible_default_ipv4']['address'] }}" port="9999" />
{% endfor %}
Output:
[ak@vm566970 stackoverflow]$ ansible-playbook -i hosts q39005760v2.yml PLAY [so question 39005760] **************************************************** TASK [setup] ******************************************************************* ok: [server274.mydomain.tld] TASK [show debug] ************************************************************** ok: [server274.mydomain.tld] => (item=server274.mydomain.tld) => { "item": "server274.mydomain.tld", "msg": "target = server274.mydomain.tld default ipv4 = 100.101.102.103" } TASK [make template] *********************************************************** ok: [server274.mydomain.tld] PLAY RECAP ********************************************************************* server274.mydomain.tld : ok=3 changed=0 unreachable=0 failed=0
Sample file:
q39005760.txt [----] 0 L:[ 1+ 0 1/ 5] *(0 / 124b) 0045 0x02D [*][X] [u'server274.mydomain.tld'] <remote protocol="remote" host="100.101.102.103" port="9999" />
Solution 2:[2]
I resolved it in the following manner:
{%- for h in play_hosts %}
{%- if 'master' in hostvars[h][h.split('.')[0] + '_alias'] %}
<remote protocol="remote" host="{{ hostvars[h]['ansible_default_ipv4']['address'] }}" port="9999" />
{% endif %}
{% endfor %}
The trick was not to rely on ansible_hostname but on the iteration variable h.
Fortunately, it only took me two days to figure out.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Simply Seth |
