Prefix all variables

Prefix all variables #

When writing roles, I recommend prefixing all variables with the role name. This helps prevent accidental variable leakage, it means you know exactly where a variable is defined, and it makes variables easier to grep for.

For example, in roles/examplerole/defaults/main.yml, I recommend this:

examplerole_foo: 12345
examplerole_blah: "asdf"

but not this:

foo: 12345
blah: "asdf"

Variables used elsewhere #

(You might think of variables used in multiple rules as “global variables”, but keep in mind that most variables in Ansible are global, so this can be confusing.)

If a variable is used in multiple roles, you may wish to use that directly, or you may wish to prefix it in every role and set each role’s default to the global value. I tend toward the latter, but most people I work with tend toward the former.

In an example of my preferred style, let’s say we have a sitetype variable that describes the type of site we’re deploying to, perhaps it holds “dev” or “prod”, or maybe it holds “customer” or “internal”, whatever. I would tend to have the following in roles/examplerole/defaults/main.yml:

examplerole_sitetype: "{{ sitetype }}"

This is more verbose, but it makes the Ansible repository a little more manageable as it grows larger. It means the roles stand alone and the role’s defaults (or vars) contain the interface for using the role.