Infrastructure as code · Advanced · 22 min
Roll out changes to a fleet in batches with Ansible serial and failure limits
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · ansible-core 2.22.0
You will roll a release across six web servers, starting with one canary host and then in growing batches, with load balancer draining, health checks, a run-once migration and failure limits that stop the rollout when a host breaks.
On this page
Run a playbook against twenty web servers with the default settings and Ansible changes five at a time, task by task, until every host has the new release. If the release is broken, you find out when all twenty are broken. A rolling update does the opposite: change one server, prove it works, then change a few more, and stop the moment something goes wrong while most of the fleet is still serving the old, working version.
Ansible builds this out of a handful of play and task keywords. serial splits the hosts into batches and finishes the whole play on one batch before starting the next. max_fail_percentage and any_errors_fatal decide when to give up. delegate_to runs a task on another machine, such as the load balancer, on behalf of the host being changed. run_once runs a task a single time for the whole fleet, which is what a database migration needs. throttle caps how many hosts run one task at the same moment.
In this tutorial you put all of them in one rollout. So that you can watch every batch on one machine, the six "web servers" are local folders, each served over HTTP on its own port, and the load balancer is a configuration file in HAProxy's format. The playbooks are the ones you would run against real servers; Step 2 says what changes when you point them at your fleet.
Step 1 · Install ansible-core and start a practice fleet
Install ansible-core with pipx, pinned so your output matches, and curl for checking the servers by hand:
sudo apt update
sudo apt install -y pipx curl
pipx install ansible-core==2.22.0
export PATH="$HOME/.local/bin:$PATH"
mkdir -p ~/ansible-rolling-demo
cd ~/ansible-rolling-demoAdd the PATH line to ~/.bashrc (or run pipx ensurepath and open a new terminal) so the commands are found next time. A pipx install gets no updates from apt; upgrade it later with pipx upgrade ansible-core.
Now build the fleet. Each web server gets a folder holding a version.txt that says 1.0.0, the release it is running today. The load balancer file lists all six as backends:
mkdir -p lb db api logs
for i in 1 2 3 4 5 6; do
mkdir -p "fleet/web-$i"
echo 1.0.0 > "fleet/web-$i/version.txt"
done
echo ok > api/index.html
printf 'backend web\n' > lb/backends.cfg
for i in 1 2 3 4 5 6; do
printf ' server web-%s 127.0.0.1:808%s check\n' "$i" "$i" >> lb/backends.cfg
done
cat lb/backends.cfgStart one small HTTP server per web host on ports 8081 to 8086, and a seventh on port 8090 that stands in for a status API your team uses to record releases. Their process IDs go in fleet.pids so you can stop them at the end:
for i in 1 2 3 4 5 6; do
python3 -m http.server "808$i" --bind 127.0.0.1 --directory "fleet/web-$i" > "logs/web-$i.log" 2>&1 &
echo $! >> fleet.pids
done
python3 -m http.server 8090 --bind 127.0.0.1 --directory api > logs/api.log 2>&1 &
echo $! >> fleet.pidsCheck it worked
Ask each server which release it is running:
for i in 1 2 3 4 5 6; do
curl -s --retry 5 --retry-connrefused --retry-delay 1 "http://127.0.0.1:808$i/version.txt"
doneYou see 1.0.0 six times. If a line says Connection refused after the retries, that server did not start: check logs/web-<n>.log for a port that is already in use.
Step 2 · Describe the fleet in an inventory
Put the inventory in its own inventory/ folder, with its group_vars/ and host_vars/ next to it. Keeping it apart from the playbooks means there is only one place Ansible reads host variables from.
mkdir -p inventory/group_vars inventory/host_vars
cat > inventory/hosts.yml <<'YAML'
all:
children:
web:
hosts:
web-1: {ansible_host: 127.0.0.1, app_port: 8081}
web-2: {ansible_host: 127.0.0.1, app_port: 8082}
web-3: {ansible_host: 127.0.0.1, app_port: 8083}
web-4: {ansible_host: 127.0.0.1, app_port: 8084}
web-5: {ansible_host: 127.0.0.1, app_port: 8085}
web-6: {ansible_host: 127.0.0.1, app_port: 8086}
lb:
hosts:
lb-1:
db:
hosts:
db-1:
YAML
cat > inventory/group_vars/all.yml <<'YAML'
ansible_connection: local
ansible_python_interpreter: "{{ ansible_playbook_python }}"
lb_config: "{{ playbook_dir }}/lb/backends.cfg"
status_api_url: http://127.0.0.1:8090/
YAML
cat > inventory/group_vars/web.yml <<'YAML'
app_dir: "{{ playbook_dir }}/fleet/{{ inventory_hostname }}"
YAMLansible_connection: local makes every host name an alias for this machine, which is what lets six hosts, a load balancer and a database live on one laptop. For your real fleet, delete that line and the interpreter line, set ansible_host to each server's address, and point app_dir and lb_config at the real paths, such as /srv/app and /etc/haproxy/haproxy.cfg. The playbooks do not change.
app_dir lives in group_vars/web.yml, not in the playbook, on purpose: a value in a play's vars: outranks host_vars, and later you will override it for one host.
Check it worked
ansible-inventory -i inventory/hosts.yml --graph
ansible -i inventory/hosts.yml web -m ansible.builtin.ping -oThe graph shows @web with web-1 to web-6, @lb with lb-1 and @db with db-1. The ping prints six lines that start web-<n> | SUCCESS and end with "ping": "pong".
Step 3 · Write a play that changes one batch at a time
This play is the rollout itself. Read the keywords at the top first:
serial: [1, 2, "100%"]makes three batches. The first is one host, your canary. The second is two hosts. The last value repeats until no hosts are left, and"100%"means "everything that remains", so the third batch is the other three. Ansible runs every task in the play,pre_taskstopost_tasks, on one batch before it starts the next.max_fail_percentage: 30stops the whole rollout if more than 30 per cent of the hosts in the current batch fail. You will see it fire in Step 5.
Then each host goes through the same cycle: out of the load balancer, new release, health check, back in, and a note to the status API.
cat > rolling.yml <<'YAML'
- name: Roll out the new release
hosts: web
gather_facts: false
serial:
- 1
- 2
- "100%"
max_fail_percentage: 30
pre_tasks:
- name: Take the host out of the load balancer
ansible.builtin.lineinfile:
path: "{{ lb_config }}"
regexp: '^\s+server {{ inventory_hostname }} '
state: absent
delegate_to: lb-1
throttle: 1
tasks:
- name: Make sure the release folder exists
ansible.builtin.file:
path: "{{ app_dir }}"
state: directory
mode: "0755"
- name: Install the new release
ansible.builtin.copy:
content: "{{ app_version }}\n"
dest: "{{ app_dir }}/version.txt"
mode: "0644"
post_tasks:
- name: Wait until the host serves the new release
ansible.builtin.uri:
url: "http://{{ ansible_host }}:{{ app_port }}/version.txt"
return_content: true
register: health
until: health.content | default('') | trim == app_version
retries: 3
delay: 2
- name: Put the host back in the load balancer
ansible.builtin.lineinfile:
path: "{{ lb_config }}"
line: " server {{ inventory_hostname }} {{ ansible_host }}:{{ app_port }} check"
delegate_to: lb-1
throttle: 1
- name: Record the release with the status API
ansible.builtin.uri:
url: "{{ status_api_url }}?host={{ inventory_hostname }}&version={{ app_version }}"
throttle: 1
YAMLThree details carry most of the safety:
delegate_to: lb-1runs the load balancer edits on the load balancer, whileinventory_hostnamestill names the web server being changed. On a real HAProxy you would drain the server through its runtime socket with thecommunity.general.haproxymodule instead of editing the file, but the shape of the play is the same.throttle: 1on the load balancer tasks matters as soon as a batch has more than one host. Without it, two hosts would editbackends.cfgat the same moment and one change could overwrite the other. On the status API task it keeps you inside a rate limit of one request at a time. A real status API would take a POST with a token read from an environment variable; this stand-in only logs each request.- The health check comes before "back in the load balancer".
untilre-runs theurirequest up to three more times, two seconds apart, until the page says the new version. If it never does, the task fails, the host stays out of the pool, and users never reach it.
Run it with release 1.1.0 and keep a copy of the output:
ansible-playbook -i inventory/hosts.yml rolling.yml -e app_version=1.1.0 | tee run-1.1.0.logWatch the output: the PLAY [Roll out the new release] header appears three times, once per batch, with one host under the first, two under the second and three under the last.
Check it worked
grep -c '^PLAY \[Roll out the new release\]' run-1.1.0.log
test "$(grep -cE '^web-[1-6] +: .*failed=0' run-1.1.0.log)" -eq 6
for i in 1 2 3 4 5 6; do curl -s "http://127.0.0.1:808$i/version.txt"; done
grep -c '^ server web-' lb/backends.cfg
grep -c 'host=web-' logs/api.logThe first count is 3, one per batch. The test line prints nothing, which means all six recap lines show failed=0. Every server answers 1.1.0, the load balancer lists 6 servers again, and the status API saw 6 requests, one per host.
Step 4 · Check the fleet first and run the migration once
Two jobs belong before the first batch, not inside it. First, make sure the whole fleet is healthy: if one server is already down, a rolling update would take a second one out of the pool and leave you short of capacity. Second, run the database migration, once, before any host gets code that needs the new schema. Write the migration so the old release still works against it (add a column; drop the old one in a later release), because for the length of the rollout both versions serve traffic.
cat > preflight.yml <<'YAML'
- name: Check the fleet before changing anything
hosts: web
gather_facts: false
any_errors_fatal: true
tasks:
- name: Refuse to start without a release number
ansible.builtin.assert:
that: app_version is defined
fail_msg: Pass the release with -e app_version=<version>
run_once: true
- name: Every web server answers before the rollout starts
ansible.builtin.uri:
url: "http://{{ ansible_host }}:{{ app_port }}/version.txt"
- name: Run the database migration once for the whole fleet
ansible.builtin.lineinfile:
path: "{{ playbook_dir }}/db/migrations.log"
line: "migrations applied for release {{ app_version }}"
create: true
mode: "0644"
delegate_to: db-1
run_once: true
YAML
cat > rollout.yml <<'YAML'
- ansible.builtin.import_playbook: preflight.yml
- ansible.builtin.import_playbook: rolling.yml
YAMLany_errors_fatal: true changes what one failure means. Normally a failed host drops out and the others carry on; here any failure ends the play for every host, so the rollout never starts on a fleet that is not ready. This play has no serial, so the check covers all six hosts at once.
run_once: true runs the task on the first host of the play only, and delegate_to: db-1 sends it to the database server. The lineinfile line stands in for your real migration command, such as your framework's migrate; what matters is that it runs one time, not six.
Try the guard: run the rollout without a release number.
ansible-playbook -i inventory/hosts.yml rollout.yml || echo "Stopped before any change"The assert fails, Ansible prints your fail_msg, and then Stopped before any change. Now run it properly with the release you already have:
ansible-playbook -i inventory/hosts.yml rollout.yml -e app_version=1.1.0 | tee run-preflight.logCheck it worked
cat db/migrations.log
test "$(grep -cE '^web-[1-6] +: .*failed=0' run-preflight.log)" -eq 6
curl -s http://127.0.0.1:8084/version.txtmigrations.log holds exactly one line, migrations applied for release 1.1.0, even though six hosts ran the play: the run without a release number stopped before the migration, and run_once kept it to a single run. The recap again shows six hosts with failed=0, and web-4 still answers 1.1.0, because installing the same release twice changes nothing.
Step 5 · Break one host and watch the rollout stop
Now simulate the kind of mistake that rolling updates exist for: a typo in one server's settings. Give web-3 a release folder that its web server does not serve, so the new version lands in the wrong place and the server keeps answering with the old one:
cat > inventory/host_vars/web-3.yml <<'YAML'
# Typo: the release goes to a folder this server does not serve.
app_dir: "{{ playbook_dir }}/fleet/web-3-new"
YAMLRoll out 1.2.0. The playbook exits with an error this time, so the || keeps your terminal session tidy:
ansible-playbook -i inventory/hosts.yml rollout.yml -e app_version=1.2.0 | tee run-1.2.0.log || echo "The rollout stopped early"Follow what happens in the output:
- The pre-flight play passes: all six servers answer, and the migration for
1.2.0runs once. - Batch one, the canary
web-1, upgrades and passes its health check. - Batch two starts on
web-2andweb-3. Both install the release.web-2passes its health check.web-3printsFAILED - RETRYINGthree times, because it still serves1.1.0, then fails. - One failed host out of two is 50 per cent, which exceeds the 30 per cent limit. Ansible prints
NO MORE HOSTS LEFT, marks the rest of the batch as failed, and never starts batch three.
That last point surprises people: web-2 deployed and passed its check, but its "back in the load balancer" task never ran, because Ansible stopped the batch at the task where the limit was crossed. Both hosts in the broken batch stay out of the pool until you decide what to do.
Pick the limit with your batch sizes in mind. The value has to be exceeded, not matched. With 30 here, any failure in the canary batch (100 per cent), one in the batch of two (50 per cent) or one in the batch of three (33 per cent) stops the rollout. A limit of 50 would let one failure in the batch of two through.
Check it worked
Read the recap at the bottom of run-1.2.0.log. Each line counts, per host, the tasks that were ok (including changed ones), changed, unreachable, failed, skipped, rescued and ignored:
grep -A 8 '^PLAY RECAP' run-1.2.0.log
grep -E '^web-3 +: .*failed=1' run-1.2.0.log
grep -E '^web-2 +: .*failed=0' run-1.2.0.log
grep -E '^web-5 +: .*changed=0 .*failed=0' run-1.2.0.log
grep 'NO MORE HOSTS LEFT' run-1.2.0.logweb-3 is the only host with failed=1. web-2 shows failed=0 because none of its tasks failed; it was stopped, not broken. web-4 to web-6 show changed=0: they only took part in the pre-flight checks. Now look at the fleet itself:
cat lb/backends.cfg
test "$(grep -cE '^ +server web-[23] ' lb/backends.cfg)" -eq 0
curl -s http://127.0.0.1:8081/version.txt
curl -s http://127.0.0.1:8084/version.txtThe load balancer lists web-1, web-4, web-5 and web-6, so four of six servers are still taking traffic. web-1 answers 1.2.0 and web-4 still answers 1.1.0: the broken release never reached the second half of the fleet.
Step 6 · Fix the host and finish the rollout
Remove the typo and the stray folder it created, then run the same command again:
rm inventory/host_vars/web-3.yml
rm -r fleet/web-3-new
ansible-playbook -i inventory/hosts.yml rollout.yml -e app_version=1.2.0 | tee run-1.2.0-retry.logYou do not need --limit to resume. Every task is idempotent, so web-1 and web-2 find 1.2.0 already installed and only pass through the load balancer and health check, web-3 gets the release in the right folder this time, and the last batch upgrades web-4 to web-6. The migration task reports ok, not changed, because that line is already in the log.
If you run rollouts from a laptop on a mobile or prepaid connection, as many teams do when they are away from the office, run them from a small control server in the same region as the fleet, inside tmux or screen. A dropped connection halfway through a batch leaves hosts out of the pool, exactly as the failure did above.
Check it worked
test "$(grep -cE '^web-[1-6] +: .*failed=0' run-1.2.0-retry.log)" -eq 6
for i in 1 2 3 4 5 6; do curl -s "http://127.0.0.1:808$i/version.txt"; done
grep -c '^ server web-' lb/backends.cfg
cat db/migrations.logThe test line prints nothing (six hosts, no failures), every server answers 1.2.0, the load balancer lists 6 servers, and migrations.log has two lines, one for 1.1.0 and one for 1.2.0.
Step 7 · Stop the practice fleet and clean up
Stop the seven HTTP servers, then confirm the ports are free:
cd ~/ansible-rolling-demo
kill $(cat fleet.pids)
sleep 1
if curl -s --max-time 2 http://127.0.0.1:8081/ > /dev/null; then echo "web-1 is still running"; false; else echo "fleet stopped"; fiThis next command deletes the whole demo folder, including the run logs. Copy anything you want to keep first:
cd ~
rm -rf ~/ansible-rolling-demoRun pipx uninstall ansible-core too if you do not need Ansible on this machine.
Check it worked
test ! -e ~/ansible-rolling-demo && echo "demo folder removed"The first command printed fleet stopped, and this one prints demo folder removed.
Next steps
- Keep per-host and per-environment values, such as batch sizes and app paths, in the right place: /tutorials/organise-ansible-variables-with-group-vars-and-host-vars.
- Swap releases on a single server without dropping requests: /tutorials/deploy-a-new-version-with-zero-downtime-behind-nginx.
- Move the deploy steps into a role so every service can share the same rollout: /tutorials/organise-ansible-work-into-roles.
Related tutorials
- Write your first Pulumi program in TypeScriptYou will install the Pulumi CLI, keep state in a local folder, declare resources in a TypeScript program, preview and apply it, read its outputs, change it and watch the diff, then destroy and remove the stack.
- Set up a new cloud server on first boot with cloud-init user dataYou will write and validate one cloud-init file that gives a new Ubuntu 26.04 server a key-only sudo user, blocks root login, installs and upgrades packages, writes files with the right owners and runs setup commands once, ready to paste into any provider's user data field.
- Use Terraform workspaces for separate environments, and know when not toYou will run one Terraform configuration as separate dev and staging workspaces with per-environment settings, find where each workspace keeps its state, guard every apply with a workspace check, and compare the result with a directory per environment.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials