Prefixing Role and Project Variables in Ansible
Categories:
harbor_hostname. Prefix
project variables with a
project prefix, for example c2_cacerts2_ca_dir.Problem
Without a role or project prefix it is not always clear where variables are used. Without a prefix there is also a chance of conflicting or duplicate variable names.
Context
In a typical inventory project many kinds of variables are created and used. Some variables belong to Ansible roles while others are introduced only in the inventory. This distinction can be confusing and may lead to mistakes.
Role variables follow a well-known naming convention that is checked by
linters such as ansible-lint.
Project variables, however, are defined in
group_vars or host_vars and are not part of any role. These variables
require an explicit project prefix to avoid clashes and to make their origin
clear.
Solution
- Prefix every
role variable with the role name, for example
harbor_. - Prefix every
project variable that exists only in
group_varsorhost_varswith a project prefix, for examplec2_.
Benefits
- Makes the origin of each variable immediately visible.
- Prevents accidental duplication or override of variables.
- Aligns with community standards and enables automated linting for role variables.
- Improves maintainability of large inventory projects.
Alternatives (Optional)
Using a generic prefix such as var_ for all variables reduces clarity and is
not recommended.
Examples and Implementation
harbor_hostnameis a role variable for thec2platform.mgmt.harborrole. The prefixharbor_follows the role name.- In the C2
inventory project
c2platform/ansiblethe prefixc2_is used for project variables, for examplec2_cacerts2_ca_diringroup_vars/all/smallca.yml. - In the RWS
inventory project
c2platform/rws/ansible-gisthe prefixgs_is used. See Configuring a Web Proxy Server Example for MS Windows Hosts for the use ofgs_proxy_regedit.
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.