-1

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?

S.Kang
  • 581
  • 2
  • 10
  • 28
  • 1
    Idk, did the variable change? What is your Ansible version? https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_conditionals.html#ansible-facts-os-family – Kevin C Dec 27 '22 at 09:30
  • 2
    Also, why are you using xml? The playbook is written in yml, not xml. – Kevin C Dec 27 '22 at 09:34
  • The variable comes in jinja expression . "{{ ansible_os_family }}" and "{{ ansible_distribution_major_version }}" will work – isilia Dec 27 '22 at 10:04
  • @isilia, no, `when` expression should [**never ever be templated**](https://stackoverflow.com/questions/42673045/ansible-when-statements-should-not-include-jinja2-templating-delimiters). – β.εηοιτ.βε Dec 27 '22 at 14:14
  • @KevinC the version is ansible 2.7.5 and What I wanted to say is yml, but I wrote it wrongly as xml. The above has been corrected. – S.Kang Dec 28 '22 at 10:22

1 Answers1

1

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.

Kevin C
  • 4,851
  • 8
  • 30
  • 64