Ansible Version Comparison: Compare Versions with version Test
By Luca Berton · Published 2024-01-01 · Category: installation
How to compare versions in Ansible using the version test. Compare software versions, semantic versioning, strict/loose modes with conditional examples.

As your IT infrastructure grows and evolves, it can become increasingly difficult to ensure consistency across all your systems and applications. One way to address this challenge is using configuration management tools like Ansible to automate tasks such as version comparison and updates. This article will explore how to use Ansible to compare versions and ensure consistency across your infrastructure.
What is Ansible?
Ansible is an open-source tool that automates IT tasks such as configuration management, application deployment, and orchestration. It uses a simple language called YAML to describe configuration and automation tasks, making it easy for developers and system administrators to learn and use.See also: Creating a Custom Ansible Lookup Plugin in Python for Reading a File
Comparing Versions with Ansible
One common task in IT infrastructure management is ensuring that all systems and applications run the same software version. This can be time-consuming and error-prone, especially as the number of systems and applications in your infrastructure grows.Fortunately, Ansible makes it easy to automate version comparison and ensure consistency across your infrastructure. The code snippet provided above Playbooknstrates how to use Ansible to compare the version of Ansible installed on all hosts with the specified version “2.15”.
This code uses the “ansible.builtin.version” filter to compare the installed version with the specified version and then returns a boolean value indicating whether the installed version is greater than or equal to the specified version. If the installed version is less than “2.15”, the debug message will return “False”, and you can use this information to trigger an update to the latest version of Ansible.
Benefits of Using Ansible for Version Comparison
Using Ansible to automate version comparison and updates has several benefits, including: • Increased consistency: Automating version comparison and updates ensures that all systems and applications are running the same software version, which can help prevent compatibility issues and reduce the risk of security vulnerabilities. • Time savings: Automating version comparison and updates can save time by reducing the amount of manual effort required to ensure consistency across your infrastructure. • Improved accuracy: Automating version comparisons and updates can reduce the risk of errors when performing these tasks manually. • Scalability: Ansible is designed to be scalable, so you can easily manage version comparison and updates across many systems and applications.See also: Creating a Custom Ansible Lookup Plugin in Python for retrieving API token
Links
• https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_tests.html#comparing-versions • https://docs.ansible.com/ansible/latest/collections/ansible/builtin/version_test.htmlDemo
This Ansible playbook will compare the version of Ansible installed on all hosts with the specified version “2.15” using the “version” filter and return a boolean value indicating whether the installed version is greater than or equal to the specified version.If the installed version of Ansible is greater than or equal to “2.15”, the debug message will return “True”. If the installed version is less than “2.15”, the debug message will return “False”.
Note that this playbook will run on all hosts specified in the Ansible inventory. If you only want to run it on a specific host or group of hosts, you will need to modify the “hosts” line accordingly.
Code
• versin.yml---
- name: Versions compare
hosts: all
tasks:
- name: Print Ansible Version
ansible.builtin.debug:
var: ansible_version.full
- name: Compare Versions
ansible.builtin.debug:
msg: "Version correct!"
when: ansible_version.full is version('2.15', '>=')
• inverntory
localhost ansible_connection=local
Execution Ansible 2.14
ansible-playbook -i inventory version.yml
PLAY [Versions compare] *****************************************************************
TASK [Gathering Facts] ******************************************************************
ok: [localhost]
TASK [Print Ansible Version] ************************************************************
ok: [localhost] => {
"ansible_version.full": "2.14.4"
}
TASK [Compare versions] *****************************************************************
skipping: [localhost]
PLAY RECAP ******************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
Execution Ansible 2.15
ansible-playbook -i inventory version.yml
PLAY [Versions compare] *****************************************************************
TASK [Gathering Facts] ******************************************************************
ok: [localhost]
TASK [Print Ansible Version] ************************************************************
ok: [localhost] => {
"ansible_version.full": "2.15.0b3"
}
TASK [Compare versions] *****************************************************************
ok: [localhost] => {
"msg": "Version correct!"
}
PLAY RECAP ******************************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
See also: Create Custom Ansible Modules: Python Module Development Guide
Conclusion
Using Ansible to compare versions and ensure consistency across your infrastructure is a powerful way to automate IT tasks and reduce the risk of errors and inconsistencies. By leveraging the power of automation, you can save time and increase accuracy while ensuring that all systems and applications in your infrastructure are running the latest software versions.
Basic Version Comparison
- debug: msg="Python 3.10+"
when: ansible_python_version is version('3.10', '>=')
- debug: msg="Ubuntu 22.04+"
when: ansible_distribution_version is version('22.04', '>=')
Operators
| Operator | Meaning |
|----------|---------|
| < / lt | Less than |
| <= / le | Less than or equal |
| > / gt | Greater than |
| >= / ge | Greater than or equal |
| == / eq | Equal |
| != / ne | Not equal |
Check Package Version
- ansible.builtin.package_facts:
- debug: msg="OpenSSL is recent enough"
when: >
ansible_facts.packages['openssl'] is defined
and ansible_facts.packages['openssl'][0].version is version('3.0', '>=')
Conditional Install/Upgrade
- name: Get current version
command: /opt/myapp/bin/app --version
register: current_version
changed_when: false
failed_when: false
- name: Upgrade if outdated
block:
- get_url:
url: "https://releases.example.com/app-{{ target_version }}.tar.gz"
dest: /tmp/app.tar.gz
- unarchive:
src: /tmp/app.tar.gz
dest: /opt/myapp
remote_src: true
when: >
current_version.rc != 0
or current_version.stdout | trim is version(target_version, '<')
become: true
Strict vs Loose Comparison
# Loose (default) - handles varied formats
when: version is version('2.0', '>=')
# Works with: "2.0", "2.0.0", "2.0.0-beta1"
# Strict - requires proper semver
when: version is version('2.0.0', '>=', strict=true)
# Fails on: "2.0" (not proper semver)
Version Ranges
# Between two versions
- debug: msg="Compatible version"
when:
- app_version is version('2.0', '>=')
- app_version is version('3.0', '<')
# Multiple version checks
- set_fact:
python_ok: "{{ ansible_python_version is version('3.8', '>=') }}"
os_ok: "{{ ansible_distribution_version is version('20.04', '>=') }}"
- fail: msg="Requirements not met"
when: not (python_ok and os_ok)
OS-Specific Logic
- name: Use new config format
template:
src: "{{ 'new' if ansible_distribution_version is version('24.04', '>=') else 'legacy' }}.conf.j2"
dest: /etc/myapp/config.conf
- name: Platform-specific package
apt:
name: "{{ 'python3-venv' if ansible_distribution_version is version('22.04', '>=') else 'python3.8-venv' }}"
become: true
In Templates
{% if ansible_distribution_version is version('22.04', '>=') %}
# Modern Ubuntu config
ssl_protocols TLSv1.3;
{% else %}
# Legacy config
ssl_protocols TLSv1.2 TLSv1.3;
{% endif %}
FAQ
What versioning scheme is used?
Default uses LooseVersion (flexible, handles most formats). strict=true uses StrictVersion (requires X.Y.Z format).
Can I compare Ansible version itself?
when: ansible_version.full is version('2.15', '>=')
How do I extract version from command output?
- command: nginx -v
register: nginx_out
- set_fact:
nginx_version: "{{ nginx_out.stderr | regex_search('nginx/([\\d.]+)', '\\1') | first }}"
Basic Version Comparison
- debug:
msg: "Version is new enough"
when: ansible_distribution_version is version('22.04', '>=')
Comparison Operators
# All operators
when: my_version is version('2.0', '>') # Greater than
when: my_version is version('2.0', '>=') # Greater or equal
when: my_version is version('2.0', '<') # Less than
when: my_version is version('2.0', '<=') # Less or equal
when: my_version is version('2.0', '==') # Equal
when: my_version is version('2.0', '!=') # Not equal
Strict vs Loose Mode
# Strict — requires valid semantic versioning (X.Y.Z)
when: app_version is version('2.1.0', '>=', strict=true)
# Loose (default) — handles irregular version strings
when: app_version is version('2.1', '>=', strict=false)
Real-World Examples
# Conditional package installation
- apt:
name: python3.12
when: ansible_distribution_version is version('24.04', '>=')
# Feature gating
- include_tasks: new-features.yml
when: app_version is version('3.0.0', '>=', strict=true)
# Deprecation warnings
- debug:
msg: "WARNING: Version {{ app_version }} is deprecated. Upgrade to 2.0+"
when: app_version is version('2.0', '<')
Compare ansible-core Version
- debug:
msg: "Using modern Ansible"
when: ansible_version.full is version('2.15', '>=')
Version Range Check
- debug:
msg: "Version {{ ver }} is in supported range"
when:
- ver is version('2.0', '>=')
- ver is version('3.0', '<')
Compare from Command Output
- command: nginx -v
register: nginx_out
changed_when: false
- set_fact:
nginx_version: "{{ nginx_out.stderr | regex_search('nginx/([\\d.]+)', '\\1') | first }}"
- debug:
msg: "Nginx {{ nginx_version }} supports HTTP/2"
when: nginx_version is version('1.9.5', '>=')
FAQ
When to use strict mode?
When comparing properly formatted semver strings (e.g., 1.2.3). Loose mode handles formats like 2.1, v3.0-beta, 20240101.
Can I compare dates as versions?
Yes with loose mode: '20260407' is version('20260101', '>') works.
version vs version_compare?
version_compare is deprecated. Always use version.
Related Articles
• multi-condition Ansible when clauses • organizing hosts with Ansible inventory • become and privilege escalation explained • managing AWS resources via AnsibleCategory: installation
Watch the video: Ansible Version Comparison: Compare Versions with version Test — Video Tutorial