Site icon techbeatly

Managing Ansible Facts

Ansible facts are nothing but some variables which are automatically discovered by the Ansible on managed hosts while running ansible adhoc commands or playbooks.

See Automation with Ansible full chapters.

Ansible Facts Examples

Facts can be used to retrieve system status and take action based on the same. Eg: You can check available memory before installing a software.

Facts are collected via setup module, which will run automatically before the first task in a play; you can see this output as Gathering Facts tasks.

$ ansible servera -m setup

You can also filter facts as below to retrieve only required information.

$ ansible servera.lab.example.com -m setup -a 'filter=ansible_hostname'
servera.lab.example.com | SUCCESS => {
	"ansible_facts": {
    	"ansible_hostname": "servera"
	},
	"changed": false
}

You can also retrieve values as below,

ansible_default_ipv4[‘address’]
ansible_devices[‘vda’][‘partitions’][‘vda1’][‘size’]
ansible_fqdn
ansible_kernel                     # Running kernel version
ansible_interfaces                 # list of interfaces
ansible_dns.nameservers            # list of DNS servers

How to turn off Facts Gathering

If you are not using any facts variables, you can disable Gathering Facts as below.

- hosts: whatever
  gather_facts: no

And you can collect facts at anytime in the playbook by calling setup modules.

  tasks:
    - name: Collect Facts
      setup:

Custom Facts

We can configure custom facts inside the managed hosts and these facts will be retrieved by setup together with ansible facts. Custom facts can be used in managed hosts to control the play based on custom values.

You can setup local custom variables in facts.d directory – /etc/ansible/facts.d. If the directory doesn’t exist, create it. You can also use JSON format for custom facts files.

[root@servera ~]# mkdir /etc/ansible/facts.d -p
[root@servera ~]# cat >custom.facts
myname = localname
value2 = this is value 2

[database]
database_port = 3306

[packages]
db_package = mariadb-server

When Ansible run the setup module, custom facts will be retrieved under ansible_local variable. See examples below.

ansible_local['custom']['database']['database_port']   # this will be 3306
ansible_local['custom']['packages']['db_package']      # this will be mariadb-server

Magic Variables

There are some variables defined by Ansible which are called magic variables. Some examples below.

$ ansible servera.lab.example.com -m debug -a 'msg={{ groups }}'
servera.lab.example.com | SUCCESS => {
	"msg": {
    	"all": [
        	"servera.lab.example.com"
    	],
    	"ungrouped": [],
    	"webserver": [
        	"servera.lab.example.com"
    	]
	}
}

$ ansible servera.lab.example.com -m debug -a 'msg={{ groups.webserver }}'
servera.lab.example.com | SUCCESS => {
	"msg": [
    	"servera.lab.example.com"
	]
}

Refer : Special Variables Documentation

See Automation with Ansible full chapters.

Exit mobile version