我尝试使用ansible动态生成/etc/hosts文件的一部分,方法是从所有主机收集事实并循环结果hostvars以获取第二个接口的IP (我需要此接口上的私有IP,而不是另一个接口的公共IP )
我可以使用以下方法从单个主机获取此信息:
- name: play 1
hosts: all
- name: play 2
hosts: localhost
connection: local
become: no
tasks:
- debug:
var: hostvars['mysinglehost'].ansible_all_ipv4_addresses[1]...but我想要做的是遍历所有主机,并从每个主机获取此值,最终将此信息写入我的主机文件,但我只能获得一些调试信息:)
我试过了
...
- debug:
var: hostvars[item].ansible_all_ipv4_addresses[1]
with_inventory_hostnames:
- all
......which给出了我期望的输出,但是当我尝试使用这个调试任务输出一个msg时:
...
- debug:
msg: "{{ hostvars[item].ansible_all_ipv4_addresses[1] }}"
with_inventory_hostnames:
- all
...我得到以下错误(例如,当我尝试使用lineinfile写入文件时):
fatal: [localhost]: FAILED! =>
msg: |-
The task includes an option with an undefined variable. The error was: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'ansible_all_ipv4_addresses'我不确定为什么会发生这种情况,因为它试图引用完全相同的变量。有没有办法做到这一点?
发布于 2021-03-09 18:19:59
我还没有测试过这一点,但原则上,也许这能行得通?
- hosts: all
- hosts: localhost
gather_facts: false
tasks:
- set_fact:
my_hosts: |
{
{% for a_host in hostvars | dict2items %}
"{{ a_host.key }}": "{{ a_host.value.ansible_all_ipv4_addresses[1] }}",
{% endfor %}
}然后,您只需在my_hosts上循环,而不是在hostvar上循环
https://stackoverflow.com/questions/66521717
复制相似问题