Part 7 – Ansible Tasks, Plays, PlayBooks

PlayBooks is the term used in Ansible to represent a configuration management scripts written in YAML. Tasks are the operations that needs to be done on the remote machines, hosts are the remote machines on which the tasks are to be executed. Tasks are always associated with hosts and this together is called a Play. PlayBook is a collection of such Plays.

PlayBooks are written in YAML and saved to a file with extension .yml, a Play can have multiple tasks i.e multiple tasks can be associated with a particular hosts mentioned. Each task can have optional parameters like name which is most commonly used as this helps in identifying the tasks easily. Let’s look at each one of them briefly.

Task

tasks:
- yum: name=httpd state=present

Play

- hosts: web
  tasks:
  - yum: name=httpd state=present
  - service: name=httpd enable=yes state=started

PlayBook

---
- hosts: web
  tasks:
  - yum: name=httpd state=present
  - service: name=httpd enable=yes state=started
- hosts: db
  tasks:
  - yum: name=git state=present

From the above examples, you can see that my_playbook.yml has two plays, one play to install and start Apache service and another to just install Git. To make it more readable and understandable to others, we add the optional name parameter to tasks. Below is my final playbook.

2017-04-04 17_42_03-vagrant@ansi_ ~_my_ansible

 

 

Note: If a task in a play fails, the rest of the play is not executed for that particular host. Because in our example, if apache installation fails, it doesn’t make any sense to start the service.

Running a PlayBook

$ ansible-playbook -i my_inventory my_playbook.yml

2017-04-04 18_12_52-vagrant@ansi_ ~_my_ansible

Playbooks gather facts (setup module) for every host by default. This is a time consuming process if there are hundreds of servers. To avoid this, we can specify the parameter gather_facts: no

2017-04-04 18_20_15-vagrant@ansi_ ~_my_ansible

Hope this was informative. Thanks!

 Part 1 – Introduction to Ansible

Part 2 – Ansible Lab Setup

Part 3 – Understanding our First Ansible Command

Part 4 – More about Inventory File

Part 5 – Ansible Config

Part 6 – Ansible Modules

Part 7 – Ansible Tasks, Plays, PlayBooks

Part 8 – Ansible Play Recap, vars, Notify, Handlers

Part 9 – Ansible Roles

 

Advertisements

#gather_facts, #play, #playbooks, #tasks