Principe du Blue-Green
Deux environnements identiques : Blue (actif) et Green (inactif). On deploie sur le Green, puis on bascule le trafic.
Playbook Blue-Green
- hosts: localhost
vars:
current_env: "{{ lookup('file', '/opt/deploy/current_env') }}"
target_env: "{{ 'green' if current_env == 'blue' else 'blue' }}"
tasks:
- name: Afficher l'environnement cible
ansible.builtin.debug:
msg: "Deploiement sur {{ target_env }} (actif: {{ current_env }})"
- hosts: "{{ target_env }}_servers"
tasks:
- name: Deployer la nouvelle version
include_role:
name: deploy_app
vars:
app_version: "{{ new_version }}"
- name: Verifier la sante de l'application
ansible.builtin.uri:
url: "http://{{ inventory_hostname }}:8080/health"
status_code: 200
retries: 20
delay: 5
register: health
until: health.status == 200
- hosts: localhost
tasks:
- name: Executer les tests d'integration
ansible.builtin.command:
cmd: "python /opt/tests/integration.py --target={{ target_env }}"
register: integration_tests
failed_when: integration_tests.rc != 0
- name: Basculer le load balancer
ansible.builtin.template:
src: haproxy.cfg.j2
dest: /etc/haproxy/haproxy.cfg
vars:
active_backend: "{{ target_env }}"
delegate_to: "{{ lb_host }}"
notify: reload_haproxy
- name: Enregistrer le nouvel environnement actif
ansible.builtin.copy:
content: "{{ target_env }}"
dest: /opt/deploy/current_env
- name: Notifier l'equipe
community.general.slack:
token: "{{ slack_token }}"
channel: "#deployments"
msg: "Deploiement {{ new_version }} termine. Environnement actif : {{ target_env }}"
Rollback instantane
- hosts: localhost
vars:
current_env: "{{ lookup('file', '/opt/deploy/current_env') }}"
rollback_env: "{{ 'green' if current_env == 'blue' else 'blue' }}"
tasks:
- name: Rollback - basculer vers l'ancien environnement
ansible.builtin.template:
src: haproxy.cfg.j2
dest: /etc/haproxy/haproxy.cfg
vars:
active_backend: "{{ rollback_env }}"
delegate_to: "{{ lb_host }}"
notify: reload_haproxy
- name: Mettre a jour l'environnement actif
ansible.builtin.copy:
content: "{{ rollback_env }}"
dest: /opt/deploy/current_env
Template HAProxy pour Blue-Green
# templates/haproxy.cfg.j2
frontend http
bind *:80
default_backend {{ active_backend }}
backend blue
{% for host in groups['blue_servers'] %}
server {{ host }} {{ hostvars[host].ansible_host }}:8080 check
{% endfor %}
backend green
{% for host in groups['green_servers'] %}
server {{ host }} {{ hostvars[host].ansible_host }}:8080 check
{% endfor %}
Avantage : Le blue-green permet un rollback instantane en rebasculant le trafic vers l'ancien environnement.