Master Ansible Variables: Naming Rules, Scopes, and Practical Playbook Examples
This guide explains Ansible variable naming conventions, the three scopes (global, play, host/group), and demonstrates each with clear playbook snippets, showing how to define, import, and override variables using command‑line options, vars, vars_files, host_vars, and group_vars.
Variable Naming Rules
Variables must start with a letter and can contain only letters, numbers, and underscores.
Variable Scopes
Ansible supports three scopes:
Global : defined on the command line with the -e option.
Play : defined inside a playbook using vars or vars_files.
Host/Group : defined in the inventory file, host_vars, or group_vars directories.
Global Variables
Example playbook using a global variable package to install Apache:
---
- name: Install Apache
hosts: servera
tasks:
- name: Install {{ package }}
apt:
name: "{{ package }}"
state: presentRun with:
ansible-playbook test.yml -e "package=apache2"Play Variables
Define a variable directly in a play:
---
- name: Create User
hosts: servera
vars:
user: jack
tasks:
- name: Create a user named {{ user }}
user:
name: "{{ user }}"Run the playbook to see the variable substituted.
Variable Files
Create a separate YAML file (e.g., user.yml):
---
user: jerryImport it with vars_files:
---
- name: Create User
hosts: servera
vars_files:
- user.yml
tasks:
- name: Create a user named {{ user }}
user:
name: "{{ user }}"Host Variables
Add a variable to a host entry in the inventory:
serverb user=user1
[web]
servera
[prod:children]
webReference the variable in the playbook the same way as other variables.
Host‑Vars Directory
Create a host_vars directory and a file named after the host (e.g., servera.yml) containing:
---
user: user2The playbook will automatically load this variable for the matching host.
Group Variables
Define a variable for a group in the inventory:
[web:vars]
user=user3Or create a group_vars directory with a file named after the group (e.g., web.yml) containing:
---
user: user4Playbooks targeting the group will use the defined variable.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
