Ansible facts_gathering in roles with tags

Ansible is an IaC software. You can create playbooks which consist of roles and tasks. To enable partial playbook deployment, one can use tags to limit the deployment to a defined set of tasks.

Ansible also delivers magic variables, therefore variables with a predefined content and/or structure. One of the is ansible_facts which delivers information about the to be processed (remote) host. Ansible gathers facts about the host automatically at the beginning of the playbook. One can deactivate this via the following code snippet in the playbook:

gather_facts: no

When running the playbook with tags, only the selected tasks are run, which exclude the facts gathering. All tasks that require ansible_facts do not work, therefore.

The ansible module setup does the same thing as the the facts_gathering and also saves the result into the same magic variable ansible_facts. The following task helps overcome the described problem:

- name: Gather ansible_facts
  setup:
    gather_subset:
      - all
  tags: never
The module lets you decide if all facts should be gathered or just a subset (gather_subset). Also, the line tags: never defines that this task should never run, except when run with at least one tag.

If you want to always gather facts on your play, not just a role, I would suggest to preload the playbook with a gathering one as displayed below:

# Gather facts of servers
- name: gather_facts of servers
  hosts: servers
  tags: servers
  gather_facts: false
  become: true

  tasks:
    - name: Gather ansible_facts
      setup:
        gather_subset:
          - all
      tags: always 

# Configure servers
- name: configure servers
  hosts: servers
  tags: servers
  gather_facts: false
  become: true
 
  roles:
    - name: _apt-sources
      tags: _apt-sources
      when:
      - ansible_distribution == "Debian"
This display gathers all facts via a first play and does all the actual configuration, etc. of your choice in the second play. You should notice the tag always at the task and the gather_facts: false parameter. This configures the plays to only run a facts gathering once via the task (and this one runs always) and not built-in.

Previous Blog EntryNext Blog Entry


Last update: 2025-01-07