1

Lets say I have a playbook like below

- name: install nagios client
  hosts: client1
  roles:
    - nagios-client
  set_fact:
    client_ip: "{{ ansible_default_ipv4.address }}"
    client_hostname: "{{ ansible_hostname }}"

- name: register client
  hosts: server
  vars:
    - ip: {{ client_ip }}
    - hostname: {{ client_hostname }}
  role:
    - register-nagios-client

I know that set_fact is bound to one host and cannot be used in another, also that you can get the IP of the client from facts {{ hostvars['client1']['ansible_eth0']['ipv4']['address'] }}. But is there a work around to define a local variable that can be referenced in multiple places in the yml file?

4

1 回答 1

1

事实绑定到主机而不是播放,并且在运行的剧本的生命周期内保持定义。

您似乎已经知道如何从另一个主机引用事实,所以只需使用它。要么(如果您保留set_fact在第一个剧本中):

vars:
  - ip: "{{ hostvars['hostname'][client_ip] }}"
  - hostname: "{{ hostvars['hostname'][client_hostname] }}"

或者(因为似乎不需要在第一部剧中设置事实):

vars:
  - ip: "{{ hostvars['hostname'][ansible_default_ipv4][address] }}"
  - hostname: "{{ hostvars['hostname'][ansible_hostname] }}"

我在hostname上面用来指代您想要的主机。client1在你的剧本中是一个主机组。它可能与主机名匹配,也可能不匹配。它也可能解析为多个主机。

于 2017-10-07T23:52:32.927 回答