While ad hoc commands are indispensable for learning Ansible and executing one time tasks, playbooks are real workhorses. In this introductory post I will explain the essence of a playbook on example.
So what is a playbook?
At the first glance, it’s a file written in YAML that contains a list of plays. If we look closer, we’ll see that a playbook file is a mixture of configuration and script concepts. On one hand, it specifies the desired configuration of systems. On the other hand, like in a script, it defines in which order tasks must be executed in a play.
It’s better to see once than to hear 100 times. This is a playbook we’ll use as an example:
---
- hosts: frontend,backend
remote_user: yury
become: True
tasks:
- name: ensure golang is at the latest version
apt: name=golang state=latest
- hosts: frontend
remote_user: yury
become: True
tasks:
- name: ensure apache is at the latest version
apt: name=apache2 state=latest
- name: write the apache config file
template:
src: conf/apache2.j2
dest: /etc/apache2/apache2.conf
notify:
- restart apache
- name: ensure apache is running
service:
name: apache2
state: started
handlers:
- name: restart apache
service:
name: apache2
state: restarted