Operations 18 min read

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.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Ansible Playbooks: From Basics to Advanced YAML Techniques

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
- Python

and as inline JSON‑style: ["Shell","Perl","Python"] Complex structures combine objects and arrays, e.g.:

languages:
  - Shell
  - Perl
  - Python

4.2.1 Objects

Key/value pairs require a space after the colon:

name: junmajinlong

4.2.2 Arrays

- Shell
- Perl
- Python

4.2.3 Dictionaries

person1:
  name: junmajinlong
  age: 18
  gender: male
person2:
  name: xiaofanggao
  age: 19
  gender: female

4.2.4 Composite structures

- person1:
    name: junmajinlong
    age: 18
    langs:
      - Perl
      - Ruby
      - Shell
- person2:
    name: xiaofanggao
    age: 19
    langs:
      - Python
      - Javascript

4.2.5 String continuation

Multi‑line strings are written with indentation; line breaks become spaces:

str: hello
  world
  hello world

Using > 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: /tmp

Running 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\.com

Intersection ( &) 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: false

Running it shows up to five concurrent SSH/Ansible processes.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AutomationDevOpsYAMLAnsiblePlaybook
MaGe Linux Operations
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.