ansible play_hosts 模板循环

问题描述 投票:0回答:2

我正在尝试在 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
loops ansible jinja2 ansible-2.x
2个回答
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" />

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

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

© www.soinside.com 2019 - 2024. All rights reserved.