Check if a package (RPM) is installed in a certain version

Hi,

I’m currently writing a playbook for a workstation running Rocky Linux, and I can’t figure out one detail.

I want to add a line to a file (yum.conf) only when the vagrant package is installed in version 2.4.1. I know I have to use the package_facts module to do this. I’ve spent a couple hours banging my head on the keyboard trying out various syntaxes, but nothing works. So here’s in plain words what I have to do:

If the vagrant package is installed and its version is 2.4.1 then add the line exclude=vagrant to the /etc/yum.conf file.

Any suggestions ?

I could suggest how to do this for Debian / Ubuntu… what does the package_facts output look like on a RedHat based system?

1 Like

This is the output of package_facts:

localhost | SUCCESS => {
    "ansible_facts": {
        "packages": {
            "aardvark-dns": [
                {
                    "arch": "x86_64",
                    "epoch": 2,
                    "name": "aardvark-dns",
                    "release": "1.el9_5",
                    "source": "rpm",
                    "version": "1.12.2"
                }
            ],
            "acl": [
                {
                    "arch": "x86_64",
                    "epoch": null,
                    "name": "acl",
                    "release": "4.el9",
                    "source": "rpm",

So I’ m guessing you just have to do:

- name: Insert line in yum.conf
  ansible.builtin.lineinfile:
    line: exclude=vagrant
    path: /etc/yum.conf
  when: ansible_facts.packages.vagrant.release == '2.4.1' 

type or paste code here
4 Likes

Here’s the code I used for testing:

- name: Gather package facts
  ansible.builtin.package_facts:
    manager: rpm

- name: Print Vagrant package facts
  ansible.builtin.debug:
    var: ansible_facts.packages['vagrant']

And here’s the output:

TASK [apps_vagrant : Print Vagrant package facts] ******************************
ok: [localhost] => {
    "ansible_facts.packages['vagrant']": [
        {
            "arch": "x86_64",
            "epoch": 0,
            "name": "vagrant",
            "release": "1",
            "source": "rpm",
            "version": "2.4.1"
        }
    ]
}

@hugonz 's answer is good, just two more thoughts, older versions of Ansible would error if ansible_facts.packages.vagrant.release was not defined and if you wanted to check for vagrant version 2.4.1 or above you could also add in use of the ansible.builtin.version test:

- name: Insert line in yum.conf
  ansible.builtin.lineinfile:
    line: exclude=vagrant
    path: /etc/yum.conf
  when:
    - ansible_facts.packages.vagrant.release is defined
    - ansible_facts.packages.vagrant.release is ansible.builtin.version('2.4.1', '>=')"
1 Like