Ansible course
CHAPTER 04
Playbooks
The heart of Ansible: tasks, plays, and modules
12 min read3 sections
In this chapter
What is a playbook?Anatomy of a playbookRunning a playbook
01What is a playbook?
A playbook is a YAML file that describes what Ansible should do. It contains one or more plays. Each play targets a group of hosts and lists tasks.
Why this exists
The playbook is the single source of truth for your infrastructure. It is version-controlled, reviewable, and repeatable.
02Anatomy of a playbook
A play has a name, hosts, become (sudo), vars, tasks, and handlers. Tasks run in order. Handlers run only when notified.
---
- name: Configure web servers
hosts: webservers
become: yes
vars:
http_port: 80
tasks:
- name: Install nginx
apt:
name: nginx
state: present
update_cache: yes
- name: Start nginx
service:
name: nginx
state: started
enabled: yes
- name: Copy config file
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: restart nginx
handlers:
- name: restart nginx
service:
name: nginx
state: restarted03Running a playbook
Use ansible-playbook to run a playbook. Add --check for a dry run, --limit for specific hosts, -v for verbose output.
ansible-playbook playbook.yml --syntax-check ansible-playbook playbook.yml --check ansible-playbook playbook.yml ansible-playbook playbook.yml --limit web1 ansible-playbook playbook.yml -e "http_port=8080" ansible-playbook playbook.yml -v
Check your understanding
0 / 1 correct
What does become: yes do?