Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter gathering facts inside a playbook?

Tags:

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.

like image 243
Bernardo Vale Avatar asked Dec 27 '15 22:12

Bernardo Vale


1 Answers

Yes, that's possible, but not in the default behavior of gathering facts. Having set gather_facts to true simply calls the setup module as very first task of the play. This way you do not have any way to parameterize the setup module call.

But you can disable the default behavior and call setup yourself with the filter parameter.

- hosts: all   sudo: yes   gather_facts: False   tasks:    - setup:        filter: ansible_* 

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.

- hosts: all   sudo: yes   gather_facts: False   pre_tasks:    - setup:        filter: ansible_*   roles:    - your_role_here 
like image 123
udondan Avatar answered Sep 25 '22 06:09

udondan