Hi! Welcome to Ansible learning.
Before learning about how to write a playbook let us first understand what is a playbook?
Playbook is nothing but an YAML file where we write the steps that we intend to automate using Ansible. So we communicate with Ansible using Playbook i.e YAML file and execute it with ansible-playbook command. You must be wondering what we write in Playbook. We shall go into it but before that let us understand some basic terms in Playbooks.
Every Playbook consists of one or more Play in a list. You must be woundering what a play is. Play is the end to end scenario that we intend to implment for a host. Example if you want to deploy an application in a host using ansible the scenario to deploy application is called a play.
Every play is divided into tasks if we take the previous example to deploy an application we need to setup the environment initially. Setting up the environment is like a task. So in a play we have one or more tasks and the tasks are executed sequentially one after the other. In every task we call modules to do specific job and get the work done. You can have a look at the below picture have a better understanding.
Now that we learnt about the contents of a playbook we shall see how we write them in the actual code. For that we need to understand some basic things in YAML which you can by clicking here.
Coming to the playbooks we shall now write a sample playbook to get python version in stages.
- Every playbook starts with — and next we add list of plays in it.
- So as in YAML we represent list elements by a single dash – so in play book preceede with a – and next we add a key value pairs like name (keyword name), host (keyword hosts) on which we wish the ansible to do configuration management or whatever it is.
- In the next steps we add the tasks which are identified by tasks keyword and every task should be given a meaning full name because this is what we see in the output when we run the playbook. The name is given by keyword name.
- Since we already learnt that we call modules in tasks so we need to list these as elements of list and we do it the same way we did for a play i.e preceeding with a –
- Now we write the module we wish to use to get our job done and additionally we add – debug: var=stdout.stdout_lines to print the output in ansible console (getting the output using debug module).
---
- name: a sample play to start with
hosts: all
tasks:
- name: get python version
command: python3 --version
- debug: var=stdout.stdout_lines
Now run the above playbook using ansible-playbook command see the output.
Now we have learnt the basic terminology and structure of a very simple and basic playbook. We will use this and expand our playbook to do more complex flows.