Ansible - Facts
Facts:
- Usually gathered by the setup module
- All facts are in this var: ansible_facts
- Some facts are injected as top level variables starting with ansible_
Show all facts available:
- debug: var=ansible_facts
See raw gathered info:
ansible hostname -m setup
Hostname as reported by the system:
{{ ansible_facts['nodename'] }}
Disable facts gathering ( probably faster ):
- hosts: whatever
gather_facts: no
tasks:
....
Some common facts:
tasks:
- debug: var=ansible_facts['distribution']
- debug: var=ansible_facts['distribution_major_version']
- debug: var=ansible_facts['os_family']
- debug: var=ansible_facts['all_ipv4_addresses']
- debug: var=ansible_facts['default_ipv4']
- debug: var=ansible_facts['env']
- debug: var=ansible_facts['hostname']
- debug: var=ansible_facts['interfaces']
- debug: var=ansible_facts['kernel']
Facts from Other Hosts
Access fact from other host:
{{ hostvars['asdf.example.com']['ansible_facts']['os_family'] }}
For this to work, need to:
- Enable fact caching
- Access the other host previously in the playbook
Example using jsonfile:
ansible.cfg
[defaults]
gathering = smart
fact_caching = jsonfile
fact_caching_connection = /path/to/cachedir
fact_caching_timeout = 86400
# seconds
- “To benefit from cached facts, you will want to change the gathering setting to smart or explicit or set gather_facts to False in most plays.”
- Cache plugins: redis or jsonfile
- fact_caching_timeout - how long to cache the facts
Custom Defined - facts.d
- fact_path - can be set for alternate path
Facts can also be supplied by files that:
- are in /etc/ansible/facts.d
- end in ‘.fact’
- are JSON, INI, or executable returning JSON
Example hash variable:
/etc/ansible/facts.d/preferences.fact
[general]
asdf=1
bar=2
Check it:
ansible host1 -m setup -a "filter=ansible_local"
"ansible_local": {
"preferences": {
"general": {
"asdf" : "1",
"bar" : "2"
}
}
}
Use stuff from facts.d like this:
{{ ansible_local['preferences']['general']['asdf'] }}