How to filter gathering facts inside a playbook?
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
The Ansible way at the top of the playbook (Additional way):
----
- hosts: web
gather_facts: True
gather_subset:
- network
- virtual
Debug vars with:
- name: Print some debug information
vars:
msg: |
Module Variables ("vars"):
--------------------------------
{{ vars | to_nice_json }}
Environment Variables ("environment"):
--------------------------------
{{ environment | to_nice_json }}
GROUP NAMES Variables ("group_names"):
--------------------------------
{{ group_names | to_nice_json }}
GROUPS Variables ("groups"):
--------------------------------
{{ groups | to_nice_json }}
HOST Variables ("hostvars"):
--------------------------------
{{ hostvars | to_nice_json }}
debug:
msg: "{{ msg.split('\n') }}"
tags: debug_info
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:
- hosts: all
sudo: yes
gather_facts: False
pre_tasks:
- setup:
gather_subset: !facter,!ohai,network
roles:
- your_role_here