You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
A playbook is the heart of Ansible automation. While ad-hoc commands handle one-off tasks, playbooks let you define complex, multi-step workflows in a structured, repeatable, and version-controlled YAML file.
A playbook is a YAML file containing one or more plays. Each play maps a group of hosts to a set of tasks to be executed.
Playbook
+-- Play 1 (hosts: webservers)
| +-- Task 1
| +-- Task 2
| +-- Task 3
+-- Play 2 (hosts: dbservers)
+-- Task 1
+-- Task 2
- ): )# A list
fruits:
- apple
- banana
- cherry
# A dictionary
server:
name: web1
port: 80
enabled: true
---
- name: Configure web servers
hosts: webservers
become: true
tasks:
- name: Install nginx
apt:
name: nginx
state: present
update_cache: true
- name: Copy nginx configuration
copy:
src: files/nginx.conf
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'
- name: Ensure nginx is running
service:
name: nginx
state: started
enabled: true
| Keyword | Description |
|---|---|
| name | A descriptive name for the play |
| hosts | The host pattern to target (from inventory) |
| become | Enable privilege escalation |
| become_user | The user to escalate to (default: root) |
| gather_facts | Whether to collect system facts (default: true) |
| vars | Variables defined at the play level |
| vars_files | External variable files to include |
| tasks | The list of tasks to execute |
| handlers | Tasks triggered by notifications |
| roles | Roles to apply to the hosts |
| serial | Number or percentage of hosts to process at a time |
| max_fail_percentage | Maximum failure percentage before aborting |
# Basic execution
ansible-playbook site.yml
# Specify an inventory
ansible-playbook -i production site.yml
# Limit to specific hosts
ansible-playbook site.yml --limit web1.example.com
# Dry run (check mode)
ansible-playbook site.yml --check
# Show differences in file content
ansible-playbook site.yml --diff
# Step through tasks one at a time
ansible-playbook site.yml --step
# Start at a specific task
ansible-playbook site.yml --start-at-task "Copy nginx configuration"
Handlers are tasks that run only when notified by other tasks. They are typically used for actions like restarting a service after a configuration change:
---
- name: Configure web servers
hosts: webservers
become: true
tasks:
- name: Copy nginx configuration
copy:
src: files/nginx.conf
dest: /etc/nginx/nginx.conf
notify: Restart nginx
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.