How to use multiple filter in setup module

1,730 views
Skip to first unread message

Vikrant Agarwal

unread,
Jan 2, 2020, 5:57:22 AM1/2/20
to Ansible Project
I want to extract only specific information of the systems using Ansible setup module , like  ansible_memtotal_mb , ansible_machine and ansible_distribution_version .  How to do that in single ansible command ? 

Regards
Vikrant

Vladimir Botka

unread,
Jan 2, 2020, 6:45:13 AM1/2/20
to Vikrant Agarwal, ansible...@googlegroups.com
It's possible to 'loop' the 'filter' in the module 'setup'
https://docs.ansible.com/ansible/latest/modules/setup_module.html

For example:

- hosts: test_01
gather_facts: false
tasks:
- setup:
filter: "{{ item }}"
loop:
- 'ansible_memtotal_mb'
- 'ansible_machine'
- 'ansible_distribution_version'
- debug:
var: hostvars.test_01.ansible_facts

gives

ok: [test_01] =>
hostvars.test_01.ansible_facts:
distribution_version: '12.0'
machine: i386
memtotal_mb: 3400

It's not possible to create single 'filter' because of the limited
functionality of 'fnmatch', I think
https://docs.python.org/3.8/library/fnmatch.html

HTH,

-vlado

Vladimir Botka

unread,
Jan 2, 2020, 7:07:06 AM1/2/20
to Vikrant Agarwal, ansible...@googlegroups.com
On Thu, 2 Jan 2020 12:45:01 +0100
Vladimir Botka <vbo...@gmail.com> wrote:

> On Thu, 2 Jan 2020 02:57:22 -0800 (PST)
> Vikrant Agarwal <vikranta...@gmail.com> wrote:
>
> > I want to extract only specific information of the systems using Ansible
> > setup module , like ansible_memtotal_mb , ansible_machine
> > and ansible_distribution_version . How to do that in single ansible
> > command ?

> It's possible to 'loop' the 'filter' in the module 'setup'
> https://docs.ansible.com/ansible/latest/modules/setup_module.html
>
> - hosts: test_01
> gather_facts: false
> tasks:
> - setup:
> filter: "{{ item }}"
> loop:
> - 'ansible_memtotal_mb'
> - 'ansible_machine'
> - 'ansible_distribution_version'
> - debug:
> var: hostvars.test_01.ansible_facts

FWIW. Smarter approach to avoid the burden of collecting the facts on each
play is 'Caching facts'
https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#caching-facts

HTH,

-vlado

Brian Coca

unread,
Jan 13, 2020, 9:51:11 AM1/13/20
to Ansible Project, Vikrant Agarwal
FYI, filter does not prevent gathering of other facts, it just filters
the result, running in loop gathers facts multiple times, it is much
more efficient to gather 1 time and then extract the subset you
desire.


--
----------
Brian Coca

Reply all
Reply to author
Forward
0 new messages