Operations 10 min read

Master Ansible Playbooks: From YAML Basics to Advanced Handlers

This guide walks you through Ansible playbooks, covering YAML syntax rules, data types, sample playbooks for installing software, execution commands, idempotency concepts, and how to use handlers for conditional task execution, providing clear examples and command‑line outputs.

Raymond Ops
Raymond Ops
Raymond Ops
Master Ansible Playbooks: From YAML Basics to Advanced Handlers

Playbook (剧本)

When using Ansible, ad‑hoc commands are convenient for single tasks but cannot chain multiple tasks based on previous results. A playbook is essentially a collection of ad‑hoc tasks written in YAML, executed sequentially, and offers features that ad‑hoc cannot provide.

1. YAML

Playbooks are written using YAML syntax.

1.1 YAML syntax rules

Case‑sensitive.

Indentation defines hierarchy.

Indentation must use spaces, not tabs.

The number of spaces per level is flexible as long as it is consistent.

1.2 YAML data types

Scalar – a single indivisible value.

Array – an ordered list, each element prefixed with a hyphen.

Dictionary – key‑value pairs.

1.3 YAML example

<code>basic_info:
  name: 张三
  age: 30
  gender: 男
address:
  country: 中国
  province: 广东
  city: 广州
  street: 中山路
contact:
  - type: 手机
    number: 13800000000
  - type: 工作
    number: 020-88888888
skills:
  programming_languages:
    - Python
    - Java
    - JavaScript
  tools:
    - Git
</code>

This is a simple YAML example.

2. ansible‑playbook

2.1 Playbook basics

Below is a minimal playbook:

<code>- name: This is first ansible playbook
  hosts: all
  tasks:
    - name: This is the First task
      shell: whoami
</code>

Key elements:

name – the play’s description; a playbook can contain multiple plays.

hosts – target hosts.

tasks – list of tasks.

Within a task, name describes the task.

shell – the module used.

whoami – the command executed.

2.2 Executing a playbook

Run the playbook with:

<code>ansible-playbook first_playbook.yaml</code>

The output shows a PLAY header, task execution results, and a PLAY RECAP where

ok

means no change and

changed

indicates a successful change.

2.3 Installing software via playbook

<code>- name: Install software
  hosts: all
  tasks:
    - name: start install
      yum:
        name: redis
        state: present
    - name: enable redis
      systemd:
        name: redis
        enabled: yes
        state: started
</code>

Running this playbook installs Redis, enables it to start on boot, and starts the service. Ansible modules are idempotent: the first run changes the system, subsequent runs report

ok

because the desired state is already achieved.

3. More examples

Additional YAML snippets illustrate creating groups, users, and installing packages:

<code>- name: Ansible Playbook Example for Creating Users and Groups
  hosts: all
  become: yes
  tasks:
    - name: Create the first group
      group:
        name: group1
        state: present
    - name: Create the second group
      group:
        name: group2
        state: present
    - name: Create a user and add to both groups
      user:
        name: demo_user
        groups: group1,group2
        append: yes
        state: present
</code>
<code>- name: Ansible Playbook Example for Package Installation and Configuration
  hosts: all
  tasks:
    - name: Install nginx package
      package:
        name: nginx
        state: present
    - name: Copy nginx configuration file
      copy:
        src: /path/to/local/nginx.conf
        dest: /etc/nginx/nginx.conf
        owner: root
        group: root
        mode: '0644'
    - name: Restart nginx service
      service:
        name: nginx
        state: restarted
</code>

Writing more playbooks will help you become proficient.

Handler

In an Ansible playbook, a handler is a special task that runs only when notified by another task.

Handlers are defined at the same level as

tasks

and are triggered only if a task reports a change.

1. Simple handler example

<code>- name: test handler
  hosts: all
  tasks:
    - name: install redis
      yum:
        name: redis
        state: present
      notify: start redis
  handlers:
    - name: start redis
      systemd:
        name: redis
        state: started
</code>

Notice that the handler name must match the name used in

notify

. After the playbook runs, you can verify the service status with

systemctl is-active redis

. If the task does not cause a change (e.g., Redis is already installed), the handler will not run, demonstrating Ansible’s idempotent behavior.

automationDevOpsyamlAnsibleplaybookHandlers
Raymond Ops
Written by

Raymond Ops

Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.

0 followers
Reader feedback

How this landed with the community

login 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.