1

In Ansible roles you can define variables in different ways:

  • in vars/main.yml
  • in defaults/main.yml
  • via register in a task
  • via a set_fact task
  • in task vars
  • probably more...

Through this answer I came across the recommendation to use a naming convention for role variable names, e. g. role_name__variable_name. But I am not sure if this is just a recommendation or if I have to worry about scope/namespace problems caused by a role.

I can imagine that I should take such precaution when defining variables with set_fact as this may overwrite existing host variables. But is this even true? At which variable definitions in a role do I have to worry about possible "namespace corruption"?

stackprotector
  • 10,498
  • 4
  • 35
  • 64
  • 1
    [ansible-lint](https://ansible.readthedocs.io/projects/lint/rules/var-naming/) has a rule `var-naming[no-role-prefix]` which states that _Variables names from within roles should use role\_name\_ as a prefix._ It's aimed at the public role parameters. – Iizuki Sep 01 '23 at 10:56
  • 1
    Nice find! Might be a good answer to this question ;-) – stackprotector Sep 01 '23 at 11:01

1 Answers1

1

So, it's a best practice to name variables indeed w (part) of the role name, and then what the variable stand for.
A clear example is the Elasticsearch role from Elastic.

They simply use es_whatever as naming convention. When a host has those variables, it's easy to recognize what they're for.

At which variable definitions in a role do I have to worry about possible "namespace corruption"?

Well, Ansible has 'magic variables' and predefined variables.
You're most in the clear when you do not use them in naming.

Ensure to watch out for the magic variables, and the special named variables.

Once you've gone through them, you understand why they're either magic and/or special, and most likely will not use them again.

I can imagine that I should take such precaution when defining variables with set_fact as this may overwrite existing host variables. But is this even true?

Yes, but when you write a set_fact task, defining the variable usually ends up with something it has to do.
Just watch out a bit with naming them, and ensure they're unique.

Kevin C
  • 4,851
  • 8
  • 30
  • 64