Ansible: Automate Everything from First Playbook to Production · Production Patterns: Testing, Rolling Updates and CI/CD

Rolling Updates: serial, max_fail_percentage and Health Checks

Deploy to servers in batches with automatic rollback if too many fail, and drain traffic from each batch before updating.

Members can save this page, take notes and track progress. See membership · Sign in

What you'll build

A zero-downtime deployment playbook that updates web servers behind a load balancer in rolling batches: drain traffic, deploy, health-check, then restore traffic — stopping the entire rollout if more than one server fails.

The idea

Deploying to all servers at once means all servers are down during the update. Rolling updates deploy to a few servers at a time, keeping the rest running. If a batch fails, the rollout stops and the healthy servers continue serving traffic.

Key keywords:

  • serial — how many hosts to process at once. Can be a number (serial: 2), a percentage (serial: "30%"), or a ramp-up list (serial: [1, 5, "100%"] — test one, then five, then all remaining).
  • max_fail_percentage — if more than this percentage of hosts in a batch fail, abort the entire play. Set to 0 for zero tolerance.
  • pre_tasks / post_tasks — tasks that run before and after the main tasks in each batch. Perfect for load-balancer drain and restore.
  • delegate_to — run a task on a different host (e.g., call the load balancer API from the target host).
  • wait_for — pause until a port is open or a URL responds, ensuring the app is ready before moving to the next batch.

The code

Rolling update playbook with load balancer integration
cat <<'PLAYBOOK'
# rolling_deploy.yml
---
- name: Rolling deploy behind load balancer
  hosts: webservers
  become: true
  serial: [1, "30%", "100%"]
  max_fail_percentage: 10

  pre_tasks:
    # ── Drain: remove this server from the load balancer ──
    - name: Disable server in load balancer
      ansible.builtin.uri:
        url: "https://lb.internal/api/servers/{{ inventory_hostname }}/drain"
        method: POST
        headers:
          Authorization: "Bearer {{ lb_api_token }}"
        status_code: 200
      delegate_to: localhost

    - name: Wait for active connections to finish
      ansible.builtin.wait_for:
        timeout: 30

  tasks:
    # ── Deploy ──
    - name: Pull latest application code
      ansible.builtin.git:
        repo: "https://github.com/example/app.git"
        dest: /var/www/app
        version: "{{ app_version | default('main') }}"
        force: true
      notify: restart app

    - name: Install Python dependencies
      ansible.builtin.pip:
        requirements: /var/www/app/requirements.txt
        virtualenv: /var/www/app/venv
      notify: restart app

    - name: Deploy configuration from template
      ansible.builtin.template:
        src: templates/app.conf.j2
        dest: /etc/app/app.conf
        mode: "0644"
      notify: restart app

  handlers:
    - name: restart app
      ansible.builtin.systemd:
        name: myapp
        state: restarted

  post_tasks:
    # ── Health check: make sure the app is responding ──
    - name: Wait for app to start listening
      ansible.builtin.wait_for:
        port: 8080
        host: "127.0.0.1"
        delay: 5
        timeout: 60

    - name: Verify health endpoint returns 200
      ansible.builtin.uri:
        url: "http://127.0.0.1:8080/health"
        return_content: true
        status_code: 200
      register: health
      retries: 5
      delay: 10
      until: health.status == 200

    # ── Restore: add server back to load balancer ──
    - name: Enable server in load balancer
      ansible.builtin.uri:
        url: "https://lb.internal/api/servers/{{ inventory_hostname }}/enable"
        method: POST
        headers:
          Authorization: "Bearer {{ lb_api_token }}"
        status_code: 200
      delegate_to: localhost

    - name: Wait for load balancer to route traffic
      ansible.builtin.wait_for:
        timeout: 10
PLAYBOOK

Output

# rolling_deploy.yml
---
- name: Rolling deploy behind load balancer
  hosts: webservers
  become: true
  serial: [1, "30%", "100%"]
  max_fail_percentage: 10

  pre_tasks:
    # ── Drain: remove this server from the load balancer ──
    - name: Disable server in load balancer
      ansible.builtin.uri:
        url: "https://lb.internal/api/servers/{{ inventory_hostname }}/drain"
        method: POST
        headers:
          Authorization: "Bearer {{ lb_api_token }}"
        status_code: 200
      delegate_to: localhost

    - name: Wait for active connections to finish
      ansible.builtin.wait_for:
        timeout: 30

  tasks:
    # ── Deploy ──
    - name: Pull latest application code
      ansible.builtin.git:
        repo: "https://github.com/example/app.git"
        dest: /var/www/app
        version: "{{ app_version | default('main') }}"
        force: true
      notify: restart app

    - name: Install Python dependencies
      ansible.builtin.pip:
        requirements: /var/www/app/requirements.txt
        virtualenv: /var/www/app/venv
      notify: restart app

    - name: Deploy configuration from template
      ansible.builtin.template:
        src: templates/app.conf.j2
        dest: /etc/app/app.conf
        mode: "0644"
      notify: restart app

  handlers:
    - name: restart app
      ansible.builtin.systemd:
        name: myapp
        state: restarted

  post_tasks:
    # ── Health check: make sure the app is responding ──
    - name: Wait for app to start listening
      ansible.builtin.wait_for:
        port: 8080
        host: "127.0.0.1"
        delay: 5
        timeout: 60

    - name: Verify health endpoint returns 200
      ansible.builtin.uri:
        url: "http://127.0.0.1:8080/health"
        return_content: true
        status_code: 200
      register: health
      retries: 5
      delay: 10
      until: health.status == 200

    # ── Restore: add server back to load balancer ──
    - name: Enable server in load balancer
      ansible.builtin.uri:
        url: "https://lb.internal/api/servers/{{ inventory_hostname }}/enable"
        method: POST
        headers:
          Authorization: "Bearer {{ lb_api_token }}"
        status_code: 200
      delegate_to: localhost

    - name: Wait for load balancer to route traffic
      ansible.builtin.wait_for:
        timeout: 10

Run this on your computer — see “Get Started” for setup.

Execution flow with 10 webservers and serial: [1, "30%", "100%"]:

Execution timeline
cat <<'EOF'
Batch 1:  web1                          (1 server   — canary)
Batch 2:  web2, web3, web4              (3 servers  — 30%)
Batch 3:  web5, web6, web7, web8,       (6 servers  — 100% of remaining)
          web9, web10

Each batch:
  1. pre_tasks  → drain from LB, wait 30s for connections to close
  2. tasks      → git pull, pip install, deploy config
  3. handlers   → restart app (only if something changed)
  4. post_tasks → wait for port 8080, check /health, restore in LB

If web1 fails (the canary), max_fail_percentage=10 means 1/1 = 100% failed
→ Ansible aborts. The other 9 servers are untouched and still serving.
EOF

Output

Batch 1:  web1                          (1 server   — canary)
Batch 2:  web2, web3, web4              (3 servers  — 30%)
Batch 3:  web5, web6, web7, web8,       (6 servers  — 100% of remaining)
          web9, web10

Each batch:
  1. pre_tasks  → drain from LB, wait 30s for connections to close
  2. tasks      → git pull, pip install, deploy config
  3. handlers   → restart app (only if something changed)
  4. post_tasks → wait for port 8080, check /health, restore in LB

If web1 fails (the canary), max_fail_percentage=10 means 1/1 = 100% failed
→ Ansible aborts. The other 9 servers are untouched and still serving.

Run this on your computer — see “Get Started” for setup.

Common mistakes

Mistake Fix
Setting serial: 1 on a 100-server fleet Each batch takes time; use a ramp-up like [1, 5, "25%", "100%"] to canary first, then accelerate
Forgetting the health check in post_tasks Without a health check, a server that fails to start is added back to the LB and receives traffic it can't handle
max_fail_percentage: 0 with serial: 1 A single failure stops everything; in practice, 10–20% is safer because one flaky host shouldn't block the whole fleet
Draining but not waiting for connections Active requests get dropped; always wait_for a grace period after draining

Key points

  • serial controls batch size; a ramp-up list ([1, 5, "100%"]) deploys to a canary first, then progressively larger groups.
  • max_fail_percentage stops the rollout if too many hosts fail in a batch — the remaining hosts stay on the old version.
  • pre_tasks drain traffic before updating; post_tasks verify health and restore traffic.
  • delegate_to: localhost runs a task on the control node (useful for calling load balancer APIs).
  • wait_for and uri with retries/until ensure the application is healthy before moving to the next batch.

Practice questions

What does `serial: [1, 5, '100%']` do when deploying to 20 servers?

Answer

Batch 1 deploys to 1 server (canary). Batch 2 deploys to 5 servers. Batch 3 deploys to the remaining 14 servers (100% of what's left). If the canary fails, the other 19 servers are untouched.

How does max_fail_percentage interact with serial to provide automatic rollback?

Answer

Within each batch defined by serial, if the percentage of failed hosts exceeds max_fail_percentage, Ansible aborts the entire play. Remaining batches are never started, so those servers keep running the previous version — an automatic rollback by stopping the rollout.

Why do pre_tasks and post_tasks matter for zero-downtime deployments?

Answer

pre_tasks drain the server from the load balancer before any changes, so active users aren't affected. post_tasks verify the app is healthy and restore the server to the load balancer. Without them, users would hit servers mid-deploy or servers that failed to start.

Open in the app to mark lessons complete, take notes and track your progress.

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake