Operations 10 min read

Master Ansible Playbooks: From YAML Basics to Handlers and Automation

This guide walks you through Ansible playbooks, covering YAML syntax rules, data types, simple playbook examples, how to run them, install software, enable services, and use handlers for conditional task execution, all with clear code snippets and explanations.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Ansible Playbooks: From YAML Basics to Handlers and Automation

Playbook (剧本)

Previously we ran Ansible tasks ad‑hoc, which is convenient for a single task but cannot chain tasks based on previous results. A playbook is a collection of ad‑hoc commands executed sequentially, offering features that ad‑hoc cannot provide.

1. yaml

Playbooks are written in YAML.

1.1 yaml syntax rules

Case‑sensitive.

Indentation defines hierarchy.

Indentation must use spaces, not tabs.

The number of spaces is irrelevant as long as it is consistent within the same level.

1.2 yaml data types

Scalar: a single, indivisible value.

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

- var01
- var02

Dictionary: key‑value pairs.

1.3 yaml example

basic_info:
  name: 张三
  age: 30
  gender: 男
address:
  country: 中国
  province: 广东
  city: 广州
  street: 中山路
  postcode: 510000
contact:
  - type: 手机
    number: 13800000000
  - type: 工作
    number: 020-88888888
email: [email protected]
skills:
  programming_languages:
    - Python
    - Java
    - JavaScript
  tools:
    - Git

This is a YAML syntax example.

2. ansible‑playbook

2.1 Playbook introduction

Below is a simple playbook.

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

Explanation of each line:

- name: The name of the play; a playbook can contain multiple plays.

hosts: Target hosts.

tasks: List of tasks.

Task name: Human‑readable description of the task.

shell: The module to run a shell command.

whoami: The command executed.

2.2 Executing a playbook

Run the playbook with ansible‑playbook:

$ ansible-playbook first_playbook.yaml
PLAY [This is first ansible playbook] ******************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.200.210]
TASK [This is the First task] **************************************************
changed: [192.168.200.210]
PLAY RECAP *********************************************************************
192.168.200.210 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

The summary shows ok (no change) and changed (task caused a change).

2.3 Using a playbook to install software

- name: Install software
  hosts: all
  tasks:
    - name: start install
      yum:
        name: redis
        state: present

Execute it:

$ ansible-playbook second.yaml
PLAY [Install software] ********************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.200.210]
TASK [start install] ***********************************************************
changed: [192.168.200.210]
PLAY RECAP *********************************************************************
192.168.200.210 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

Because Ansible modules are idempotent, re‑running the playbook shows ok instead of changed when the package is already present.

3. More examples

Additional YAML playbooks illustrate creating groups, users, installing packages, copying configuration files, and restarting services.

# Create groups and a user
- 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

# Install nginx and restart service
- 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

Writing more playbooks will quickly improve your proficiency. Remember never to use tabs for indentation.

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 must have a name that matches the notify reference.

1. Simple handler example

- 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

When the install redis task makes a change, the start redis handler is triggered after all tasks complete.

If the package is already installed, the task reports ok (no change) and the handler does not run, leaving the service stopped.

Ansible output illustration
Ansible output illustration
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.

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