Include default variables based on conditions

Hi,

I’m using and help maintaining the role GitHub - riemers/ansible-gitlab-runner: Ansible role to install gitlab-runner

In this role, there in one defaults/main.yml which defines a few good general default values. Additionally, there is this:

- name: Load platform-specific variables
  ansible.builtin.include_vars: "{{ lookup('first_found', possible_files) }}"
  vars:
    possible_files:
      files:
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - default.yml
      paths:
        - vars

which picks then a file out of those:

  • Archlinux.yml
  • Darwin.yml
  • Debian.yml
  • RedHat.yml
  • Windows.yml
  • default.yml

The problem we have is, that variables of the presented list cannot be overwritten then in the playbook, because they are imported with include_vars what has very high precedence.

What we want to archive is, including defaults/main.yml for basic vars and including the platform specific vars but also as “default” vars, to allow all variables to be overwritten in the playbook. How can this be archived?

Kind rgards
guenther

Use a role’s defaults for low precedence. With include_role you can use defaults_from: + first_found lookup or you can just include the role with the defaults when include_vars fails (after removing default.yml).

Hi,

we have two different solutions for the Problem. The first one is like yours:

- name: Include OS-specific variables
 ansible.builtin.include_vars: "{{ item }}"
 with_first_found:
   - files:
       - "vars/{{ ansible_os_family }}-{{ ansible_distribution_major_version }}.yml"
       - "vars/{{ ansible_os_family }}.yml"
     skip: true

- name: Define mysql_commercial_packages
 ansible.builtin.set_fact:
   mysql_commercial_packages: "{{ __mysql_commercial_packages | list }}"
 when: mysql_commercial_packages is not defined

__mysql_commercial_packages is defined in vars/RedHat.yml

now we can set mysql_commercial_packages in our group_vars and overwrite the default from the OS specific Vars.

Second Solution: defaults/main.yml

mysql_community_packages: "{{ lookup('ansible.builtin.vars', 'mysql_community_packages_' + os_version, default='mysql-server') }}"
mysql_community_packages_redhat9:
  - mysql
  - mysql-server
  - mysql-common