Sobes.tech
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/ and host_vars/.
  • Playbook — variables can be declared within the playbook in vars or vars_files sections.
  • Roles — within roles, variables are placed in roles/<role_name>/vars/ (hardcoded variables) or roles/<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_vars and group_vars.
  • Use defaults in roles for default values that can be overridden.
  • Use vars in roles for mandatory variables that should not be overridden.

This approach ensures ease of maintenance and reusability of configurations.