我正在尝试使用主机变量中的jinja2循环索引从清单中获取ip地址(从ansible):
库存如下所示:
all:
hosts:
host1:
ansible_host: 192.168.1.1
host2:
ansible_host: 192.168.1.2
host3:
ansible_host: 192.168.1.3
service_nodes:
hosts:
host1:
host2:
host3:Template.yml类似于:
...
{% for host in service_nodes %}
- {{ loop.index }}:{{ hostvars[groups.service_nodes[{{ loop.index }}]].ansible_host }}
...
{% endfor %}
...我运行了攻略,但遇到了:{"changed": false, "msg": "AnsibleError: template error while templating string: expected token ':', got '}'.查看了AnsibleError: template error while templating string: expected token 'end of statement block', got '{',但似乎这不是我的答案。
另外,我在模板上尝试了这些,但失败了:
{% set idx = loop.index %}
- {{ loop.index }}:{{ hostvars[groups.service_nodes[{{ idx }}]].ansible_host }}和
- {{ loop.index }}:{{ hostvars[groups.service_nodes["{{ loop.index }}"]].ansible_host }}发布于 2020-08-31 18:07:24
使用指令children声明group of hosts service_nodes
shell> cat hosts
all:
hosts:
host1:
ansible_host: 192.168.1.1
host2:
ansible_host: 192.168.1.2
host3:
ansible_host: 192.168.1.3
children:
service_nodes:
hosts:
host1:
host2:
host3:测试它。查看命令的输出
shell> ansible-inventory -i hosts --list然后是下面的攻略
shell> cat playbook.yml
- hosts: all
tasks:
- template:
src: template.yml
dest: hosts.txt
delegate_to: localhost
run_once: true和模板
shell> cat template.yml
{% for host in groups.service_nodes %}
- {{ loop.index }}:{{ hostvars[host]['ansible_host'] }}
{% endfor %}给
shell> cat hosts.txt
- 1:192.168.1.1
- 2:192.168.1.2
- 3:192.168.1.3https://stackoverflow.com/questions/63667812
复制相似问题