Issue
I want to run similar commands on Linux mint and Ubuntu but they have small differences. I found a solution but it makes me rewrite each task twice. Is there a better way to do that?
- name: install the latest version of Ansible
block:
- name: Add Ansible PPA (Ubuntu)
ansible.builtin.apt_repository:
repo: ppa:ansible/ansible
become: true
when: ansible_facts['distribution'] == 'Ubuntu'
- name: Add Ansible PPA (Linux Mint)
ansible.builtin.apt_repository:
repo: ppa:ansible/ansible
codename: focal
become: true
when: ansible_facts['distribution'] == 'Linux Mint' and ansible_distribution_release == 'una'
- name: install Ansible and dependency
apt:
name:
- software-properties-common
- ansible
state: latest
update_cache: yes
become: true
Solution
One way to do this is to use the omit
filter. See the documentation. This can be used to make the codename
parameter optional when running the apt_repository
module.
Example:
- name: set distro codename when OS is Linux Mint
ansible.builtin.set_fact:
distro_codename: focal
when: ansible_facts['distribution'] == 'Linux Mint' and ansible_distribution_release == 'una'
- name: Add Ansible PPA
ansible.builtin.apt_repository:
repo: "ppa:ansible/ansible"
codename: "{{ distro_codename | default(omit) }}"
This will ensure that the codename
is used while creating APT repository if it is set (for Linux Mint in this case). Otherwise it will be omitted.
Answered By - seshadri_c Answer Checked By - Dawn Plyler (WPSolving Volunteer)