我试图在ansible模板中使用play_hosts
变量。
我正在尝试为wildfly设置主/从域设置。
所以我希望遍历清单组中的所有主机,而不必指定组。
这就是我正在尝试的:
{%- 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 %}
我收到以下错误:
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
答案 0 :(得分:0)
剧本:
---
# 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
模板:
{{ play_hosts }}
{% for host in play_hosts %}
<remote protocol="remote" host="{{ hostvars[host]['ansible_default_ipv4']['address'] }}" port="9999" />
{% endfor %}
输出:
[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
示例文件:
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" />
答案 1 :(得分:0)
我通过以下方式解决了这个问题:
{%- 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 %}
诀窍不是依赖于ansible_hostname
而是依赖于迭代变量h
。
幸运的是,我花了两天才弄明白。