What is a playbook?
A playbook is a YAML file that defines what to automate on which hosts — a reusable alternative to ad-hoc commands.
Ad-hoc → one-off commands
Playbook → versioned, multi-step automation
Why playbooks matter
- Repeatable deployments
- Reviewable in Git
- Multiple tasks in order
- Same outcome across many servers
Basic structure
---
- name: Install and Start Nginx
hosts: all
become: true
tasks:
- name: Update apt cache
apt:
update_cache: true
- name: Install nginx
apt:
name: nginx
state: present
- name: Start nginx
service:
name: nginx
state: started
- name: Enable nginx
service:
name: nginx
enabled: true| Keyword | Meaning |
|---|---|
name | Play / task description |
hosts | Inventory target |
become | Privilege escalation (sudo) |
tasks | Ordered list of module calls |
File extension: .yml or .yaml.
Hands-on
mkdir -p ~/ansible-project/playbooks
cd ~/ansible-project
vim playbooks/nginx.yml
# paste the playbook above
ansible-playbook playbooks/nginx.ymlFlow:
Control node
↓
Reads playbook
↓
SSH to EC2
↓
Runs tasks in order
Open http://<managed-public-ip> to verify Nginx.
Syntax check & dry run
ansible-playbook playbooks/nginx.yml --syntax-check
ansible-playbook playbooks/nginx.yml --check
ansible-playbook playbooks/nginx.yml -vPlaybook vs ad-hoc
| Ad-hoc | Playbook |
|---|---|
| Quick one-liners | Multi-step automation |
| Hard to version | Lives in Git |
| Easy for ping/uptime | Best for real deploys |
Folder structure
ansible-project/
├── ansible.cfg
├── inventory.ini
└── playbooks/
└── nginx.yml
Mini project — deploy a static page
echo '<h1>Hello from Ansible</h1>' > playbooks/index.html---
- name: Deploy Nginx website
hosts: all
become: true
tasks:
- name: Install nginx
apt:
name: nginx
state: present
- name: Start nginx
service:
name: nginx
state: started
enabled: true
- name: Copy index.html
copy:
src: index.html
dest: /var/www/html/index.htmlansible-playbook playbooks/site.ymlInterview: a playbook is YAML automation executed by Ansible against inventory hosts. Prefer playbooks over ad-hoc for anything you will run more than once.