Access ansible facts variable?

Hi,

I’m currently writing an Ansible playbook, and I can’t seem to wrap my head around one small problem.

I’m trying to check if the vagrant package is installed in version 2.4.1. As far as I can tell, I need the package_facts module to do this.

I’m testing this in my playbook like this:

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

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

When I run the playbook, this is 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"
        }
    ]
}

Now here’s the question: how do I access only the version? I tried ansible_facts.packages['vagrant'].version, ansible_facts.packages.vagrant.version and some other combinations, but all I get is VARIABLE IS NOT DEFINED. I guess this is a no-brainer, but I’m stuck anyway.

Any suggestions ?

I think you miss the index (0) of that entry …

1 Like

This works, but more generally how would I perform the following task?

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.

The package_facts module works in a rather quirky way.

  - name: Print vagrant package version
    ansible.builtin.debug:
      var: ansible_facts.packages['vagrant'][0].version
    when:
    - ansible_facts.packages['vagrant'] is defined
    - ansible_facts.packages['vagrant'][0].version == '2.4.1'

You have to replace the debug with lineinfile or whatever.

IF ansible_facts.packages[‘vagrant’] is defined
THEN there is at least one dict in the list that has attribute version
(The installonly packages, like kernel can have more than just one entry.)

The

when:
- A
- B

is essentially IF A AND B

The AND is lazy like in C/C++, if A is false, then B is not evaluated and result is false.