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.
More on Write-an-Ansible-playbook tasks
Write a playbook that installs and starts Nginx on Ubuntu web servers.BeginnerWrite an inventory with groups, a group of groups, and per-group variables.BeginnerWrite a playbook that deploys a config file from a Jinja2 template and restarts the service only if it changed.BeginnerWrite a role structure for a Node.js app and show what goes in each folder.IntermediateWrite a task that creates multiple users with SSH keys from a list.BeginnerWrite a rolling deploy playbook: 2 servers at a time, removed from the load balancer during the update.Advanced