When you run webservers.yml, Ansible works on web1 and web2 at the same time: it installs, configures, reloads nginx and deploys the page on both servers in parallel. For a lab that's perfect, but in a real store it carries an obvious risk: if the new version has a problem, it fails on every server at once, and during the deployment there's no "trusted" server left serving customers. The professional techniques for avoiding this are rolling deployments (rolling updates), which go through the servers in batches, and delegation, which lets a task for one server run on another one, for example, to take it out of the load balancer while it's being updated. In this lesson you'll add a load balancer, lb1, to Aurora Store, you'll learn serial, per-batch max_fail_percentage, delegate_to, delegate_facts, run_once, local_action, connection: local, throttle, order and execution strategies, and you'll deploy the website without a single second of downtime.

Contents

  1. The problem: deploying without interrupting the service
  2. A load balancer for Aurora
  3. Practice: adding lb1 to the lab
  4. Practice: the load balancer in the inventory and in the playbooks
  5. serial: running in batches
  6. max_fail_percentage with serial
  7. delegate_to: running a task on another host
  8. delegate_facts
  9. run_once
  10. local_action and connection: local
  11. throttle and order
  12. Execution strategies
  13. Practice: a zero-downtime deployment from web1 to web2
  14. Verifying and saving the work

  1. The problem: deploying without interrupting the service

Today, Aurora's customers (in the lab, you with curl) connect directly to web1 or to web2. That raises two problems:

Problem Consequence
There's no single entry point The customer has to know which server to go to; if that server goes down, the store "goes down" for them
The servers are updated at the same time A failure in the new version affects all of them; during the reload, they're all in transition

The usual architecture has a load balancer in front: the customer only knows the load balancer, and it distributes the requests among the web servers. With a load balancer, a zero-downtime deployment always follows the same cycle for each server:

sequenceDiagram
    participant A as Ansible
    participant LB as lb1 (load balancer)
    participant W1 as web1
    participant W2 as web2
    Note over LB: Distributes between web1 and web2
    A->>LB: Take web1 out of the load balancer
    Note over LB: All traffic goes to web2
    A->>W1: Deploy and check
    A->>LB: Put web1 back in
    A->>LB: Take web2 out of the load balancer
    Note over LB: All traffic goes to web1 (already updated)
    A->>W2: Deploy and check
    A->>LB: Put web2 back in

For that you need two things Ansible offers: running the play in turns (serial) and running some of each web server's tasks on the load balancer (delegate_to).

  1. A load balancer for Aurora

Design decisions:

Decision Value Reason
New server lb1, IP 192.168.56.10, 512 MB of RAM nginx as a proxy uses very little; the .10 IP sits "in front of" the web servers (.11, .12)
Group loadbalancers, a child of aurora It gets the common role (users, motd, facts) like the rest
Software nginx, with the same nginx role In Lesson 5.2 you prepared site.conf.j2 to generate a load balancer with nginx_upstream_servers
Weights aurora_lb_weight from host_vars (web1: 2, web2: 1) Data that has existed since Module 2 and is finally used
Load balancer servers Computed with dict + zip (Lesson 5.3) A web3 would be added automatically

From now on the store will be used through http://192.168.56.10/ (in a real environment, the aurora-store.example domain would point to that IP).

  1. Practice: adding lb1 to the lab

3.1. The Vagrantfile

Add lb1 to the MACHINES dictionary in lab/Vagrantfile (Lesson 1.3), in first position:

MACHINES = {
  "lb1"  => { ip: "192.168.56.10", memory: 512,  cpus: 1 },
  "web1" => { ip: "192.168.56.11", memory: 1024, cpus: 1 },
  "web2" => { ip: "192.168.56.12", memory: 1024, cpus: 1 },
  "db1"  => { ip: "192.168.56.21", memory: 2048, cpus: 2 },
}

Create only the new machine (the others stay as they are) and save its initial state, as you did with the others:

cd ~/aurora-infra/lab
vagrant up lb1
vagrant snapshot save lb1 clean
cd ..

The Vagrantfile provisioning already authorizes the ~/.ssh/aurora_ed25519.pub key for the vagrant user.

3.2. SSH

Add the alias to ~/.ssh/config and extend the common options line (remember from the web3 exercise in Lesson 1.3 that patterns are matched against the name you type):

Host lb1
    HostName 192.168.56.10

Host lb1 web1 web2 db1 192.168.56.*
    User vagrant
    IdentityFile ~/.ssh/aurora_ed25519
    IdentitiesOnly yes

Since ansible.cfg keeps host_key_checking = True, accept lb1's fingerprint with a first manual connection, checking that it's the machine you've just created:

ssh lb1 hostname
The authenticity of host '192.168.56.10 (192.168.56.10)' can't be established.
ED25519 key fingerprint is SHA256:...
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
lb1

  1. Practice: the load balancer in the inventory and in the playbooks

4.1. The inventory

In inventory/hosts.yml, add the loadbalancers group inside aurora:

all:
  children:
    aurora:                      # All of the store's servers
      children:
        loadbalancers:           # Load balancers (nginx as a proxy)
          hosts:
            lb1:
              ansible_host: 192.168.56.10
        webservers:              # Web servers (nginx)
          hosts:
            web1:
              ansible_host: 192.168.56.11
            web2:
              ansible_host: 192.168.56.12
        dbservers:               # Database servers (PostgreSQL)
          hosts:
            db1:
              ansible_host: 192.168.56.21

Create inventory/group_vars/loadbalancers.yml with the nginx role parameters for the load balancer:

---
# Variables of the Aurora Store load balancers

# nginx role parameters (load balancer mode)
nginx_port: 80
nginx_worker_connections: 1024
nginx_site_name: aurora
nginx_server_name: "{{ aurora_domain }} www.{{ aurora_domain }}"
nginx_firewall_enabled: true

# Web servers the traffic is distributed to: {IP: weight}, computed from
# the webservers group and each host's aurora_lb_weight (Lesson 5.3).
nginx_upstream_servers: >-
  {{ dict(groups['webservers']
          | map('extract', hostvars, 'ansible_host')
          | zip(groups['webservers'] | map('extract', hostvars, 'aurora_lb_weight'))) }}

# nginx port on the web servers.
nginx_upstream_port: "{{ hostvars[groups['webservers'][0]]['nginx_port'] }}"

nginx_root doesn't appear: in load balancer mode, the template doesn't use it. Check the computed values:

ansible-inventory --graph
ansible lb1 -m ansible.builtin.debug -a "var=nginx_upstream_servers"
@all:
  |--@ungrouped:
  |--@aurora:
  |  |--@loadbalancers:
  |  |  |--lb1
  |  |--@webservers:
  |  |  |--web1
  |  |  |--web2
  |  |--@dbservers:
  |  |  |--db1
lb1 | SUCCESS => {
    "nginx_upstream_servers": {
        "192.168.56.11": 2,
        "192.168.56.12": 1
    }
}

4.2. The loadbalancers.yml playbook

Create loadbalancers.yml at the root of the project, with the same structure as the others:

---
- name: Configure the Aurora Store load balancers
  hosts: loadbalancers
  become: true

  roles:
    - nginx

  post_tasks:
    - name: Wait for the load balancer to serve the store
      ansible.builtin.uri:
        url: "http://localhost:{{ nginx_port }}/"
        return_content: true
      register: aurora_lb_check
      until: aurora_lb_check.status == 200
      retries: 5
      delay: 3
      check_mode: false
      tags: always

    - name: Check that the load balancer serves the store
      ansible.builtin.assert:
        that:
          - "'Aurora Store' in aurora_lb_check.content"
        fail_msg: "{{ inventory_hostname }} does not serve the Aurora Store page"
        success_msg: "{{ inventory_hostname }} distributes the store traffic correctly"
      tags: always

4.3. site.yml

Add the new playbook to site.yml, before the web servers (you'll see why shortly: the website deployment will need the load balancer to exist):

---
# Aurora Store main playbook: configures the whole infrastructure.
# Usage: ansible-playbook site.yml [--limit <hosts>]
#
#   common.yml         all servers (aurora group)         -> common role
#   dbservers.yml      database servers                   -> postgresql role + checks
#   loadbalancers.yml  load balancers                     -> nginx role (load balancer) + checks
#   webservers.yml     web servers, one at a time         -> nginx and aurora_app roles + checks

- name: Common configuration for all servers
  ansible.builtin.import_playbook: common.yml

- name: Database servers
  ansible.builtin.import_playbook: dbservers.yml

- name: Load balancers
  ansible.builtin.import_playbook: loadbalancers.yml

- name: Web servers
  ansible.builtin.import_playbook: webservers.yml

4.4. Building lb1

Apply site.yml only to lb1: it will get the common role and then nginx in load balancer mode (the database and web server plays have no matching hosts and are skipped):

ansible-playbook site.yml --limit lb1

And test the distribution, with the 2 to 1 weights:

for i in 1 2 3 4 5 6; do curl -s http://192.168.56.10/ | grep -o 'Served by web[0-9]'; done
Served by web1
Served by web2
Served by web1
Served by web1
Served by web2
Served by web1

Out of every three requests, two go to web1 and one to web2. Look at the generated configuration:

ssh lb1 'cat /etc/nginx/sites-available/aurora'
# Managed by Ansible (aurora-infra). Do not edit by hand.
upstream aurora_backend {
    server 192.168.56.11:80 weight=2;
    server 192.168.56.12:80 weight=1;
}

server {
    listen 80 default_server;
    ...

One server line per web server: the lines the rolling deployment will work with.

  1. serial: running in batches

By default, a play runs each task on all its hosts before moving on to the next one (the linear strategy, Lesson 1.4). With serial, the play runs in full on a batch of hosts, and only when it finishes does it move on to the next batch:

flowchart LR
    subgraph Without serial
      A1[Task 1: web1, web2] --> A2[Task 2: web1, web2] --> A3[Task 3: web1, web2]
    end
    subgraph With serial 1
      B1[Batch 1: web1<br/>all tasks] --> B2[Batch 2: web2<br/>all tasks]
    end

"In full" means everything: fact gathering, pre_tasks, roles, tasks, post_tasks and their handlers. Each batch is, in practice, a run of the play.

serial accepts three forms:

Form Example Batches with 10 hosts
Number serial: 2 2, 2, 2, 2, 2
Percentage serial: "30%" 3, 3, 3, 1
List (growing batches) serial: [1, "50%", "100%"] 1, 5, 4

The list is the most common form in production: a first batch of one server (the "canary": if something goes wrong, it only affects one), then half and, finally, the rest. The last value is repeated if there are hosts left.

With two web servers, Aurora will use serial: 1. In the final PLAY RECAP you'll see all the hosts, as always.

  1. max_fail_percentage with serial

In Lesson 5.5 you saw that max_fail_percentage stops the play if more than N% of the hosts fail. With serial, the percentage is calculated per batch, and if it's exceeded, the following batches don't run:

Configuration If the first batch fails…
serial: 1 (nothing else) With a batch of a single host, the whole batch has failed and the play stops anyway
serial: [1, "50%"] + max_fail_percentage: 0 Any failure in any batch stops the deployment
serial: "25%" + max_fail_percentage: 30 One isolated failure per batch is tolerated; if more than 30% of a batch fails, it stops

Aurora will set max_fail_percentage: 0. With serial: 1 it's redundant (a one-host batch that fails already stops the play), but it puts the policy in writing: if one day there are four web servers and someone changes it to serial: 2, a failure will still stop the deployment.

  1. delegate_to: running a task on another host

delegate_to runs a task on another host, but on behalf of the current host:

- name: Take the server out of the load balancer
  ansible.builtin.replace:
    path: /etc/nginx/sites-available/aurora
    regexp: '...'
    replace: '...'
  delegate_to: lb1

While web1 is being processed, this task connects to lb1 and modifies its file. The rules:

Aspect Value in a delegated task
Where the module runs On the delegated host (lb1)
Connection details (ansible_host, user, key) Those of the delegated host
become Applied on the delegated host
inventory_hostname Still the current host (web1)
Task variables (hostvars, facts, inventory) Those of the current host
Result (register) Stored on the current host

The inventory_hostname row is the key: inside a task delegated to lb1, you're still "being" web1, and that's why you can build the load balancer line with web1's IP. To avoid any ambiguity with the connection variables, refer to the current host's IP with hostvars[inventory_hostname]['ansible_host'].

Common uses:

  • Taking a server out of, or putting it back into, a load balancer.
  • Checking from outside that a service responds: delegate_to: localhost makes the request from the control node, as a customer would.
  • Registering the server in a monitoring system or in a DNS.
  • Running a task on a database server on behalf of an application (creating its database, for example).

And a precaution: when delegating to localhost, the task inherits become: true from the play, and on your computer it would try to use sudo. Set become: false on those tasks.

  1. delegate_facts

When a delegated task gathers facts (for example, ansible.builtin.setup), which host are they assigned to? By default, to the current host, not the delegated one: db1's data would end up stored as if it were web1's. delegate_facts: true makes them be assigned to the delegated host:

- name: Gather the database server facts
  ansible.builtin.setup:
  delegate_to: "{{ item }}"
  delegate_facts: true
  loop: "{{ groups['dbservers'] }}"
  run_once: true

- name: Show the database server's memory
  ansible.builtin.debug:
    msg: "db1 has {{ hostvars['db1']['ansible_facts']['memtotal_mb'] }} MB"

It's the solution to the problem in Lesson 3.5: the web servers play can't read db1's facts if they haven't been gathered in that same ansible-playbook run. With delegate_facts, a play can gather them explicitly. (Aurora doesn't need it: the website reads inventory data from db1, not facts.)

  1. run_once

run_once: true runs a task on a single host of the batch (the first one) and shares the result with the others:

- name: Apply the store schema migrations
  ansible.builtin.command:
    cmd: /opt/aurora/bin/migrate
  delegate_to: "{{ groups['dbservers'][0] }}"
  run_once: true

Combined with delegate_to, it's the pattern for tasks that must happen once per deployment even if the play has many hosts (the example is illustrative: Aurora doesn't have an application with migrations yet).

Watch out with serial: run_once means "once per batch". With serial: 1 and two web servers, a run_once task would run twice. If you need "once per run" in a play with serial, make it conditional with when: inventory_hostname == ansible_play_hosts_all[0], or put it in an earlier play without serial.

  1. local_action and connection: local

local_action is the old way of delegating to the control node:

- name: Check the store from the control node
  local_action:
    module: ansible.builtin.uri
    url: http://192.168.56.10/

It's exactly equivalent to delegate_to: localhost. You'll find local_action in old playbooks; in new code, use delegate_to: localhost, which reads just like any other task.

connection: local is something else: a connection type for a whole play (or a task) that runs the modules on the control node without SSH. Its natural use is plays that work against APIs rather than servers:

- name: Create the infrastructure in the cloud
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: ...    # modules that call the provider's API (Lesson 8.4)

localhost already uses the local connection implicitly (Lesson 2.1), so in that example connection: local is just documentation. The classic mistake is putting it in a play with hosts: webservers: all the tasks would run on your computer as many times as there are web servers, with each one's variables.

  1. throttle and order

Three mechanisms limit concurrency, at different levels:

Mechanism Level What it limits
forks (ansible.cfg, -f) Global The maximum number of hosts Ansible processes in parallel (Aurora: 10)
serial Play How many hosts go into each batch; the whole play runs batch by batch
throttle Task or block How many hosts run that task at the same time, without changing the rest of the play
- name: Register the server in the monitoring service
  ansible.builtin.uri:
    url: https://monitor.aurora-store.example/api/hosts
    method: POST
    body_format: json
    body:
      name: "{{ inventory_hostname }}"
  delegate_to: localhost
  become: false
  throttle: 1

With throttle: 1, even if the play processes 50 servers in parallel, this task calls the API one at a time (for example, because the API doesn't accept simultaneous requests). The example is illustrative.

order controls the order in which the play's hosts are processed, which matters above all with serial (which server goes first):

Value Order
inventory (default) The inventory's: web1, web2
reverse_inventory The reverse
sorted / reverse_sorted Alphabetical / reverse
shuffle Random on each run

Aurora uses the default value: web1 (weight 2) goes first, and during its update web2 handles all the traffic.

  1. Execution strategies

A play's strategy keyword decides how hosts advance through the tasks:

Strategy How it works When to use it
linear (default) Each task finishes on all the hosts of the batch before the next one starts Almost always: it's predictable and the output is easy to read
free Each host advances at its own pace, without waiting for the others Independent hosts with very different timings; the output gets mixed up
host_pinned Like free, but each fork finishes one host before starting another Like free, when there are more hosts than forks and you want to finish whole hosts
debug Like linear, but opens the interactive debugger when a task fails Debugging (Lesson 3.7)

free speeds up playbooks with heterogeneous hosts (you'll come back to it in Lesson 5.8), but it isn't compatible with what a rolling deployment needs: if each host advances at its own pace, you can't guarantee that one server is out of the load balancer while the other is being updated. For deployments with a load balancer, linear + serial.

  1. Practice: a zero-downtime deployment from web1 to web2

13.1. Taking a server out of the load balancer and putting it back

To take web1 out of the load balancer, all you need to do is mark its server line with down; nginx stops sending it requests when it reloads:

    server 192.168.56.11:80 weight=2 down;

You'll do it with the ansible.builtin.replace module (which replaces text using regular expressions), delegated to each load balancer, and you'll undo it at the end. It's a temporary modification of a file managed by the nginx role: the play always reverts it when the deployment goes well, and if a forgotten down mark were ever left behind, the next run of loadbalancers.yml would remove it (the template doesn't contain it).

13.2. The new webservers.yml

The complete webservers.yml:

---
- name: Configure the Aurora Store web servers
  hosts: webservers
  become: true
  serial: 1
  max_fail_percentage: 0

  pre_tasks:
    - name: Take the server out of the load balancer
      ansible.builtin.replace:
        path: /etc/nginx/sites-available/aurora
        regexp: '^(\s*server {{ hostvars[inventory_hostname]["ansible_host"] | regex_escape }}:\d+ weight=\d+);$'
        replace: '\1 down;'
      delegate_to: "{{ item }}"
      loop: "{{ groups['loadbalancers'] }}"
      changed_when: false
      tags: always

    - name: Reload the load balancer without this server
      ansible.builtin.systemd_service:
        name: nginx
        state: reloaded
      delegate_to: "{{ item }}"
      loop: "{{ groups['loadbalancers'] }}"
      changed_when: false
      tags: always

  roles:
    - nginx
    - aurora_app

  post_tasks:
    - name: Wait for the store website to respond
      ansible.builtin.uri:
        url: "http://localhost:{{ nginx_port }}/"
        return_content: true
      register: aurora_web_check
      until: aurora_web_check.status == 200
      retries: 5
      delay: 3
      check_mode: false
      tags: always

    - name: Get the nginx version
      ansible.builtin.command:
        cmd: nginx -v
      register: nginx_version_cmd
      changed_when: false
      check_mode: false
      tags:
        - never
        - info

    - name: Show the nginx version
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }}: {{ nginx_version_cmd.stderr }}"
      tags:
        - never
        - info

    - name: Check that the store website works
      ansible.builtin.assert:
        that:
          - aurora_web_check.status == 200
          - "'Aurora Store' in aurora_web_check.content"
        fail_msg: "The website on {{ inventory_hostname }} does not show the Aurora Store page"
        success_msg: "The website on {{ inventory_hostname }} responds correctly (HTTP {{ aurora_web_check.status }})"
      tags: always

    - name: Put the server back into the load balancer
      ansible.builtin.replace:
        path: /etc/nginx/sites-available/aurora
        regexp: '^(\s*server {{ hostvars[inventory_hostname]["ansible_host"] | regex_escape }}:\d+ weight=\d+) down;$'
        replace: '\1;'
      delegate_to: "{{ item }}"
      loop: "{{ groups['loadbalancers'] }}"
      changed_when: false
      tags: always

    - name: Reload the load balancer with this server
      ansible.builtin.systemd_service:
        name: nginx
        state: reloaded
      delegate_to: "{{ item }}"
      loop: "{{ groups['loadbalancers'] }}"
      changed_when: false
      tags: always

    - name: Check the store through the load balancer
      ansible.builtin.uri:
        url: "http://{{ hostvars[item]['ansible_host'] }}:{{ hostvars[item]['nginx_port'] }}/"
        return_content: true
      register: aurora_lb_check
      failed_when: >-
        aurora_lb_check.status != 200 or
        'Aurora Store' not in (aurora_lb_check.content | default(''))
      delegate_to: localhost
      become: false
      loop: "{{ groups['loadbalancers'] }}"
      check_mode: false
      tags: always

Go over the new pieces:

  • serial: 1 and max_fail_percentage: 0: the whole play runs for web1 and, only if it finishes without failures, for web2.
  • Delegated pre_tasks: before touching the server, its line is marked as down on each load balancer (loop over the loadbalancers group, so that it works the same with one or several) and nginx is reloaded there. The regular expression finds the line by the current server's IP; regex_escape (a filter from the regex_replace family) escapes the dots in the IP so they're interpreted literally.
  • The reloads are tasks, not handlers: they must happen at that moment, before carrying on. A handler would wait until the end of the section.
  • changed_when: false on the four load balancer tasks: taking a server out and putting it back in is an operation that leaves the load balancer exactly as it was. If they counted as changes, webservers.yml would never give changed=0, and you'd lose the signal that warns you of real drift.
  • post_tasks: first the usual local checks; only if they pass does the server go back into the load balancer. If a check fails (or the aurora_app deployment fails), the host is left failed, the following tasks don't run and the server stays out of the load balancer, which is exactly what you want with a broken server.
  • The final check is delegated to localhost with become: false: the request leaves your computer and comes in through the load balancer, like a real customer's. It doesn't check the version, because the load balancer can respond with either of the two servers, and during the deployment both versions coexist.
  • always tags on all the load balancer tasks: with any filter (for example, --tags deploy), the server goes out and comes back in.

Before deploying anything, check that the play works without changes:

ansible-playbook webservers.yml

You'll see the play run first for web1 and then for web2, with changed=0 on both.

13.3. The deployment: version 1.1.0

Open a second terminal and leave a "customer" running that requests the page every half second and prints who responds and with which version (or ERROR if it fails):

while true; do
  curl -sf http://192.168.56.10/ | grep -o 'Version [0-9.]* - Served by web[0-9]' || echo ERROR
  sleep 0.5
done

In the first terminal, bump the version in inventory/group_vars/webservers.yml:

aurora_app_version: "1.1.0"

And deploy:

ansible-playbook webservers.yml
PLAY [Configure the Aurora Store web servers] **********************************

TASK [Gathering Facts] *********************************************************
ok: [web1]

TASK [Take the server out of the load balancer] ********************************
ok: [web1 -> lb1(192.168.56.10)] => (item=lb1)

TASK [Reload the load balancer without this server] ****************************
ok: [web1 -> lb1(192.168.56.10)] => (item=lb1)
...
TASK [aurora_app : Publish the store home page] ********************************
changed: [web1]
...
TASK [Put the server back into the load balancer] ******************************
ok: [web1 -> lb1(192.168.56.10)] => (item=lb1)
...
TASK [Check the store through the load balancer] *******************************
ok: [web1 -> localhost] => (item=lb1)

PLAY [Configure the Aurora Store web servers] **********************************

TASK [Gathering Facts] *********************************************************
ok: [web2]
...
PLAY RECAP *********************************************************************
web1                       : ok=...  changed=2    unreachable=0    failed=0    ...
web2                       : ok=...  changed=2    unreachable=0    failed=0    ...

The notation web1 -> lb1(192.168.56.10) indicates a task for web1 run on lb1. The two changed on each server are the home page and the cleanup of its backup (Lesson 5.5).

Meanwhile, the second terminal shows something like this:

Version 1.0.0 - Served by web1
Version 1.0.0 - Served by web2
Version 1.0.0 - Served by web1
Version 1.0.0 - Served by web2     ← web1 leaves the load balancer
Version 1.0.0 - Served by web2
Version 1.0.0 - Served by web2
Version 1.1.0 - Served by web1     ← web1 is back, already updated
Version 1.1.0 - Served by web1     ← web2 leaves the load balancer
Version 1.1.0 - Served by web1
Version 1.1.0 - Served by web2     ← web2 is back, already updated
Version 1.1.0 - Served by web1

Not a single ERROR: the store hasn't stopped responding at any moment, and a half-updated server has never handled a request. Stop the loop with Ctrl+C.

13.4. A deployment that fails

Repeat the experiment from Lesson 5.5, now with the load balancer: a version 1.2.0 whose check fails.

ansible-playbook webservers.yml -e aurora_app_version=1.2.0 \
  -e aurora_app_check_url=http://localhost/does-not-exist

What happens:

  1. web1 leaves the load balancer.
  2. The aurora_app deployment fails, the rescue restores version 1.1.0 and ends with fail: web1 is left failed.
  3. The post_tasks don't run for web1: it stays out of the load balancer.
  4. Since the batch has failed, the play stops: web2 isn't touched.
PLAY RECAP *********************************************************************
web1                       : ok=...  changed=3    unreachable=0    failed=1    skipped=...  rescued=1    ignored=0

web2 doesn't even appear in the summary: it never got to run. Meanwhile, the store has kept working with web2 (version 1.1.0) handling all the traffic. Check it:

ssh lb1 'grep server /etc/nginx/sites-available/aurora'
    server 192.168.56.11:80 weight=2 down;
    server 192.168.56.12:80 weight=1;
    ...

To get back to normal, all you have to do is run the deployment again without the problem:

ansible-playbook webservers.yml

The "Take the server out of the load balancer" task doesn't find the line (it already has down) and does nothing; the 1.1.0 deployment doesn't change anything; the checks pass and web1 goes back into the load balancer. The down mark has disappeared and both servers are serving again.

  1. Verifying and saving the work

Check the complete infrastructure, now with four servers:

ansible-playbook site.yml
PLAY RECAP *********************************************************************
db1                        : ok=...  changed=0    unreachable=0    failed=0    ...
lb1                        : ok=...  changed=0    unreachable=0    failed=0    ...
web1                       : ok=...  changed=0    unreachable=0    failed=0    ...
web2                       : ok=...  changed=0    unreachable=0    failed=0    ...

Save the work:

git add lab/Vagrantfile inventory/ loadbalancers.yml webservers.yml site.yml
git commit -m "Load balancer lb1 and rolling deployment of the web servers (version 1.1.0)"

From now on, the store's entry point in the lab is http://192.168.56.10/.

Common Mistakes and Tips

  • UNREACHABLE on lb1 with a fingerprint error: you didn't accept the new host's SSH fingerprint (section 3.2). With host_key_checking = True, Ansible doesn't accept it for you.
  • The task delegated to localhost asks for a sudo password: it inherits become: true from the play. Add become: false.
  • Facts assigned to the wrong host: a delegated setup without delegate_facts: true stores the data on the current host.
  • A run_once task that runs several times: with serial, run_once is per batch.
  • Servers left out of the load balancer: if the deployment fails, that's expected. Investigate the failure and run it again; don't "put them back by hand" without knowing why they failed.
  • strategy: free with serial: the hosts in a batch advance without waiting for each other; don't use it in deployments with a load balancer.
  • Tip: on large fleets, use growing batches (serial: [1, "25%", "100%"]) with a low max_fail_percentage. The first server is your "canary": if it goes down, nobody else notices.

Exercises

Exercise 1: Batches

For a group of 20 web servers, write the serial line that updates 1 server first, then 25%, and then the rest. How many hosts will each batch have?

Exercise 2: run_once with serial

You want to add a task to webservers.yml that shows, only once per run, the message "Start of the deployment of version X". Write it so that it runs once even though the play uses serial: 1.

Exercise 3: A server under maintenance

web2 needs a one-hour hardware intervention. Using only delegated ad hoc commands (without modifying the playbooks), take it out of the load balancer, check that all the traffic goes to web1 and, when you're done, put it back in. What would happen if someone ran loadbalancers.yml during the intervention?

Solutions

Exercise 1. serial: [1, "25%", "100%"]. Batches: 1, 5 (25% of 20) and 14 (the rest, because 100% covers everything that's left). If you wanted 25% batches until the end, the list would be [1, "25%"]: the last value is repeated (1, 5, 5, 5, 4).

Exercise 2.

  pre_tasks:
    - name: Announce the start of the deployment
      ansible.builtin.debug:
        msg: "Start of the deployment of version {{ aurora_app_version }}"
      when: inventory_hostname == ansible_play_hosts_all[0]
      tags: always

ansible_play_hosts_all contains all the hosts in the play (not just those in the batch), so the condition is only met for the first one, web1. With run_once: true, on the other hand, the message would appear once per batch: twice.

Exercise 3.

ansible lb1 -b -m ansible.builtin.replace \
  -a "path=/etc/nginx/sites-available/aurora regexp='^(\s*server 192\.168\.56\.12:\d+ weight=\d+);$' replace='\1 down;'"
ansible lb1 -b -m ansible.builtin.systemd_service -a "name=nginx state=reloaded"
for i in 1 2 3 4; do curl -s http://192.168.56.10/ | grep -o 'Served by web[0-9]'; done

All the responses come from web1. To put it back in, use the same command with regexp='^(\s*server 192\.168\.56\.12:\d+ weight=\d+) down;$' replace='\1;' and another reload (or, more simply, ansible-playbook loadbalancers.yml, which restores the template). And there lies the answer to the question: if someone ran loadbalancers.yml during the intervention, the template would put web2 back into the load balancer too early, and customers would get errors. In practice, planned maintenance is expressed in the inventory (for example, with a weight or a variable that the template translates into down), not with manual changes; it's a good improvement to the nginx role that you might want to consider.

Conclusion

Aurora Store now has a load balancer, lb1 (192.168.56.10), configured with the same nginx role in proxy mode, with its servers and weights computed from the inventory, its own loadbalancers.yml playbook and its place in site.yml. You've learned to run a play in batches with serial (a number, a percentage or a growing list) and to stop a deployment with per-batch max_fail_percentage; to run tasks on another host with delegate_to, assign facts to the right host with delegate_facts and run something only once with run_once (remembering that with serial it's once per batch); and you know local_action, connection: local, throttle, order and the linear, free and host_pinned strategies. With all of that, webservers.yml deploys server by server, taking each one out of the load balancer while it's being updated, checking it from inside and from outside, and leaving it out and stopping the deployment if anything fails: you've released version 1.1.0 without a single error for customers. The infrastructure is growing and runs are getting longer and longer: four servers, batches, checks… In the next lesson, Optimizing Playbooks, you'll learn to measure where the time goes and to reduce it without sacrificing safety.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved