Sobes.tech
Junior — Middle

Explain how variable priorities work in Ansible and in which cases they are applied.

sobes.tech AI

Answer from AI

In Ansible, variables can be defined in various places: in inventory, playbooks, roles, facts, via command line, etc. The variable priority determines which value will be used if the same variable is defined in multiple places.

The main priority levels (from lowest to highest):

  1. Default values in roles (defaults/main.yml).
  2. Variables defined in inventory (inventory vars).
  3. Variables defined in playbooks or in vars.
  4. Variables passed via command line using -e (extra vars).

Extra vars have the highest priority and always override other values.

Applying priorities is important for managing configuration flexibly and avoiding conflicts. For example, you can set general values in roles and override them during execution via extra vars for specific environments.

Example:

# defaults/main.yml
app_port: 80

# inventory/group_vars/all.yml
app_port: 8080

# playbook.yml
vars:
  app_port: 8000

# run with extra vars
ansible-playbook playbook.yml -e "app_port=9000"

The value 9000 will be used because extra vars have the highest priority.