Level 1
0 / 100 XP

Variable Precedence

In this lesson, you will explore the concept of variable precedence in Ansible. Understanding how Ansible prioritizes variables is crucial for managing complex playbooks and ensuring that your automation behaves as expected.

By the end of this lesson, you'll have a clear understanding of the different levels at which you can define variables in Ansible and how the precedence rules affect their values.

Understanding Variable Precedence

Variable precedence in Ansible is the order in which the system decides which value to use when you have the same variable defined in multiple places. Ansible uses a specific hierarchy to resolve this, and understanding this hierarchy is key to effectively managing and utilizing variables in your playbooks.

Here's a simplified view of the variable precedence hierarchy in Ansible, from highest (most prioritized) to lowest:

  1. Extra Variables (Passed at Command Line) \- When you use the -e or --extra-vars option in the command line.
  2. Role and Include Variables \- Variables defined within a role or using the include_vars module.
  3. Block Variables \- Variables passed to a block.
  4. Task Variables \- Variables directly attached to a task.
  5. Play Variables \- Variables defined at the play level.
  6. Inventory Variables \- Variables defined in the inventory file.
  7. Role Defaults \- Default variables defined in a role.

It's important to remember that while this hierarchy exists, good practice in Ansible is to keep variable usage clear and understandable. Over-reliance on variable precedence can make your playbooks hard to read and maintain.

Understanding the Task

We will create a task in an Ansible playbook that touches a file on the remote server. The name of the file will be determined by a variable named file_name. We will define this variable in two places:

  1. In the inventory file, where file_name will be set to "inventory". 2…