Use ansible to get all the servers with specific package

509 views
Skip to first unread message

Jade Foram

unread,
Apr 29, 2021, 5:12:02 PM4/29/21
to Ansible Project
Is there way to find out all the servers that has specific package installed either via ansible command line or awx/tower similar to puppet pql query?

Komal Suthar

unread,
Apr 29, 2021, 9:43:55 PM4/29/21
to ansible...@googlegroups.com
- name: Gather the package facts
  ansible.builtin.package_facts:
    manager: auto

- name: Print the package facts
  ansible.builtin.debug:
    var: ansible_facts.packages

- name: Check whether a package called foobar is installed
  ansible.builtin.debug:
    msg: "{{ ansible_facts.packages['foobar'] | length }} versions of foobar are installed!"
  when: "'foobar' in ansible_facts.packages"
This module of package_facts can help you I guess

On Fri, Apr 30, 2021, 2:42 AM Jade Foram <foramg...@gmail.com> wrote:
Is there way to find out all the servers that has specific package installed either via ansible command line or awx/tower similar to puppet pql query?

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/eb73c820-d71b-47e2-ba32-ff6508d199e3n%40googlegroups.com.

Vladimir Botka

unread,
Apr 30, 2021, 12:52:32 AM4/30/21
to Jade Foram, ansible...@googlegroups.com
Yes. Use ansible.builtin.package_facts. As a hints, e.g. search Apache
2.4.27 at srv1 and srv2


- hosts: srv1,srv2
vars:
my_pkg: apache24
my_ver: 2.4.27
tasks:
- package_facts:
- set_fact:
my_pkgs: "{{ ansible_facts.packages|dict2items|
selectattr('key', 'eq', my_pkg)|
map(attribute='value')|
flatten }}"

gives

ok: [srv1] =>
my_pkgs:
- arch: i386
automatic: false
category: www
installed: '1501582995'
name: apache24
origin: unknown-repository
port_epoch: 0
prefix: /usr/local
revision: '0'
source: pkg
version: 2.4.27
vital: false
ok: [srv2] =>
my_pkgs:
- arch: amd64
automatic: false
category: www
installed: '1574925090'
name: apache24
origin: FreeBSD
port_epoch: 0
prefix: /usr/local
revision: '0'
source: pkg
version: 2.4.41
vital: false

Select the version and set the variable *mypkg_installed*

- debug:
msg: "{{ my_pkg }} {{ my_ver }} is installed."
when: my_pkgs|selectattr('version', 'eq', my_ver)|
list|length > 0
- set_fact:
mypkg_installed: "{{ my_pkgs|selectattr('version', 'eq',
my_ver)| list|length > 0 }}"

gives

ok: [srv1] =>
msg: apache24 2.4.27 is installed.
skipping: [srv2]


Put the results into the dictionary *mypkg_hosts*

- set_fact:
mypkg_hosts: "{{ dict(ansible_play_hosts_all|zip(_mypkg)) }}"
vars:
_mypkg: "{{ ansible_play_hosts_all|
map('extract', hostvars, 'mypkg_installed')|
list }}"
run_once: true

gives

mypkg_hosts:
srv1: true
srv2: false

--
Vladimir Botka
Reply all
Reply to author
Forward
0 new messages