Ansible - 无法获取远程主机名

时间:2021-03-11 14:00:54

标签: ansible

这里是我的 playbook.yml:

- hosts: oph-server
  roles:
    - role: 'myrole'
      server_hostname: "{{ansible_hostname}}"
      io_hostnames: "{{ groups['oph-io']|map('extract', hostvars, 'ansible_hostname')|list }}"
      io_ips: "{{ groups['oph-io']|map('extract', hostvars, 'ansible_default_ipv4')|list if 'oph-io' in groups else []}}"

- hosts: oph-io
  roles:
    - role: 'myrole'
      server_hostname: "{{ hostvars['oph-server']['ansible_hostname'] }}"
      io_hostnames: "{{ groups['oph-io']|map('extract', hostvars, 'ansible_hostname')|list if 'oph-io' in groups else []}}"
      io_ips: "{{ groups['oph-io']|map('extract', hostvars, ['ansible_default_ipv4', 'address'])|list if 'oph-io' in groups else []}}"

这是库存

[oph-io]
oph-io1 ansible_default_ipv4=A.B.C.D
[oph-server]
oph-server ansible_default_ipv4=E.F.G:H

oph-io 节点上没有问题,而在 oph-server 上我能够正确获取 io_ips,但 io_hostnames 为 UNDEFINED

怎么了?

谢谢

1 个答案:

答案 0 :(得分:2)

ansible_hostnameansible_default_ipv4 是带有 setup module 或播放关键字 gather_facts: yes 的计算事实。

剧集仅收集目标主机的事实,因此尚未收集来自 oph-io 的事实。 要收集其他主持人的事实(或之前尚未被另一部剧收集),您可以使用 setup 模块与委托和事实委托如文档化https://docs.ansible.com/ansible/2.9/user_guide/playbooks_delegation.html#delegated-facts

- hosts: oph-server
  pre_tasks:
    - name: gather facts from oph-io
      setup:
      delegate_to: "{{ item }}"
      delegate_facts: true
      loop: "{{ groups['oph-io'] }}"
  roles:
    - role: 'myrole'
[...]

要定义要连接的机器 IP 或主机,参数为 ansible_host,如 ansible inventory documentation 中所述。

相关问题