Introduction to Ansible Playbook – Part 1

We have already seen how to run an Ansible task using the AdHoc method in the Adhoc tutorial. Though useful for simple tasks like installing a package or executing a command on all servers, this is not helpful when dealing with multiple tasks.

Ansible Playbook is the solution for such scenarios. Playbooks are the configuration, deployment and orchestration language of Ansible.

In its basic form, a playbook is a YAML file consisting of one or more tasks. Apart from the tasks, we can also include variables, files, templates, etc. It’s very easy to understand a YAML file, as you will see later in this tutorial.

In the advanced form, there will be many plays in a playbook, with corresponding tasks(plays) in different folders, each folder containing dependent variables, files,  templates, custom modules, etc. We will be covering that in a later session.

Creating an Ansible Playbook

As mentioned in the AdHoc tutorial, we need to update the inventory list first, with the remote servers you intend to manage. But in this example, instead of the default inventory location I will be using another location. You can specify the location of the inventory file using ‘-i ‘ argument in the command. For more information refer inventory files tutorial.

sudo vim /home/mdtutorials2/inventory.ini

So let us start with the actual playbook creation. Create a new file with .yaml extension.

touch helloplaybook.yaml

For the first example, we will take the command mentioned in the AdHoc Ansible tutorial post and convert it to an Ansible playbook format.

adhoc command -> ansible all -m shell -a "wall Hello to ansible"

Ansible playbook for the above command

- hosts: all
  - name: "wall command"
    shell: "wall Hello to Ansible"

hosts: The set of remote servers in which you intend to execute the command. ‘all‘ means all the servers specified in the inventory file.

tasks: A series of commands which you will be running on the remote systems.

name: A text to identify the task in the execution output. If it is not given, then the name of the module will be taken.

shell: Name of the module used.

Make sure the indentation is correct. Else the execution will throw an error.

You can run the ansible playbook using the following command.

ansible-playbook -s -i inventory.ini helloplaybook.yaml

Ansible Playbook Ubuntu

In the above GIF, I am executing the Ansible playbook, and the task is executed on the remote servers. In the end, a playbook summary will be shown which shows the details of the tasks just completed. It will show how many tasks didn’t change the system status, how many changed and how many tasks failed.

The wall command Ansible Playbook still runs only one command. Let us look at the advanced model in the next Ansible Playbook tutorial.