Master Ansible Playbooks: Syntax, Variables, Handlers & Advanced Tips
This guide explains what an Ansible playbook is, its YAML syntax, how to run tasks on multiple hosts, limit execution with --limit, use inventory files, define variables via extra‑vars, vars, vars_files, host_vars and group_vars, work with facts, register results, apply when conditions, delegate tasks, pause execution, prompt for input, tag tasks, and structure plays with blocks, rescue and always sections.
What is a Playbook?
A playbook is essentially a collection of tasks written in YAML, similar to a shell script, but it can run on multiple servers. Each task corresponds to a command, and the playbook specifies which hosts to target.
Playbook Syntax
Playbooks use YAML. The file starts with three dashes (---) and uses indentation to define blocks. A simple example from the official documentation:
---
- hosts: webservers
vars:
http_port: 80
max_clients: 200
remote_user: root
tasks:
- name: ensure apache is at the latest version
yum: pkg=httpd state=latest
- name: write the apache config file
template: src=/srv/httpd.j2 dest=/etc/httpd.confIndentation works like Python to separate code blocks.
Example: Check MySQL Status
---
- hosts: all
remote_user: root
gather_facts: no
tasks:
- name: check the mysql status
service: name=mysqld state=runningRunning the playbook produces output showing the status of each host.
Limiting Host Execution
Use the --limit option to run a playbook only on a subset of hosts defined in the inventory.
[all]
10.0.102.212
10.0.102.200
10.0.102.162
[dbservers]
10.0.102.162Running with --limit dbservers restricts execution to the dbservers group.
Listing Target Hosts
ansible-playbook test.yml --list-hostsShows which hosts the playbook will affect.
Playbook Variables
Extra Vars
ansible-playbook test.yml --extra-vars "test_var=test" -vThe variable test_var is passed to the playbook and can be echoed.
Vars Block
---
- hosts: all
remote_user: root
gather_facts: no
vars:
test_var: Hello World
tasks:
- name: test playbook variables
command: echo {{ test_var }}Vars Files
---
- hosts: all
remote_user: root
gather_facts: no
vars_files:
- vars.yml
tasks:
- name: test playbook variables
command: echo {{ test_var }}Where vars.yml contains:
---
test_var: Hello WorldHost‑Specific Variables
Define variables per host directly in the inventory:
[all]
10.0.102.212 test_var=212
10.0.102.200 test_var=200
10.0.102.162 test_var=162Host and Group Variable Files
Create /etc/ansible/host_vars/ and /etc/ansible/group_vars/ directories with files named after hosts or groups.
# /etc/ansible/host_vars/10.0.102.162
---
test_var: 162Group variables example ( group_vars/all):
---
test_group_var: from groupFacts Variables
Facts are automatically gathered system information. You can view them with the setup module.
ansible 10.0.102.162 -m setupCommon facts include ansible_os_family, ansible_hostname, etc., and can be used in when statements.
Register Variables
Use register to capture a task’s result.
- name: test the register variables
shell: uptime
register: results
- name: print the register result
debug: msg="{{ results.stdout }}"Conditional Execution (when)
- name: shut down the db server
service: name=mysqld state=stopped
when: ansible_eth0.ipv4.address == "10.0.102.162"Task Delegation
Run a specific task on a different host using delegate_to or local_action.
- name: stop the db server
service: name=mysqld state=stopped
delegate_to: 10.0.102.162Pausing Execution
Use the wait_for module to pause until a condition is met.
- name: wait for webserver to start
local_action:
module: wait_for
host: webserver1
port: 80
delay: 10
timeout: 300
state: startedInteractive Prompts (vars_prompt)
---
- hosts: all
remote_user: root
vars_prompt:
- name: share_user
prompt: "what is your network username?"
private: no
- name: share_pass
prompt: "what is your network password"
private: noTags
Tag tasks, roles, or entire playbooks to run or skip specific parts.
- name: Notify on completion
local_action:
module: osx_say
msg: "{{inventory_hostname}} is finished"
voice: Zarvox
tags:
- notifications
- sayBlocks, Rescue & Always
Group tasks with block and handle errors with rescue and always.
tasks:
- block:
- name: risky command
shell: ./do_something.sh
rescue:
- debug: msg="There was an error in the block"
always:
- debug: msg="This always executes"Source: https://www.cnblogs.com/wxzhe/p/10386649.html
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.
