Use Ansible to get OS package version (even with a dash)

Ansible package version (Ansible Logo)

Getting an OS package version using Ansible seems like a simple thing to do, except it’s not simple when there’s a dash in the package name. This approach will always work, even for packages with a dash in the name.

Get the OS package version using Ansible

This is using the builtin Ansible module: package_facts.

The example will get the version of the OS package “haproxy”, even if it has a dash. And the template file has logic to use certain configuration if the version of the OS package is greater or equal to version “2.0”. If the version is less than 2.0, then the older configuration will be used.

Example Ansible task:

# tasks/main.yml

- name: Gather the OS package facts
package_facts:
manager: auto
tags:
- always

- name: show package version (RHEL 7)
debug:
# This doesn't work. Doesn't work with a dash in the name
# var: ansible_facts.packages.rh-haproxy18-haproxy.version
var: ansible_facts.packages | json_query('"rh-haproxy18-haproxy"[*].version') | join(' ')
when:
- ansible_os_family == "RedHat"
- ansible_distribution_major_version | int == 7
tags:
- always

- name: Set fact for haproxy version (RHEL 7)
set_fact:
stat_install_haproxy_haproxy_version: "{{ ansible_facts.packages | json_query('\"rh-haproxy18-haproxy\"[*].version') | join(' ') }}"
when:
- ansible_os_family == "RedHat"
- ansible_distribution_major_version | int == 7
- ansible_facts.packages | json_query('"rh-haproxy18-haproxy"[*].version') | join(' ') is defined
tags:
- always

- name: install-haproxy | show haproxy version
debug: var=stat_install_haproxy_haproxy_version
tags:
- always

- name: Generate haproxy config (RHEL7)
template:
src: templates/haproxy.cfg.j2
dest: "{{ install_haproxy_config_dir }}/haproxy.cfg"
validate: haproxy -f %s -c -q
environment:
PATH: "/usr/sbin:/usr/local/sbin:/sbin:{{ install_haproxy_bin_dir }}"
notify:
- reload haproxy
when:
- ansible_os_family == "RedHat"
- ansible_distribution_major_version | int == 7
tags:
- config

And then a template file which applies different configuration options depending on the package version.

Example Ansible template file:

# templates/haproxy.cfg.j2

# {{ ansible_managed | comment }}

{% if stat_install_haproxy_haproxy_version is version('2.0', '>=') %}
config here only for version greater or equal to 2.0
{% else %}
config here for version less than 2.0
{% endif %}

# {{ ansible_managed | comment }}

The above example isn’t complete, some variables need to be defined. But you get the idea.

Conclusion

That’s it. Not exactly straight forward, but the example above should be enough to understand how to accomplish getting an OS package version using Ansible. This even works when there is a dash in the package name.

Want another interesting Ansible example? Check out How to add an Inline Comment using Ansible.