Ansible — Playbooks
Let’s continue learning more about Ansible. I’ve covered some basics in my previous blog. Now I want to learn about Playbooks in Ansible.
What are Playbooks?
Playbooks are the files where Ansible code is written. Playbooks are written in YAML format. YAML stands for Yet Another Markup Language. Playbooks are one of the core features of Ansible and tell Ansible what to execute. They are like a to-do list for Ansible that contains a list of tasks.
Playbooks contain the steps which the user wants to execute on a particular machine. Playbooks are run sequentially. Playbooks are the building blocks for all the use cases of Ansible.
How to Create a Playbooks
Playbooks are expressed in YAML format. YAML stands for Yet Another Markup Language. However, according to official documentation of YAML: “YAML Ain’t Markup Language. YAML is a human friendly data serialization
standard for all programming languages”.
First, we start by creating a YAML file:
$ touch /etc/ansible/main.yml
Where main.yml is the name of the file.
Once I created the file, to run the playbook I just created, I can run the following:
$ ansible-playbook /etc/ansible/main.yml -i /etc/ansible/hosts
Where:
- ansible-playbook is the command we are using to manipulate playbooks
- -i /etc/ansible/hosts is path for my inventory file
Please Note:
If you are using the default inventory file you don’t need to include -i /etc/ansible/hosts
As you can see below, both options work fine.
I created the playbook, but the file is empty that’s why I am getting this error. Each playbook consist of one or more “plays” in it. As I understood from the official Ansible documentation, each YAML file (that we are using in Ansible ) consist of one or more lists. Each list consists of items. Item represents a key-value pair.
In order to fix it, I need to modify my playbook file:
$ sudo vi /etc/ansible/main.yml
Let’s start by adding three dashes on the first line. According to YAML syntax, three dashes indicate the beginning of the file.
Next, let’s add the most basic ‘play’ ever:
Once we save & exit. We can check if that works:
Congratulations on creating your first & most basic Ansible Playbook!