LinuxUnity LinuxUnity

Posts / Ansible

[Ansible] Part 5: A Beginner’s Guide to Writing Simple, Effective Playbooks

What is a playbook? A playbook is a core Ansible component that uses YAML to define organized, automated workflows and tasks for groups of hosts.

11/07/2026 8 min read 45 views

Z Zedx

In this article

What is a playbook?

A playbook is a core component of Ansible. It is the most common way to describe automated workflows in a simple and organized manner. Ansible playbooks are YAML files containing instructions (the tasks to be performed) for Ansible. A playbook consists of multiple “plays” — each play is a collection of tasks to be performed on a specific group of hosts.

YAML overview

YAML — YAML Ain’t Markup Language — is a Data Serialization Language designed to be easy for humans to read, similar to JSON and XML. It uses a highly readable format (similar to Python) to define structure.

Commonly used for configuration files, but can also be used for other purposes such as storing log files, interprocess communication, cross-language data exchange, object persistence, or debugging complex data structures.

The file typically begins with ---. Comments begin with #.

There are three ways to represent values in YAML:

  1. Key-Value Pair

– The simplest syntax.

– In YAML, keys and values are separated by a colon (:), and the colon must always be followed by a space.

Example:

text
name: Install httpd

name: Copy Site Files
  1. Lists

– Array elements are represented by a hyphen (-).

– Each item must be preceded by a space.

– All elements in an array must have the same indentation.

Example:

text
tasks:

  - install httpd

  - start httpd
  1. Dictionary

– A nested structure with multiple levels of indentation.

– Uses indentation to represent parent-child relationships.

yaml

→ Select the appropriate YAML representation based on the intended use.

Playbook Structure

An Ansible Playbook is typically divided into three basic sections:

  1. Header (Metadata)

Declare the server groups to operate on, as well as variables, facts, sudo privileges,…

Some typical parameters are as follows:

gather_facts: Select whether to gather system information from the hosts.

hosts: Specify the target group or server in the inventory.

vars or vars_files: Declare global variables or variables from an external file.

become: Define sudo privileges if necessary.

  1. Body (Tasks)

This section contains the list of tasks that Ansible will execute. It is the main part of the Playbook and is organized as a list of modules and parameters.

Each task includes a name, module, and the required parameters.

Conditions (when), loops (with_items), or error handling (ignore_errors).

  1. Final Section (Handlers) (Optional)

Handlers are used when one or more tasks change state. They are commonly used to restart services, update log files, or perform other necessary tasks after a task has been executed.

Handlers are only called when a task has a status of changed.

Handlers are declared in a separate section with a name similar to a callback.

Example Playbook

Below is a simple playbook that installs and deploys Apache configuration, then uploads a static website to two remote servers running Ubuntu 24.

Step 1: Declare the inventory

Step 2: Write the Playbook

  • First section:
text
---
- hosts: all
  become: yes
  gather_facts: no
  vars:
    http_port: 1808
  vars_prompt:
    - name: yours_name
      prompt: Type yours name?

hosts: all: applies the Playbook to all hosts in the inventory.

become: yes: run commands with elevated privileges sudo.

gather_facts: no: If you do not need to collect information from remote servers or use default variables, set No the Ansible playbook skips this section, reducing execution time.

vars: variable declaration.

http_port: defines the Apache port as 1808. This variable is declared in the port.j2 file below. When the Apache port needs to be changed on the servers, you only need to update the variable value in the playbook.

vars_prompt: prompts the user to enter an input value when running the playbook.

yours_name: This variable is defined in the index.j2 file.

  • Body:

Use the module apt to ensure that Apache is installed on the system:

text
  - name: Ensure that Apache is installed
    apt:
      name: apache2
      state: present

Start Apache and enable the service to start automatically when the host boots:

text
  - name: Start Apache service
    service:
      name: apache2
      state: started
      enabled: yes

Disable the iptables firewall:

text
  - name: Stop iptables
    service:
      name: iptables
      state: stopped

For simplicity, we disable the iptables firewall to prevent it from blocking Apache's port. Alternatively, you can write a task to allow the Apache port through this firewall.

Apache configuration (change the port):

text
  - name: Deploy configuration file
    template:
      src: /root/templates/ports.j2
      dest: /etc/apache2/ports.conf
      backup: yes
    notify:
      - Restart Apache

Module template is used to create configuration files using variables. It uses Jinja2 to render a file from a template .j2 and save it to the remote machine.

We will use this module to automatically deploy the Apache port configuration file from the path /root/templates/ports.j2 (on the control server) to /etc/apache2/ports.conf (on the remote servers). If the file ports.conf already exists and has not changed, Ansible will not write it.

backup: yes: Create a backup if there are changes compared with the previous original file on remote servers.

notify: Activate the handler to restart Apache if there are changes.

Deploy the website files:

text
  - name: Copy site files
    template:
      src: /root/templates/index.j2
      dest: /var/www/html/index.html

??? Copy the website interface files (index.j2) into the web directory /var/www/html/index.html.

  • Final section

If the Apache configuration changes, the handler will be called to restart Apache.

text
  handlers:
  - name: Restart Apache
    service:
      name: apache2
      state: restarted
  • Complete playbook:

playbook

File ports.j2, where you need to declare variables in the form {{ tên_biến }}.

??? Variables http_port in this file correspond to the var variables declared at the beginning of the playbook.

Similarly, for the file index.j2

  • Content of the index.j2 and ports.j2 files download here!

Step 3: Run the playbook

Run the following command:

text
ansible-playbook -i <path_to_inventory> <name_of_playbook>

When running the command, Ansible prompts you to enter a value Type yours name?. Here, we will enter Linux Unity. This value corresponds to the variable yours_name in the index.j2 file above.

Note that in the task [Deploy configuration file], only the configuration on the web2 server changes. Therefore, the Restart Apache handler is also called only on this server.

Step 4: Verify

Access the IP addresses of the 2 remote servers on port 1808. At this point, the website interface will display the Linux Unity input value passed earlier.

SSH into the web2 server and navigate to the path /etc/apache2. The file ports.conf has changed, so it has been backed up under a different name (file ports.conf.731055.2025-02-03@17:17:32~).

Roles in Ansible

A role is not a playbook. A role is a framework for splitting a playbook into multiple separate files. Each role is an independent component that includes variables, tasks, files, templates, and underlying modules.

Organizing playbooks by role also makes it easier for users to share and reuse playbooks with others. This is especially important in enterprise environments with hundreds or thousands of playbooks, where roles are the primary way to manage them.

A role contains seven folders with different functions. Each folder must contain one file main.yml. Among them, tasks is usually the most important folder because it contains the playbooks.

  • tasks: Write the specific setup steps for the role. Write them like a normal playbook.
  • handlers: Used to trigger operations such as reloading, restarting, starting, or stopping a service when a task in the playbook is executed using a command notify.
  • defaults: Defines the default values for variables used in roles. If variables are not defined in the vars directory, these default values are used.
  • vars: Contains information about the variables used in the role. Variables in vars override variables in defaults.
  • files: Contains files used by the role, such as image files.
  • templates: Contains template files in Jinja format with the *.j2 extension, such as configuration files, system files, and others.
  • meta: Contains metadata about the role, typically used when publishing a role to Ansible Galaxy – where users upload and share the roles they have written.

Illustration of the directory tree structure for an Ansible role:

  • View examples of roles, along with all the basic Ansible knowledge I have practiced, here !!

Conclusion

This completes the Playbook, providing an overview of how to automate system administration in a simple and effective way. Mastering Playbooks will help you save time, minimize errors, and improve work efficiency.

Series: Ansible · Part 5/8

  1. Intro Automation in Linux Configuration Management
  2. Part 1 [Ansible] Part 1: Introduction to Ansible
  3. Part 2 [Ansible] Part 2: Installing and Getting Started with Ansible
  4. Part 3 [Ansible] Part 3: How to Create and Manage Inventory Effectively in Ansible
  5. Part 4 [Ansible] Part 4: Exploring Commonly Used Modules in Ansible
  6. Part 5 [Ansible] Part 5: A Beginner’s Guide to Writing Simple, Effective Playbooks
  7. Part 6 [Ansible] Part 6: Writing an Ansible Playbook to Install WordPress on a LAMP Stack
  8. Part 7 [Ansible] Part 7: Install Ansible CMDB and Create System Reports in Minutes

Related posts