Ansible Playbook: Write and Run Your First Playbook (Complete Guide)
By Luca Berton · Published 2024-01-01 · Category: installation
How to write and run Ansible playbooks. Complete guide to playbook structure, plays, tasks, variables, handlers, loops, conditionals, and best practices with examples.
Ansible Playbook: Write and Run Your First Playbook (Complete Guide)
An Ansible playbook is a YAML file that defines automation tasks to run on remote hosts. Playbooks are the core of Ansible — they describe the desired state of your infrastructure in a human-readable format.
Playbook Structure
Run a Playbook
Variables
Variable Files
Register Task Output
Conditionals
Loops
Handlers
Error Handling
Tags
Include and Import
Complete Example: Web App Deployment
FAQ
What is an Ansible playbook?
An Ansible playbook is a YAML file containing one or more plays. Each play maps a group of hosts to tasks that define the desired state. Playbooks are the primary way to automate configuration, deployment, and orchestration with Ansible.
How do I run an Ansible playbook?
Use ansible-playbook playbook.yml. Add -i inventory.ini to specify an inventory, --check for dry run, -e "var=value" for extra variables, and -v for verbose output.
What is the difference between import_tasks and include_tasks?
import_tasks is static — parsed at load time, supports tags, but can't use loops or runtime variables. include_tasks is dynamic — parsed at runtime, supports loops and conditionals, but tags don't propagate the same way.
How do I pass variables to a playbook?
Use -e on the command line (-e "version=2.0"), define in vars: section, load from vars_files:, or set in inventory. Variables from -e have the highest precedence.
What is check mode in Ansible?
Check mode (--check) is a dry run — Ansible reports what would change without making actual changes. Add --diff to see the exact differences. Not all modules support check mode.
Conclusion
Playbooks are the heart of Ansible automation. Master the structure — plays, tasks, variables, handlers, conditionals, and loops — and you can automate any infrastructure task reliably and repeatably.
Related Articles • Getting Started with Ansible • Ansible Inventory: Complete Guide • Ansible Roles: Organize Your Playbooks
Category: installation