Interview Prep/Ansible/Variables, Facts and Precedence Problems

A database migration with `run_once: true` ran four times in a rolling deploy with `serial: 25%`

AdvancedTroubleshootingVariables, Facts and Precedence Problems
Answer

Likely causes → run_once means once per batch. With serial, each batch is a separate pass through the play, so the task runs once per batch.

Fix → Move one-time steps into their own play before the rolling play:

- name: Migrate once
  hosts: app[0]
  tasks:
    - ansible.builtin.command: /opt/app/bin/migrate
- name: Rolling deploy
  hosts: app
  serial: "25%"
  roles: [app]

Or guard the task with when: inventory_hostname == ansible_play_hosts_all[0].

Prevent → Make migrations idempotent (track a version in a migrations table), so that a repeated run is harmless anyway.

All Ansible questions Roadmap: Ansible

More on Variables, Facts and Precedence Problems