Check Ansible version from inside of a playbook

The correct way to compare ansible version inside a playbook looks like

- hosts: all
  tasks:
    - name: foo
      when: "ansible_version.full is version_compare('2.11', '>=')"
      ...

Do not use string comparison or you will be surprised that it does not work as expected.


You can use the assert module:

- assert:
    that: ansible_version.major < 2

Ansible provides a global dict called ansible_version, dict contains the following

"ansible_version": {
        "full": "2.7.4", 
        "major": 2, 
        "minor": 7, 
        "revision": 4, 
        "string": "2.7.4"
    }

you can use any of the following ansible_version.full, ansible_version.major or any other combination in creating conditional statements to check the version of ansible that's installed.

example playbook: using this dict and a when statement.

---
- hosts: localhost
  tasks:

    - name: Print message if ansible version is greater than 2.7.0
      debug:
        msg: "Ansible version is  {{ ansible_version.full }}"
      when: ansible_version.full >= "2.7.4"