Best practices with roles and variables

Hi,

Suppose to have a variable (Y) used inside a role (X).
Y is defined inside roles/X/vars/main.yml as “Y: reasonable_default_value”

What about if host (A) must have its Y custom value?

  • “Y: a_custom_value” inside host_vars/A doesn’t work (by design or bug?)
    This is a working solution (obviously with “Y: a_custom_value” inside vars/A.yml):

playbook

  • hosts: all
    vars_files:

  • [ “vars/{{ inventory_hostname }}.yml”, “vars/defaults.yml” ]
    roles:

  • role: X

Are there other better methods?

Thank you!

In Jinja2, I believe you want {{ x | default y }}

It might be so?

playbook

  • hosts: all
    roles:
  • role: x

roles/x/vars/main.yml

y: “{{ y1 | default(‘reasonable_default_value’) }}”

roles/x/tasks/main.yml

{{ y }} used in many place: tasks, template, etc

host_vars/A

y1: a_custom_value

If so:

  • variables defined inside roles/x/vars/main.yml are defaults

  • variables defined inside roles/x/vars/main.yml can be “overridden” by using

  1. vars_files
  2. another variable and jinja default (y1 → y)
    it’s right?

Correct.