Interview Prep/Real-World Interview/Write-an-Ansible-playbook tasks

Write a playbook that runs a database migration once, even though it targets 5 app servers.

AdvancedHands-onWrite-an-Ansible-playbook tasks
Answer
# Play 1: migrate exactly once, on one host
- hosts: app[0]
  become: true
  tasks:
    - name: Run migrations
      ansible.builtin.command: /opt/app/bin/migrate --to "{{ version }}"
      register: mig
      changed_when: "'No migrations to run' not in mig.stdout"

# Play 2: rolling deploy across all app servers
- hosts: app
  become: true
  serial: 1
  roles:
    - nodeapp

Key trick → run_once runs on the first host of the current batch, so combined with serial: 1 it would run 5 times. A separate first play targeting app[0] guarantees exactly one run, and if it fails the deploy play never starts. Without serial, run_once: true on the task is enough.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-an-Ansible-playbook tasks