Ansible Canary Deployment — Complete Guide
Introduction
Roll out changes to a subset of servers first with Ansible serial, batch_size, and health verification. This guide provides practical examples, best practices, and production-ready patterns.
Quick Start
---
- name: Canary Deployment
hosts: all
become: true
tasks:
- name: Execute task
ansible.builtin.debug:
msg: "Implementing canary deployment"
Method 1: Basic Approach
- name: Basic implementation
ansible.builtin.debug:
msg: "Canary Deployment - basic method"
Method 2: Advanced Pattern
- name: Advanced implementation with error handling
block:
- name: Main task
ansible.builtin.debug:
msg: "Canary Deployment - advanced method"
rescue:
- name: Handle failure
ansible.builtin.debug:
msg: "Task failed, executing recovery"
Production Example
---
- name: Production canary deployment
hosts: all
become: true
vars:
app_name: myapp
environment: production
tasks:
- name: Validate prerequisites
ansible.builtin.assert:
that:
- app_name is defined
- environment in ['dev', 'staging', 'production']
- name: Execute canary deployment
ansible.builtin.debug:
msg: "Running in {{ environment }} for {{ app_name }}"
register: result
- name: Verify success
ansible.builtin.assert:
that: result is not failed
fail_msg: "Canary Deployment failed"
Best Practices
- Test in check mode first — always run
--check --diffbefore applying - Use variables — parameterize for reuse across environments
- Handle errors — use
block/rescue/alwaysfor graceful failures - Idempotency — ensure repeated runs produce the same result
- Documentation — add comments explaining why, not what
Troubleshooting
| Issue | Cause | Fix |
|---|---|---|
| Task fails | Missing prerequisites | Check dependencies are met |
| Not idempotent | State not checked before action | Add conditional checks |
| Permission denied | Insufficient privileges | Use become: true |
| Timeout | Network or resource issue | Increase timeout values |
Conclusion
Roll out changes to a subset of servers first with Ansible serial, batch_size, and health verification. Use check mode for validation, handle errors gracefully, and always test in a non-production environment first.