ansibleansible-facts

How to get just the version of the software when using ansible_facts.packages["zabbix-agent"]


I'm having an issue with using the package_facts module in Ansible. Basically, I just want to get the version of zabbix-agent installed as I need to do some stuff depending on which version is installed.

Now I got this in a playbook task:

- name: Gather Installed Packages Facts
  package_facts:
    manager: "auto"
  tags:
    - zabbix-check

- name: "Zabbix Found test result"
  debug: var=ansible_facts.packages['zabbix-agent']
  when: "'zabbix-agent' in ansible_facts.packages"
  tags:
    - zabbix-check

- name: "Zabbix Not-found test result"
  debug: 
    msg: "Zabbix NOT found"
  when: "'zabbix-agent' not in ansible_facts.packages"
  tags:
    - zabbix-check

Which spits out something like this:

ok: [vm3] => {
    "ansible_facts.packages['zabbix-agent']": [
        {
            "arch": "x86_64", 
            "epoch": null, 
            "name": "zabbix-agent", 
            "release": "1.el7", 
            "source": "rpm", 
            "version": "4.0.10"
    ]
}
ok: [vm4] => {
    "ansible_facts.packages['zabbix-agent']": [
        {
            "arch": "x86_64", 
            "epoch": null, 
            "name": "zabbix-agent", 
            "release": "1.el7", 
            "source": "rpm", 
            "version": "3.2.11"
        }
    ]
}

I want to get the value of that "Version": "3.2.11" so that I can store that in a variable and use that later. I've seen that post using yum and doing some json query but that won't work for me.


Solution

  • For some reason (probably because of more versions of the same package might be installed), the value of the package dictionary is a list. A simple solution is to take the first element

    - set_fact:
        za_ver: "{{ ansible_facts.packages['zabbix-agent'][0].version }}"
      when: "'zabbix-agent' in ansible_facts.packages"
    
    - set_fact:
        za_ver: "{{ ansible_facts.packages['zabbix-agent']|
                    map(attribute='version')|
                    list }}"
      when: "'zabbix-agent' in ansible_facts.packages"
    
    - set_fact:
        za_ver: "{{ ansible_facts.packages['zabbix-agent']|
                    json_query('[].version') }}"
      when: "'zabbix-agent' in ansible_facts.packages"