'How can I get the installed apt packages with Ansible?

I am trying to list all installed packages on my Debian 7 (Wheezy), 8 (Jessie), and 9 (Stretch) machines. There are easy ways dealing with it using APT or dpkg, but I could not find a proper way to do this with Ansible out of the box.

Is there a nice and smooth way to do this?

For RHEL machines I found this post: How can I get the installed YUM packages with Ansible?



Solution 1:[1]

It doesn't look like Ansible provides any modules that would support this. You'll have to use shell or command.

- name: Get packages
  shell: dpkg-query -f '${binary:Package}\n' -W
  register: packages

- name: Print packages
  debug:
    msg: "{{ packages.stdout_lines }}" 

Solution 2:[2]

Since Ansible 2.5 you can use the package_facts module: ansible.builtin.package_facts module – Package information as facts

- name: Gather package facts
  package_facts:
    manager: auto

- name: Debug if package is present
  debug:
    msg: 'yes, mypackage is present'
  when: '"mypackage" in ansible_facts.packages'

- name: Debug if package is absent
  debug:
    msg: 'no, mypackage is absent'
  when: '"mypackage" not in ansible_facts.packages'

Mind you, you need the ansible-apt module on Debian for that (which is kindly provided by bootstrap).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kfreezy
Solution 2 Peter Mortensen