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.
tasks: - yum: name=httpd state=present
- hosts: web tasks: - yum: name=httpd state=present - service: name=httpd enable=yes state=started
--- - 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.
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
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
Hope this was informative. Thanks!