ansibleansible-facts

Ansible pass fact between hosts in the same playbook


I'm trying to pass a fact from host1 to host2, but when ansible reaches hosts2 it returns "undefined variable":

- name: some playbook
  gather_facts: false
  hosts: host1
  tasks:
    - set_fact:
        fact1: "foo"

- hosts: host2
  gather_facts: false
  tasks:
    - debug:
        msg: "{{ fact1 }}"

Solution

  • set_fact module sets host variables, You could access to those variable with hostvars.

    - name: some playbook
      gather_facts: no
      hosts: host1
      tasks:
    
      - set_fact:
          fact1: "foo"
    
    - hosts: host2
      gather_facts: no
      tasks:
    
      - debug:
          msg: "{{ hostvars['host1']['fact1'] }}"