I'm working on a role that only needs to gather a single fact.
Performance it's a concern and I know that gathering facts it's time-consuming.
I'm looking for some way to filter gather_facts
inside a playbook, this will allow me to gather only the required facts.
This is possible using the setup core module:
ansible -m setup -a 'filter=ansible_hostname' my_host
10.200.0.127 | success >> {
"ansible_facts": {
"ansible_hostname": "my_host"
},
"changed": false
}
It's possible to use this feature inside the playbook? Something like this?
- hosts: all
sudo: yes
gather_facts: True
filter: "filter=ansible_*"
PS: The code above throws syntax exception.
EDIT 1: If someone needs to get hostname there's also another useful variable inventory_hostname.
The Ansible way at the top of the playbook (Additional way):
Debug vars with:
Yes, that's possible, but not in the default behavior of gathering facts. Having set
gather_facts
totrue
simply calls the setup module as very first task of the play. This way you do not have any way to parameterize thesetup
module call.But you can disable the default behavior and call setup yourself with the filter parameter.
Since you're working on a role and might not want to have this setup call in your role, you could make use of pre_tasks.
After this question was asked and answered, Ansible 2.1 added the
gather_subset
option to the setup module so its now possible to use the!facter,!ohai,network
syntax described in the documentation rather than a regex filter:If all you're interested in is the hostname of each host then simply doing something like this should do what you need:
If it's some other fact that you're interested in then just specify the appropriate command, and refer to the fact via the registered variable.