Jenkins + Ansible
Zero-downtime deploys with Jenkins and Ansible
Rolling batches with serial, draining the load balancer, health checks that check something real, and a rollback you've actually run.
5 min readPart 3 of 4
The simplest deploy stops the service, copies the new build over and starts it again. For however long that takes, users get errors. With one server there isn't much you can do about that. With two or more behind a load balancer, there's no reason anyone should notice a deploy at all.
This post walks through an Ansible playbook and a Jenkins stage that get you there: roll through the servers in batches, take each one out of the load balancer first, check it's healthy before it goes back in, and roll it back on its own if it isn't.
The shape of a rolling deploy
For each batch of servers:
- Take them out of the load balancer and let in-flight requests finish.
- Install the new release next to the old one.
- Switch over and restart.
- Check they're healthy.
- Put them back in the load balancer.
If step 4 fails, switch back to the old release, put the server back, and stop the rollout before it touches anything else.
Releases side by side
Keep each release in its own directory and point a symlink at the live one:
/opt/app/
├── current -> /opt/app/releases/1.42.0
└── releases/
├── 1.41.3
└── 1.42.0Deploying is changing one symlink. Rolling back is changing it back. The systemd unit runs /opt/app/current/bin/app, so it never needs to know which version is live. Prune old releases on a schedule and keep the last few around for quick rollbacks.
The playbook
- name: Rolling deploy
hosts: web
serial: 1
max_fail_percentage: 0
vars:
release_dir: "/opt/app/releases/{{ app_version }}"
pre_tasks:
- name: Take the host out of the load balancer and wait for it to drain
community.aws.elb_target:
target_group_arn: "{{ target_group_arn }}"
target_id: "{{ ec2_instance_id }}"
state: absent
target_status: unused
target_status_timeout: 300
delegate_to: localhost
tasks:
- name: Create the release directory
ansible.builtin.file:
path: "{{ release_dir }}"
state: directory
owner: app
group: app
mode: "0755"
- name: Unpack the release
ansible.builtin.unarchive:
src: "dist/app-{{ app_version }}.tar.gz"
dest: "{{ release_dir }}"
owner: app
group: app
- name: Remember which release is live now
ansible.builtin.stat:
path: /opt/app/current
register: previous
- name: Switch, restart and check
block:
- name: Point current at the new release
ansible.builtin.file:
src: "{{ release_dir }}"
dest: /opt/app/current
state: link
- name: Restart the service
ansible.builtin.systemd_service:
name: app
state: restarted
- name: Wait until the app reports healthy
ansible.builtin.uri:
url: http://127.0.0.1:8080/health
status_code: 200
register: health
until: health.status == 200
retries: 30
delay: 2
rescue:
- name: Point current back at the previous release
ansible.builtin.file:
src: "{{ previous.stat.lnk_source }}"
dest: /opt/app/current
state: link
when: previous.stat.islnk | default(false)
- name: Restart on the previous release
ansible.builtin.systemd_service:
name: app
state: restarted
- name: Stop the rollout
ansible.builtin.fail:
msg: "{{ inventory_hostname }} failed its health check on {{ app_version }} and was rolled back"
always:
- name: Put the host back in the load balancer
community.aws.elb_target:
target_group_arn: "{{ target_group_arn }}"
target_id: "{{ ec2_instance_id }}"
state: present
target_status: healthy
target_status_timeout: 300
delegate_to: localhosttarget_group_arn and ec2_instance_id come from inventory variables. Most of the rest is ordinary Ansible, but a few lines are doing the real work.
serial is what makes it rolling. serial: 1 does one host at a time, which is slow and the safest option. serial: "25%" does a quarter of the fleet per batch. A list such as serial: [1, "50%"] sends one host first as a canary and then the rest in two halves.
max_fail_percentage: 0 matters more than it looks. With serial: 1, a failure stops the play anyway, because the whole batch failed. With bigger batches, Ansible carries on as long as some hosts in the batch succeeded, and that's how a broken release ends up on most of a fleet with one red host per batch. Setting it to 0 stops everything at the first failure, whatever the batch size.
Deregistering a target makes the load balancer stop sending it new requests while the in-flight ones finish, for up to the target group's deregistration delay. target_status: unused makes the task wait until that's done instead of pulling the rug out from under live requests. If you're behind HAProxy rather than an AWS load balancer, the community.general.haproxy module can drain a server in the same way.
block, rescue and always give the playbook try, catch and finally. The rescue only runs if something in the block failed, and it ends with fail, so the host still counts as failed and the rollout stops. The always section puts the host back in the load balancer either way: on the new release if it passed, on the old one after a rollback.
The health check is the whole game
A /health endpoint that returns 200 as soon as the process is listening proves almost nothing. The new release can be up and still broken: wrong config, no database connection, a migration that didn't run. If the check passes on a broken release, every other line in that playbook is decoration.
Make the health check test what the app needs to serve real traffic. Can it reach the database? Did its config load? Is the schema at the version this code expects? It doesn't need to be elaborate. It needs to fail when the app can't do its job.
The Jenkins side
pipeline {
agent { label 'deploy' }
environment {
APP_VERSION = "1.42.${env.BUILD_NUMBER}"
}
stages {
// Build and test stages produce dist/app-$APP_VERSION.tar.gz
stage('Deploy to production') {
when { branch 'main' }
options { lock('production-deploy') }
steps {
sh 'ansible-playbook -i inventories/production deploy.yml -e "app_version=$APP_VERSION"'
}
}
}
}The lock stops two deploys from overlapping. If a second one starts while the first is halfway through the fleet, it waits its turn instead of racing it. The version goes through an environment variable that the shell expands, the same habit as with credentials: quoting stays sane and nothing gets interpolated by Groovy by accident.
The database is the hard part
During a rolling deploy, the old and new versions run side by side for a while, and they share one database. So every schema change has to work with both at once.
Adding a column? Add it as nullable, or with a default, in one release, and start relying on it in the next. Removing one? Stop reading and writing it in one release, drop it in a later one. Renaming? Don't, at least not in one step: add the new column, write to both, backfill, switch reads over, then drop the old column, spread across several releases.
This is usually called expand and contract, and it's the one part of zero-downtime deploys that no playbook can do for you. Run the migrations as their own step before the rollout starts, so every new instance comes up against a schema it understands.
Test the rollback
A rollback path that has never run is a theory. Every so often, deploy a build to staging with a health check that's rigged to fail, and watch the playbook roll it back and stop. If it doesn't, you've learned that on a quiet afternoon instead of in the middle of an incident.
References
- Ansible playbook guide: strategies and serial, error handling and max_fail_percentage, and blocks (
block,rescueandalways). - Ansible modules: community.aws.elb_target (including
target_status), community.general.haproxy, ansible.builtin.uri, ansible.builtin.stat (islnkandlnk_source) and ansible.builtin.systemd_service. - Deregistration delay, Elastic Load Balancing documentation.
- ParallelChange, on Martin Fowler's site: the expand and contract pattern for changes like schema migrations.
- Lockable Resources, the Jenkins plugin behind
lock.
#ansible #jenkins #deployment