Ansible variables and facts
209 words
Table of Contents
Variables #
Tip
avoid using variables in inventory
Example in a playbooks:
- hosts: all
vars:
foo: bar
Example in a playbooks for external file:
- hosts: all
vars_files:
- vars/common.yml
Example in inventory:
[lala]
server1
[lala:vars]
user=joe
- the directories group_vars and host_vars in the same directory as the inventory file or directory are implicitly sourced.
- bracket notation is preferred above dot notation to avoid confusion to methods or attributes.
animal:
pike:
class: fish
legs: no
wolf:
class: canine
legs: yes
animal.pike.class --> 'fish'
better: animal['pike']['class']
Facts #
Disable the use of facts #
Example:
---
- name:
gather_facts: no
...
Note
Don’t disable unless you have performance issues.
# ansible 10.0.0.90 -m setup -a 'filter=ansible_fqdn'
10.0.0.90 | SUCCESS => {
"ansible_facts": {
"ansible_fqdn": "heimdall.doubtfull.snd"
},
"changed": false
}
Add facts to a system #
File /etc/ansible/facts.d/system.fact
[system_responsiblity]
gateway = true
# ansible 10.0.0.170 -m setup -a 'filter=ansible_local'
10.0.0.170 | SUCCESS => {
"ansible_facts": {
"ansible_local": {
"system": {
"system_responsiblity": {
"gateway": "true"
}
}
}
},
"changed": false
}
Query based on fact #
# ansible webserver -m setup -a 'filter=ansible_user*'
servera.lab.example.com | SUCCESS => {
"ansible_facts": {
"ansible_user_dir": "/root",
"ansible_user_gecos": "root",
"ansible_user_gid": 0,
"ansible_user_id": "root",
"ansible_user_shell": "/bin/bash",
"ansible_user_uid": 0,
"ansible_userspace_architecture": "x86_64",
"ansible_userspace_bits": "64"
},
"changed": false
}