Search code examples
ansibleansible-facts

Conditional task if a variable is set


I have a playbook with the interpreter (ansible_python_interpreter) set manually.

Then I have 2 tasks (foo, bar) as an example.

I only want bar executed if the interpreter is set to python2. How can I make that happen?

hosts: "{{ ansible_limit | default (omit) }}"
  vars:
    ansible_python_interpreter: "/usr/bin/python3"
  tasks:
  - name: foo
    shell: /home/test/foo
  - name: bar
    shell: /home/test/bar

I tried when but did not get the access to the variable right I think.

when: ansible_python_interpreter.find('python2') != -1

Solution

  • The setup module provides you with the option to gather python_version

        - setup:
            gather_subset: python_version
        - debug:
            var: ansible_python_version
    

    gives for example,

      ansible_python_version: 3.8.18
    

    Then, test the version. For example,

        - debug:
            msg: foo
          when: ansible_python_version is version('3.8', '>')
        - debug:
            msg: bar
          when: ansible_python_version is version('3.8', '<')
    

    gives

      msg: foo
    

    Example of a complete playbook for testing

    - hosts: all
    
      vars:
    
        ansible_python_interpreter: /usr/local/bin/python3.8
    
      tasks:
    
        - setup:
            gather_subset: python_version
    
        - debug:
            var: ansible_python_version
    
        - debug:
            msg: foo
          when: ansible_python_version is version('3.8', '>')
    
        - debug:
            msg: bar
          when: ansible_python_version is version('3.8', '<')