updated: 12th of June 2019
published: 11th of June 2018
A collection of useful tips and tricks for Ansible which don't really justify a full blog post on their own. I'll keep updating this post when I come across something of value.
Convert the output of a playbook run to json. Either set the stdout_callback = json setting in the ansible.cfg or alternatively set the ANSIBLE_STDOUT_CALLBACK=json variable at the CLI on playbook execution.
ANSIBLE_STDOUT_CALLBACK=json ansible-playbook some-playbook.yml
create an ad-hoc inventory using the -i or --inventory flags. An ad-hoc inventory allows you to run ansible or ansible-playbook against a node (or list of nodes) without creating an inventory file.
ansible-playbook -i myhost,<another-host> all -a 'uname -a'
Credit: https://gist.github.com/alces/f7e3de25d98a19550a4e4f97cabc2cf4
There is a fair bit of boilerplate involved in creating a role. There is an ansible-galaxy command to aid in the process of building a role. Optionaly add the --offline flag if the role is not intended for Ansible galaxy.
ansible-galaxy init role-name --offline
# output
- role-name was created successfully
# role-name directory contents
role-name/
├── defaults
│ └── main.yml
├── files
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── README.md
├── tasks
│ └── main.yml
├── templates
├── tests
│ ├── inventory
│ └── test.yml
└── vars
└── main.yml
8 directories, 8 files
Credit: https://docs.ansible.com/ansible/latest/reference_appendices/galaxy.html#create-roles
Get a json dict of all vars that will be applicable to a host at playbook runtime. The following command also shows you which groups a host belongs to and all groups that are available.
ansible -i inventory a.example.com -m debug -a "var=hostvars[inventory_hostname]"
# output
a.example.com | success >> {
"var": {
"hostvars": {
"ansible_ssh_host": "10.0.0.1",
"ansible_ssh_user": "user",
"group_names": [
"group1",
"groups"
],
"groups": {
"all": [
"x.example.com",
"y.example.com",
"a.example.com",
"b.example.com"
],
"group1": [
"a.example.com"
],
"group2": [
"b.example.com"
],
"groups": [
"a.example.com",
"b.example.com"
],
"ungrouped": [
"x.example.com",
"y.example.com"
]
},
"inventory_hostname": "a.example.com",
"inventory_hostname_short": "a"
}
}
}
Credit: https://unix.stackexchange.com/a/208854/294891
Find the source file that a variable was derived from. This is quite useful when you are using the Ansible variable precedence system to see which file a variable actually came from.
ansible -i inventory leaf01 -m debug -a "var=hostvars[inventory_hostname]['bgp']['asn']._data_source"
# output
leaf01 | SUCCESS => {
"hostvars[inventory_hostname]['bgp']['asn']._data_source": "/path/to/host_vars/leaf01.yml"
}
Credit: https://twitter.com/codethenetwork/status/936733364089794560