Lesson 8 of 13 · 25m
Delegation, run_once, and the Rolling Update
serial batches, delegate_to for LB drains, run_once per slice, and async — the choreography that turns a playbook into a deploy.
A deploy is not a config change. A config change is a file landing on a host; a deploy is a choreography — drain the node, upgrade it, health-check it, put it back — where the steps happen in order, on the right machines, once each. serial, delegate_to, and run_once are the three keywords that turn a playbook from a batch command into that choreography. Most teams discover them after their first "we took down the whole pool at once" deploy.
serial: slices instead of the whole fleet
- name: Roll the web tier
hosts: webservers
serial: "30%"
max_fail_percentage: 10Without serial, a play targets every matched host at once (bounded only by forks). With it, Ansible runs the entire play — every task, every handler — against one slice at a time: 30% of webservers, then the next 30%. serial also takes counts (serial: 5) and lists (serial: ["10%", "30%", "100%"] — a canary slice, then confidence, then the rest). max_fail_percentage: 10 aborts the run if a tenth of the batch fails — the difference between "one bad canary" and "every slice ran the broken deploy."
ansible_play_batch is the magic variable that holds the current slice's hostnames — the thing your drain/undrain logic actually iterates.
delegate_to: run the task somewhere else
- name: Drain from the load balancer
community.general.haproxy:
state: disabled
host: "{{ inventory_hostname }}"
backend: app_back
delegate_to: lb01.acme.corp
- name: Drain via the stats socket instead
ansible.builtin.command: >
sh -c "echo 'disable server app_back/{{ inventory_hostname }}' |
socat stdio /var/lib/haproxy/stats"
delegate_to: lb01.acme.corpdelegate_to: runs the task on a different host, with {{ inventory_hostname }} still bound to the play's target — the web node is the subject, the LB is the instrument. The canonical use is draining; it also fits "create a DNS record on the API host," "snapshot the VM on the hypervisor," "add the node to monitoring on the Nagios box." local_action is the old spelling of delegate_to: localhost.
Two details that matter. A delegated task still evaluates when: and loop for the target host — the context stays anchored even though the execution moved. And delegate_to: localhost plus command/shell/raw runs code on your control node — a fact to remember when reading playbooks you didn't write.
run_once: once per batch, not once per host
- name: Announce the deploy window
ansible.builtin.uri:
url: "https://chat.acme.corp/hooks/deploys"
method: POST
body_format: json
body: { text: "web deploy starting: {{ ansible_play_batch }}" }
run_once: true
delegate_to: localhostrun_once executes on the first host of the batch and skips the rest — "open the ticket," "freeze the queue," "acquire the deploy lock." The nuance that bites: with serial, it runs once per slice, not once per play. On a serial: "30%" roll that's three announcements, which is usually what you want — and a silent triple-execute when it isn't. For genuinely-once semantics across slices, gate on inventory_hostname == ansible_play_hosts[0] or move the step to a separate play with hosts: webservers[0] or localhost.
The canonical rolling update, assembled
- name: Rolling deploy
hosts: webservers
serial: "30%"
max_fail_percentage: 10
tasks:
- name: Drain
community.general.haproxy: { state: disabled, host: "{{ inventory_hostname }}", backend: app_back }
delegate_to: lb01.acme.corp
- name: Wait for connections to bleed off
ansible.builtin.wait_for: { timeout: 10 }
- name: Deploy
ansible.builtin.apt: { name: "acme-app={{ app_version }}", state: present }
notify: Restart acme-app
- name: Health-check before rejoining
ansible.builtin.uri:
url: "http://{{ inventory_hostname }}:8080/healthz"
status_code: 200
register: health
retries: 12
delay: 10
until: health.status == 200
- name: Rejoin the pool
community.general.haproxy: { state: enabled, host: "{{ inventory_hostname }}", backend: app_back }
delegate_to: lb01.acme.corpHandlers fire at the end of each batch in a serial play — notify: Restart inside the slice restarts the app while the slice is still drained. The health-check until is what makes this a deploy and not a coin flip: a node that never comes healthy fails its slice, max_fail_percentage stops the roll, and the rest of the pool is still serving.
async: work that outlives the SSH session
- name: Kick the schema migration
ansible.builtin.command: /opt/app/bin/migrate
async: 7200 # seconds the job may run
poll: 0 # don't wait — fire and return
register: migration
- name: Collect it
ansible.builtin.async_status: { jid: "{{ migration.ansible_job_id }}" }
register: job
until: job.finished
retries: 60
delay: 30async lets a task outlive the connection — a two-hour migration, a kernel rebuild — while poll: 0 returns immediately with a job ID; async_status + until collects it later. poll: 0 without a collecting async_status is fire-and-forget, which is a rumor, not a result.
Field notes
delegate_tochanges where the module runs, not who it talks about — keep{{ inventory_hostname }}in the args so the drain hits the right backend.run_once+delegate_to: localhostis how "once total" (create the LB pool, open the change window) stays once.- A failed slice still runs
serial's post-batch handler flush for the hosts that succeeded — your drained-and-fixed node does get its reload, even when the run aborts later.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Self-Hosting Prometheus and Grafana: Infrastructure Monitoring That Actually Works
Build a production-grade monitoring stack with Prometheus and Grafana from scratch. Covers architecture, Docker Compose deployment, Node Exporter, alerting with Alertmanager, PromQL from basics to advanced, pre-built dashboards, and everything SudoSecurity uses to monitor its own infrastructure.
Zero Trust Everything: The Complete Guide to Self-Hosting Teleport for Secure Infrastructure Access
SudoSecurity runs Teleport internally for everything — admin panel access, secure database connections, Kubernetes, and zero-trust philosophy across our entire team. This is the complete technical guide to installing, configuring, and running your own self-hosted Teleport cluster from scratch.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
AWS Emulator Puts AWS on Your Laptop. Keep Your IAM Tests Off It.
AWS released AWS Emulator on November 11, a free local server that answers AWS API calls on 127.0.0.1 with per-run keys and fresh certificates.