how to use conditional statement in main.yml in ansible roles

338 Views Asked by At

I wanna apply role using conditional statement by centos version(7, 8) in yml

There are tons of examples of conditional statement in the playbook.

However, there seems to be no example of yml to be used in role.

As in the example below I tried to use a conditional statement by got an error.

[main.yml]
    - name: example1
      yum:
        name: "{command1}"
      become: yes
      when:
        - ansible_os_family | lower == "centos"
        - ansible_distribution_major_version == "7"
    
    - name: example2
      yum:
        name: "{command2}"
      become: yes
      when:
        - ansible_os_family | lower == "rocky"
        - ansible_distribution_major_version == "8"

error

The error was: error while evaluating conditional (ansible_os_family | lower == \"centos\"): 'ansible_os_family' is undefined\n\nThe error appears to have been in main.yml

In this case, is there a way to solve it using yml in roles?

1

There are 1 best solutions below

0
Kevin C On

The following should work, ensure to gather facts on play level.

---
- hosts: my_host
  become: true
  gather_facts: true
  tasks:
    - name: install yum package for el-7
      yum:
        name: pkg
      when:
        - ansible_os_family | lower == "centos"
        - ansible_distribution_major_version == "7"
    
    - name: install yum package for el-8
      yum:
        name: package
      when:
        - ansible_os_family | lower == "rocky"
        - ansible_distribution_major_version == "8"

Your statement, ansible_os_family | lower == "rocky" is correct and should work.