Lesson 6 of 11 ↓
- 1.Ansible Basic Setup Guide
- 2.Ansible Inventory Guide (hosts)
- 3.Ansible Configuration Guide (ansible.cfg)
- 4.Ansible Ad-hoc Commands Guide
- 5.Ansible Playbook Guide (playbook.yml)
- 6.Ansible Variables & Precedence Guide
- 7.Ansible Loops Guide
- 8.Ansible Conditionals Guide (when)
- 9.Ansible Vault Guide
- 10.Ansible Handlers Guide
- 11.Ansible Custom Roles Guide
5 min read
Ansible Variables & Precedence Guide
A comprehensive guide to understanding Variables in Ansible and their Precedence order. This file is designed to be a reference from beginner to professional levels.
Introduction: What are Variables? Why Use Them?
Variables are a way to store values (like usernames, file paths, or package names) and use them throughout your Playbooks.
Importance:
-
Dynamic: Makes the code flexible (changing a value in one place applies it everywhere).
-
Reusability: You can use the same Playbook for different servers just by changing the variables.
Variable Precedence (who Wins?)
In Ansible, you can define variables in many places. If the same variable is defined in two different places, who wins?
The General Rule: "The most specific wins, and the CLI overrides everything."
The Order from Strongest (Always Wins) to Weakest:
-
Extra Vars (
-e) (From Command Line - The Strongest 💪). -
Task Vars / set_fact (Inside the task during execution).
-
Play Vars (Defined inside the Play).
-
Host Vars (Specific to a single server).
-
Group Vars (Specific to a group of servers).
-
Role Defaults (The Weakest - used only as default values).
Detailed Examples (from Strongest to Weakest)
In the following examples, we assume we want to print a message using the variable message.
Extra Vars (-e)
This method is the Wildcard. Any variable you write here will wipe out any old value and replace it. It is usually used during manual execution or in Pipelines (CI/CD).
Command:
ansible-playbook play.yml -e "message='Hello from CLI'"-
-eor--extra-vars: This argument allows you to pass variables at Runtime. -
Importance: ⭐⭐⭐⭐⭐ (Very important for testing and Overriding).
Playbook:
- name: Example with extra vars
hosts: all
tasks:
- debug:
msg: "{{ message }}"- Result: It will print
Hello from CLIregardless of what is written inside the files.
Set_fact (runtime Variables)
This module allows you to create or modify variables during the execution of the Playbook.
Playbook:
- name: Example with set_fact
hosts: all
tasks:
- name: Set a variable dynamically
set_fact:
message: 'Hello from set_fact'
- debug:
msg: "{{ message }}"-
What does it do? It reserves the variable in the server's (Host) memory during execution.
-
Importance: ⭐⭐⭐⭐⭐ (Very important for calculations or building variables based on previous results).
-
Priority: Very high, beats Play Vars and Inventory Vars.
Vars in a Play
Defining variables explicitly inside the Playbook file itself under the vars section.
Playbook:
- name: Example with vars in play
hosts: all
vars:
message: 'Hello from vars'
tasks:
- debug:
msg: "{{ message }}"-
Advantage: Clear, easy to read, and exists in the same file.
-
Disadvantage: Hard to change if you want to use different values for each environment (Prod vs Dev).
Vars_files
Instead of writing variables inside the Playbook and cluttering it, we place them in an external file and import them.
File: vars.yml
message: 'Hello from vars_files'Playbook:
- name: Example with vars_files
hosts: all
vars_files:
- vars.yml
tasks:
- debug:
msg: "{{ message }}"- Importance: ⭐⭐⭐⭐ (Excellent for organization, and for keeping secrets in files encrypted with Ansible Vault).
Host_vars
Variables specific to one single server. They are placed in a folder named host_vars containing a file named after the server or IP.
Directory Structure:
project/
├── playbook.yml
└── host_vars/
└── 192.168.1.10.yml <-- (Contains: message: 'Hello from host_vars')Playbook:
- name: Example with host_vars
hosts: all
tasks:
- debug:
msg: "{{ message }}"- When to use? If you have one server that needs special settings (e.g., a Master Node needs more RAM than Workers).
Group_vars
Variables specific to a whole group of servers (like the web or db group).
Directory Structure:
project/
├── playbook.yml
└── group_vars/
├── all.yml <-- (Applies to ALL servers)
└── web.yml <-- (Applies only to the web group)Playbook:
- name: Example with group_vars
hosts: all
tasks:
- debug:
msg: "{{ message }}"-
Importance: ⭐⭐⭐⭐⭐ (This is the standard place to put general variables).
-
Note:
host_varsis stronger thangroup_vars. (Specific beats General).
Must-know Additions
These commands and concepts are essential for anyone using Ansible.
register (how to Store Command Output?)
The most important way to create dynamic variables. It captures the output of a Linux command and stores it in a variable for later use.
Example:
- name: Check if file exists
command: ls /tmp/myfile.txt
register: file_check
ignore_errors: true
- name: Print the result
debug:
msg: "File exists!"
when: file_check.rc == 0-
register: file_check: Stores all execution details in a variable namedfile_check. -
file_check.rc: The Return Code (0 means success). -
file_check.stdout: The text output of the command.
Ansible Facts (automatic Info)
When Ansible starts, it gathers information about the server (IP, OS, RAM, CPU) and stores it in variables called Facts.
-
You can view them with the command:
ansible all -m setup -
Famous Examples:
-
ansible_default_ipv4.address: Main IP address. -
ansible_distribution: OS Distribution (CentOS, Ubuntu). -
ansible_memtotal_mb: Total RAM size.
-
Example in Playbook:
- debug:
msg: "This server is running {{ ansible_distribution }} with IP {{ ansible_default_ipv4.address }}"Magic Variables
Special variables provided by Ansible that give you information about the Inventory.
-
inventory_hostname: The name of the server as written in the Inventory file. -
groups: A list of all groups and the servers inside them. -
group_names: A list of group names that the current server belongs to.
Jinja2 Filters (formatting Variables)
You can manipulate variable values using Filters.
-
default: Set a backup value if the variable doesn't exist.code msg: "{{ my_var | default('Not Defined') }}" -
upper: Convert text to uppercase.code msg: "{{ message | upper }}"
Summary (cheat Sheet)
| Order | Method | Location | When to use? |
|---|---|---|---|
| 1 (Strongest) | -e (Extra Vars) |
Command Line | For emergencies and quick Overriding. |
| 2 | set_fact |
Inside Task | To calculate values during runtime. |
| 3 | register |
Task Output | To make decisions based on previous commands. |
| 4 | vars / vars_files |
Inside Play | For static variables specific to the Playbook. |
| 5 | host_vars |
Host Files | For settings specific to a single server. |
| 6 | group_vars |
Group Files | For general settings (like Domain name, DNS). |
| 7 (Weakest) | role defaults |
Inside Role | To set default values that can be easily changed. |
Comments
Loading the discussion…