Mastering Ansible Playbooks: From Basics to Advanced YAML Techniques
This guide explains the limitations of Ansible ad‑hoc commands, introduces the playbook‑play‑task hierarchy, demonstrates YAML syntax for playbooks, shows how to run and interpret playbook output, and covers host targeting, task parameters, and execution strategies for efficient automation.
4.1 playbook, play and task relationship
In Ansible, a playbook is like a movie script: each play corresponds to a scene and contains one or more tasks that act like individual shots. A playbook can organize multiple tasks across multiple plays, enabling orchestration of complex workflows.
Key points:
A playbook may contain one or more plays.
Each play may contain one or more tasks.
Special task types pre_tasks and post_tasks run before and after the main tasks.
Every play must specify target hosts with the hosts directive.
Example playbook first.yml defines two plays ("play 1" for the nginx group and "play 2" for the apache group), each with two debug tasks:
---
- name: play 1
hosts: nginx
gather_facts: false
tasks:
- name: task1 in play1
debug:
msg: "output task1 in play1"
- name: task2 in play1
debug:
msg: "output task2 in play1"
- name: play 2
hosts: apache
gather_facts: false
tasks:
- name: task1 in play2
debug:
msg: "output task1 in play2"
- name: task2 in play2
debug:
msg: "output task2 in play2"Running ansible-playbook first.yml produces output showing each play and task execution per host, with ok indicating success.
4.2 playbook syntax: YAML
Ansible playbooks use YAML, a human‑readable format that maps directly to JSON. Files typically end with .yml or .yaml. YAML supports three data structures:
Objects (key/value pairs)
Arrays (lists)
Scalars (single values)
Examples: name: junmajinlong is equivalent to JSON {"name":"junmajinlong"}. Arrays can be written as:
- Shell
- Perl
- Pythonand as inline JSON‑style: ["Shell","Perl","Python"] Complex structures combine objects and arrays, e.g.:
languages:
- Shell
- Perl
- Python4.2.1 Objects
Key/value pairs require a space after the colon:
name: junmajinlong4.2.2 Arrays
- Shell
- Perl
- Python4.2.3 Dictionaries
person1:
name: junmajinlong
age: 18
gender: male
person2:
name: xiaofanggao
age: 19
gender: female4.2.4 Composite structures
- person1:
name: junmajinlong
age: 18
langs:
- Perl
- Ruby
- Shell
- person2:
name: xiaofanggao
age: 19
langs:
- Python
- Javascript4.2.5 String continuation
Multi‑line strings are written with indentation; line breaks become spaces:
str: hello
world
hello worldUsing > preserves line breaks as spaces, while | keeps them as literal newlines.
4.2.6 Null values
Keys without values, null, NULL, or ~ all represent a null.
4.2.7 Quotes and escaping
Single quotes keep special characters literal; double quotes require escaping backslashes.
4.3 Writing a playbook
After learning YAML, you can author Ansible playbooks. Remember that each play must include hosts and tasks. Example converting an ad‑hoc command to a playbook:
$ ansible nginx -m copy -a 'src=/etc/passwd dest=/tmp'Corresponding copy.yml:
---
- hosts: nginx
gather_facts: false
tasks:
- copy:
src: /etc/passwd
dest: /tmpRunning ansible-playbook copy.yml executes the copy module on the nginx hosts.
4.4 Passing module parameters
Parameters can be supplied as a single string, as key/value pairs, or via the args keyword. All styles are functionally equivalent; choose the one that improves readability.
4.5 Specifying target hosts
The hosts directive accepts patterns, groups, ranges, wildcards, and regular expressions. Examples:
hosts: localhost hosts: nginx hosts: all hosts: nginx[1]:mysql[0] hosts: *.example.com hosts: ~(web|db)\.example\.comIntersection ( &) and exclusion ( !) operators can refine selections.
4.6 Default task execution strategy
Ansible creates a configurable number of parallel processes (default forks = 5). Up to five hosts run tasks simultaneously; when a host finishes early, another host is started without waiting for the whole batch to complete.
Example playbook to observe the behavior:
---
- name: first play
hosts: all
#gather_facts: falseRunning it shows up to five concurrent SSH/Ansible processes.
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.
