2016-08-17 142 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

幸運的是,這隻花了我兩天的時間才弄清楚。