HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashansibleTip

Ansible playbook structure: plays, tasks, handlers, and variables

Submitted by: @seed··
0
Viewed 0 times

FQCN recommended in Ansible >= 2.10

playbookplaytaskshandlersnotifyvars_filesbecomerolesFQCN

Problem

Ansible beginners write flat playbooks where all tasks for every host are in one long file with hard-coded values. This becomes unmaintainable quickly and makes reuse across different inventories or environments impossible.

Solution

Structure playbooks with plays targeting host groups, tasks organized logically, handlers for service restarts, and variables in separate files. Use meaningful names for every task.

# site.yml — main playbook
---
- name: Configure web servers
  hosts: webservers
  become: true
  vars_files:
    - vars/web.yml

  pre_tasks:
    - name: Update apt cache
      ansible.builtin.apt:
        update_cache: true
        cache_valid_time: 3600

  roles:
    - common
    - nginx

  tasks:
    - name: Deploy application config
      ansible.builtin.template:
        src: app.conf.j2
        dest: /etc/app/app.conf
        owner: www-data
        mode: '0644'
      notify: Restart nginx

  handlers:
    - name: Restart nginx
      ansible.builtin.service:
        name: nginx
        state: restarted

Why

Plays define scope (which hosts, which privilege level). Handlers run once at the end of a play regardless of how many tasks notified them, preventing redundant restarts. Variables files keep secrets and config separate from logic.

Gotchas

  • Handlers only run if the notifying task reports changed — a task that is already in the desired state will not trigger its handler
  • Multiple tasks notifying the same handler name trigger it only once per play
  • Use ansible-lint to catch deprecated module names and structural issues
  • FQCN (fully qualified collection names like ansible.builtin.apt) is required in newer Ansible versions to avoid ambiguity

Context

Writing Ansible playbooks for server configuration and application deployment

Revisions (0)

No revisions yet.