Ansible Can';我看不出一个可靠的事实

Ansible Can';我看不出一个可靠的事实,ansible,ansible-playbook,ansible-facts,Ansible,Ansible Playbook,Ansible Facts,我知道访问Ansible facts是可行的,但我无法让这个代码工作 # site.yml --- - name: get fact hosts: webservers tasks: - debug: msg="{{ hostvars['web01.example.com']['ansible_all_ipv4_addresses'] }}" - fail: 当我运行它时,会出现以下错误: fatal: [web01.example.com] => One or

我知道访问Ansible facts是可行的,但我无法让这个代码工作

# site.yml
---
- name: get fact
  hosts: webservers

  tasks:
    - debug: msg="{{ hostvars['web01.example.com']['ansible_all_ipv4_addresses'] }}"
    - fail:
当我运行它时,会出现以下错误:

fatal: [web01.example.com] => One or more undefined variables: 'dict object' has no attribute 'ansible_all_ipv4_addresses'
然而,当我运行命令“ansible-I inventory-m setup”时,我确实看到了字典键:

web01.example.com | success >> {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "<ip_address>"
        ],
        (other objects...)
    }
}

我做错了什么?看起来这应该很简单。

这应该可以做到:

- debug: msg="{{ hostvars[inventory_hostname]['ansible_all_ipv4_addresses'] }}"

与ansible有点混淆,但您只需使用(中间没有
ansible\u facts
):

或者像@oley发布的那样

hostvars[inventory_hostname]['ansible_all_ipv4_addresses']
对于任务中的相应主机


在你张贴的文档中,中间也总是没有<>代码> ANSILBLASHOS/<代码>,但是它很容易被忽视:

当你运行你的剧本时,实际上有一个“安装”任务作为第一个任务执行吗?code>{hostvars['web01.example.com']['ansible\u all\u ipv4\u addresses']}应该可以工作,所以
{{hostvars[inventory\u hostname]['ansible\u all\u ipv4\u addresses']}
。另外,
{{ansible\u all\u ipv4\u addresses}}
也可以工作,因为您只有一台主机,所以实际上是首选解决方案。如果需要访问其他主机的事实,只需使用
hostvars
对象。但如果所有这些都不起作用,这表明事实根本没有定义,只有在没有执行安装模块的情况下才会发生。我的错误是我将Ansible“gather_facts”设置为False而不是True。
- debug: msg="{{ hostvars[inventory_hostname]['ansible_all_ipv4_addresses'] }}"
hostvars['web01.example.com']['ansible_all_ipv4_addresses']
hostvars[inventory_hostname]['ansible_all_ipv4_addresses']