Question:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
- 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
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.
Answer:
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
1 2 3 4 |
- set_fact: za_ver: "{{ ansible_facts.packages['zabbix-agent'][0].version }}" when: "'zabbix-agent' in ansible_facts.packages" |
To take into the account the possibility of more versions installed, use map filter
1 2 3 4 5 6 |
- set_fact: za_ver: "{{ ansible_facts.packages['zabbix-agent']| map(attribute='version')| list }}" when: "'zabbix-agent' in ansible_facts.packages" |
Below is the equivalent with json_query filter
1 2 3 4 5 |
- set_fact: za_ver: "{{ ansible_facts.packages['zabbix-agent']| json_query('[].version') }}" when: "'zabbix-agent' in ansible_facts.packages" |