creating a csv for a package existing or not existing on remotes

I want to check whether a certain package is installed on a coupld of servers and create a csv-file from it

   sub1-rd1533.agrar.portal.local, python3-psycopg2 is missing
   sub1-rd5194.prod.eakte.rz-abc.local, python3-psycopg2 exists
   vm-414001-0251.step.zrz.abc.local, python3-psycopg2 exists

I though of using 'rpm -q <package_name>' and based on it's return code 0 or 1 print the corresponding message into my csv.

However the rpm -q <package_name> tasks simply fails on targets who do not have the package installed rather then registering the rc 1 and making it avaiable further down the playbook.

So I guess I am following the wrong approach. Can anybody kindly push be into the right direction?

==== THE Playbook =================================================

- name: check wheter packages exist
  hosts: "{{ targets | default ('postgres') }}"
  vars:
    package_names:
      - python3-psycopg2
  tasks:
    - name: "Check if listed package is installed or not"
      command: rpm -q "{{ item }}"
      loop: "{{ package_names }}"
      register: package_check

    - name: "Print success"
      debug:
        msg: "{{ package_names }} is installed"
      when: package_check is succeeded

    - name: "Print failure"
      debug:
        msg: "{{ package_names }} is not installed"
      when: package_check is failed

You can use package facts.

  • name: Gather the rpm package_facts

package_facts:

manager: auto

  • name: do something if package not installed

debug:

msg: ‘hey package is not installed’

when: “‘‘MyPackage’’ not in ansible_facts.packages”

  • name: do something if package is installed

debug:

msg: ‘Hey package is installed’

when: “‘‘MyPackage’’ in ansible_facts.packages”

You can use package facts.

  • name: Gather the rpm package_facts

package_facts:

manager: auto

  • name: do something if package not installed

debug:

msg: ‘hey package is not installed’

when: “‘‘MyPackage’’ not in ansible_facts.packages”

  • name: do something if package is installed

debug:

msg: ‘Hey package is installed’

when: “‘‘MyPackage’’ in ansible_facts.packages”