2016-08-17 94 views
1

我试图在模板中使用play_hosts变量。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 
+1

jinja语法是{%...%}不是{% - ...%} jinja.pocoo.org/docs/dev/templates –

+0

你确定'ansible_hostname +'_alias''是变量名吗? –

+0

我很确定ansible_hostname +'_alias'我在其他地方使用过这个变量。 –

回答

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 %} 

输出:

[[email protected] 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" /> 
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

幸运的是,这只花了我两天的时间才弄清楚。