ansible

How to set fact which is visible on all hosts in Ansible role


I'm setting fact in a role:

- name: Check if manager already configured
  shell: >
    docker info | perl -ne 'print "$1" if /Swarm: (\w+)/'
  register: swarm_status

- name: Init cluster
  shell: >-
    docker swarm init
    --advertise-addr "{{ ansible_default_ipv4.address }}"
  when: "'active' not in swarm_status.stdout_lines"

- name: Get worker token
  shell: docker swarm join-token -q worker
  register: worker_token_result

- set_fact:
    worker_token: "{{ worker_token_result.stdout  }}"

Then I want to access worker_token on another hosts. Here's my main playbook, the fact is defined in the swarm-master role

- hosts: swarm_cluster
  become: yes
  roles:
    - docker

- hosts: swarm_cluster:&manager
  become: yes
  roles:
    - swarm-master

- hosts: swarm_cluster:&node
  become: yes
  tasks:
    - debug:
        msg: "{{ worker_token }}"

I'm getting undefined variable. How to make it visible globally? Of course it works perfectly if I run debug on the same host.


Solution

  • if your goal is just to access worker_token from on another host, you can use hostvars variable and iterate through the group where you've defined your variable like this:

    - hosts: swarm_cluster:&node
      tasks:
      - debug:
          msg: "{{ hostvars[item]['worker_token'] }}"
        with_items: "{{ groups['manager'] }}"
    

    If your goal is to define the variable globally, you can add a step to define a variable on all hosts like this:

    - hosts: all
      tasks:
      - set_fact:
          worker_token_global: "{{ hostvars[item]['worker_token'] }}"
        with_items: "{{ groups['manager'] }}"
    
    - hosts: swarm_cluster:&node
      tasks:
      - debug:
          var: worker_token_global