What is Ansible Playbook and How to Write it

Infrastructure automation is an essential aspect of IT operations in the modern world. It allows organizations to easily achieve scalability, efficiency, and consistency. It also allows DevOps engineers to focus on higher-priority tasks instead of spending time on repetitive, mundane tasks. One of the most popular and powerful infrastructure automation tools is Ansible.

This article will cover how Ansible works, its core concept, and how to write an Ansible playbook from scratch.

Key Takeaway

  • To use the Ansible playbook, run the command ansible-playbook -i inventory_filename playbook_filename
  • To write an Ansible playbook, define hosts, tasks, and inventory in the playbook's yaml file.
  • To customize the execution of the playbook, use variables in the Ansible playbook.

What is Ansible?

Ansible is an open-source tool that automates infrastructure provisioning, application deployment, and configuration management. Ansible provides two ways for users to manage servers: through ad-hoc commands and playbooks. This article focuses on how to configure servers using playbooks.

What is Ansible Playbook?

Ansible Playbook is a script file - written in YAML format - that defines the tasks required to configure servers. Ansible executes the listed tasks on the target machine sequentially. Playbooks allow us to create complex, repeatable, and scalable automation workflows by using scripts.

It also allows us to send scripted commands to remote computers. That enables us to remotely configure computers using Ansible commands from the command line. We can use it to perform simple tasks, such as restarting multiple servers sequentially. We can also use it for complex tasks, such as deploying hundreds of VMs in a private and public cloud.

How Ansible Playbook Works?

An Ansible Playbook defines the desired state of a system and then executes a series of tasks to get the system there. The playbook is made up of one or several plays. Each play contains a series of tasks that are executed sequentially on the target machines. The playbook is complete once all the tasks and plays in the playbook are completed.

Playbooks use modules to perform actions on target hosts. Modules are programs that contain functionality such as managing files, installing packages, or manipulating configurations.

Ansible Playbook Building Blocks

Below are the components needed to create a playbook:

Hosts

The host section lists the servers/computers where the playbook will be executed. The data in this section is derived from Ansible's inventory file.

Hosts can be defined at various levels, including globally, for specific groups of hosts, or even within a task. Using hosts allows you to target specific machines or groups of machines with different tasks and configurations.

Variables

Variables store values that can be used throughout the playbook. They can be defined at various levels, including globally, for specific hosts or groups of hosts, or even within a task. Variables can be used to make playbooks more dynamic and flexible, allowing them to adapt to different environments and situations. They can also be used to store sensitive information, such as passwords or API keys, which can be encrypted for added security.

Inventory file

This is a file or a set of files that define the hosts or groups on which the playbook operates. Without this file, the playbook will not know where the tasks defined in the playbook need to run.

[webservers]
192.168.33.21
192.168.33.22
192.168.33.23
[dbservers]
172.13.4.41

Tasks

Tasks are a list of actions that need to be performed in the playbooks. The list can contain tasks such as installing software, configuring services, and updating files, among others.

Handlers

A handler is a type of special task that is activated by notifications. It is used to send out notifications when there are changes in the configuration files. The handlers run at the end of each play.

How to Write an Ansible Playbook?

Now that you know the basics of an Ansible Playbook, let’s create one that installs and starts Apache servers.

Prerequisites

Ansible is a prerequisite to writing and running a playbook, so make sure you have it installed on your system. If you don’t have it, follow this guide to install it. In this demo, I’m using Ansible 2.14.5, which is installed on Ubuntu 22.04.

Using Ansible Playbook

Let's get started. Open a terminal and run the command below to check Ansible's version.

ansible --version

Below is the output we get after executing the command:

ansible version

Run the ansible-playbook command to see all the usage options that Ansible offers while using a playbook.

ansible-playbook

Below is the list of commands that you can use to run an Ansible playbook:

We will start by creating a directory and navigating to it. To do that, run the commands below:

mkdir playbookDemo

cd playbookDemo/

Below is the output we get after creating a playbookDemo directory:

Next, we will create an inventory file and name it inventory.ini

gedit inventory.ini

This inventory file defines target hosts where you want to deploy the playbook tasks. Here, we have defined a single target, but you can define multiple targets. We will use the name ‘clients’ to reference our host while creating the playbook file. Below is a screenshot of the inventory.ini file

Defining Tasks in Ansible Playbooks

Now, create a playbook definition file, demo.yml. The file will contain a list of all the tasks required to install and start the Apache service on the target host mentioned in the inventory file.

gedit demo.yml

Add the code below to the demo.yml file.

---
- name: Install and Start Apache
hosts: clients
become: true
tasks:
- name: Update package cache
apt:
update_cache: yes
- name: Install Apache
apt:
name: apache2
state: present
- name: Start Apache service
service:
name: apache2
state: started
enabled: true

Every playbook starts by defining the hosts. We have defined ‘clients’ as hosts, which we added to the inventory.ini file. In this manifest file, we are defining three tasks. The first task will use the apt module to update the package. The second task installs Apache, and the third task starts the Apache service.

Finally, run the ansible-playbook command as shown below. This will connect to the hosts specified in the inventory.ini file and execute the tasks defined in the demo.yml file.

ansible-playbook -i inventory.ini demo.yml

Below is the output we get after all the tasks in the demo.yml are executed:

As you can see in the above screenshot, the ansible-playbook ran successfully and executed all the tasks.

You can now run the command below to verify that the Apache service has been successfully installed on the host.

dpkg --get-selections | grep apache

The output captured in the screenshot below shows that the installation of Apache was completed successfully.

How To Use Variables in Ansible Playbooks

In this section, we shall use the inventory file we created in the previous step to demonstrate how to use variables. Let’s create another playbook by running the command below:

gedit demo_vars.yml

Add the code below to the demo_vars.yml file.

---
- name: Install and Start Apache
hosts: clients
become: true
vars:
package_name: apache2
service_name: apache2
config_file: /etc/apache2/apache2.conf
tasks:
- name: Update package cache
apt:
update_cache: yes
- name: Install Apache
apt:
name: "{{ package_name }}"
state: present
- name: Start Apache service
service:
name: "{{ service_name }}"
state: started
enabled: true
- name: Print Apache configuration file path
debug:
var: config_file

In this updated playbook, we have added three variables in the vars section:

  • package_name: References the name of the Apache package to be installed (e.g., apache2).
  • service_name: References the name of the Apache service.
  • config_file: References the path to the Apache configuration file (e.g., /etc/apache2/apache2.conf).

Next, run the demo_vars.yml playbook using the command below:

ansible-playbook -i inventory.ini demo_vars.yml

Below is the output we get after executing the command above:

Ansible connects to the hosts mentioned in the inventory.ini file and executes the tasks defined in the demo_vars.yml file. It installs and starts Apache on the host using the specified variable values.

Master infrastructure management with our IaC Learning path:

Infrastructure as Code (IaC) Training Roadmap | Kodekloud
Explore the Infrastructure as Code (IaC) training roadmap designed by our industry experts. Master the art of IaC with proven study roadmap and resources.

Conclusion

In this article, you learned what the Ansible playbook is and its building blocks. You also saw from the example how to write and run playbooks. This was just an introduction to this powerful tool; it can do much more.


More on IaC: