Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Variable Precedence in Ansible

Introduction

Ansible is a powerful automation tool that uses variables to manage system configurations. Variable precedence defines the order in which variables are evaluated and applied. Understanding variable precedence is crucial to ensure your playbooks behave as expected.

Understanding Variable Precedence

In Ansible, variables can be defined in multiple places. The precedence determines which variable value is used when multiple definitions are available. The order of precedence from lowest to highest is as follows:

  • Role defaults
  • Inventory variables
  • Inventory group variables
  • Inventory host variables
  • Playbook group_vars
  • Playbook host_vars
  • Host facts
  • Play vars
  • Play vars_prompt
  • Play vars_files
  • Registered vars
  • Set_facts / include_vars
  • Role vars
  • Block vars
  • Task vars (only for the task)
  • Extra vars (always win precedence)

Examples

Let's explore some examples to understand how variable precedence works in practice.

Consider a variable my_variable defined in different places. We will see which value gets applied based on the precedence.

1. Role Defaults

Variable defined in defaults/main.yml of a role:

my_variable: "default_value"

2. Inventory Host Variables

Variable defined in the inventory file:

[my_group]
my_host ansible_host=192.168.1.1 my_variable="inventory_value"

3. Play vars

Variable defined in the playbook:

- hosts: my_host
  vars:
    my_variable: "playbook_value"

4. Extra Vars

Variable passed as extra vars in the command line:

ansible-playbook my_playbook.yml -e "my_variable=extra_value"

Effective Value

Given the above definitions, the effective value of my_variable will be extra_value since extra vars have the highest precedence.

Conclusion

Understanding variable precedence in Ansible is essential for writing predictable and maintainable playbooks. By knowing the order in which variables are evaluated, you can control the configuration precisely and avoid unexpected behaviors.