pdna
pdna

Reputation: 602

How to use facts/variables defined for one playbook in another?

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?

Upvotes: 1

Views: 6681

Answers (1)

techraf
techraf

Reputation: 68629

Facts are bound to hosts not plays, and remain defined for the life of a playbook being run.

You seem to already know how to refer to facts from another host, so just use it. Either (if you retain set_fact in the first playbook):

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

Or (because there seems to be no need to set the facts in the first play):

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

I used hostname above to refer to the host you wanted. client1 in your playbook is a host group. It might or might not match the name of the host. It might also resolve to multiple hosts.

Upvotes: 1

Related Questions