How to write Ansible playbooks?
· Category: DevOps & CI/CD
Short answer
An Ansible playbook is a YAML file containing a list of plays. Each play targets a group of hosts and defines a series of tasks to execute.
Steps
- Define the play and target hosts.
- Set variables and handlers.
- List tasks using modules.
- Run the playbook with
ansible-playbook.
Example
---
- name: Deploy web app
hosts: webservers
vars:
app_version: "1.2.3"
tasks:
- name: Copy application code
copy:
src: ./app
dest: /var/www/app
- name: Restart nginx
service:
name: nginx
state: restarted
Tips
- Use handlers for efficient notification.
- Use
tagsto run subsets of tasks. - Keep playbooks idempotent.
Common issues
- YAML indentation errors are common.
- Tasks run in order; failures stop execution unless
ignore_errorsis set. - Variables can be overridden in multiple places.