lonix
lonix

Reputation: 20489

Conditionally incude ansible role's variable files

Ordinarily I would dump variables in roles/myrole/defaults/main.yml. I don't need to explicitly include them - that's done for me automatically.

But let's say I need to support Debian and CentOS and have identical variables with different values. The common advice is:

roles/myrole/defaults/main.yml       # common defaults
roles/myrole/vars/debian.yml         # debian overrides
roles/myrole/vars/centos.yml         # centos overrides

And then we're supposed to "conditionally include" the correct set of variables.

But where exactly? In the main task, or a "main" variables file, or somewhere else?

Upvotes: 1

Views: 297

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67959

Q: "But where exactly? In the main task, or a "main" variables file, or somewhere else?"

In the main task, I'd say. For example

- include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - "default.yml"
        - "defaults.yml"
      paths: "vars"

A user can keep customized variables in vars. Put the defaults into the directory vars/defaults. This way the customized variables will survive potential updates of the role.

# Default variables
- include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - "default.yml"
        - "defaults.yml"
      paths: "vars/defaults"

# Custom variables
- include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - "default.yml"
        - "defaults.yml"
      paths: "vars"

available at GitHub

Upvotes: 1

Related Questions