Junior — Middle
In which places and files is it recommended to place variables when using Ansible?
sobes.tech AI
Answer from AI
In Ansible, variables can be placed in different locations depending on their scope and purpose:
- Inventory files — variables specific to hosts or groups of hosts, usually defined in inventory files or in directories
group_vars/andhost_vars/. - Playbook — variables can be declared within the playbook in
varsorvars_filessections. - Roles — within roles, variables are placed in
roles/<role_name>/vars/(hardcoded variables) orroles/<role_name>/defaults/(default variables). - Variable files — separate YAML files with variables, included via
vars_files. - Environment variables and command line — for temporary overrides.
It is recommended to:
- Store variables related to specific hosts or groups in
host_varsandgroup_vars. - Use
defaultsin roles for default values that can be overridden. - Use
varsin roles for mandatory variables that should not be overridden.
This approach ensures ease of maintenance and reusability of configurations.