Search code examples
ansibleansible-2.x

Is there a way to create different repository based on a condition in the same task in Ansible playbook?


I am trying to shorten the number of tasks I have in my playbook. I am creating a yum repository on Linux hosts and adding a different baseurl depending on the OS version.

It looks like this:

vars:
  my_version: "{{ hostvars[inventory_hostname].ansible_distribution | int }}"
    
    
- name: create mcrepo yum repo
  yum_repository:
    name: mcrepo
    description: mcrepo
    baseurl: "{{ yum_repo_url }}"
    gpgcheck: no
    enabled: yes
    sslverify: no
  when: my_version is version('8.0', operator='lt')
 
  
- name: create mcrepo yum repo
  yum_repository:
    name: mcrepo
    description: mcrepo
    baseurl: "{{ yum_repo_url_8 }}"
    gpgcheck: no
    enabled: yes
    sslverify: no
  when: my_version is version('8.0', operator='ge')

Is there a way to combine these two tasks into just one so one of them doesn't always get skipped? On the linux hosts I have ansible 2.9 or 2.10.
I couldn't find a way to implement a case statement or something similar.


Solution

  • You could use an inline if in order to get the right variable containing the yum repository URL:

    baseurl: >-
      {{ 
        yum_repo_url 
         if my_version is version('8.0', operator='lt') 
         else yum_repo_url_8
      }}