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

  1. Define the play and target hosts.
  2. Set variables and handlers.
  3. List tasks using modules.
  4. 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 tags to run subsets of tasks.
  • Keep playbooks idempotent.

Common issues

  • YAML indentation errors are common.
  • Tasks run in order; failures stop execution unless ignore_errors is set.
  • Variables can be overridden in multiple places.