Ansible – gather facts (playbook)

Ansible provides valuable information about the nodes (server/system) through ansible gather facts.

Ansible ad-hoc command uses a setup module to get the facts, refer to our earlier post for more detail on the Ansible Ad-Hoc setup module.

Ansible playbook on the other hand by default collects the fact information. This fact information is stored in a variable called ansible_facts.

Example

---
 - name: Ansible Playbook - Get facts 
   hosts: localhost

   tasks: 
   - name: Ansible-playbook will gather facts by default. The facts are stored in ansible_facts variable.
     debug:
      msg:
      - "{{ansible_facts }}"

The above playbook will print all ansible fact information like the setup command, but we do not need all this information, or we need a few details. To fetch the required details we must know the keys.

We can get the keys using two methods,

Run the ansible ad-hoc command

ansible localhost -m setup | grep ansible
ansible gather facts – ad-hoc command

As we can see from the above output, all variables are listed with the prefix ansible. We can directly use these variables in our playbook to fetch the specific fact information.

The second method is to run the setup command and then add an ansible prefix to the dictionary root keys.

ansible gather facts – default facts

As we can see from the ansible fact output we can select the key name and just add the prefix ansible to create the variable.

Example

---
 - name: Ansible Playbook - Get facts 
   hosts: localhost

   tasks: 
   - name: Ansible-playbook will gather facts by default. The facts are stored in ansible_facts variable.
     debug:
      msg:
      - "{{ansible_facts }}"

   - name: get indiviual tasks from the facts. 
     debug:
      msg:
      - "{{ansible_distribution}}"
      - "{{ansible_system}}"
      - "{{ansible_lsb['description']}}"
ansible gather facts – custom output