Write a block/rescue/always structure for a deploy with automatic rollback.
AdvancedHands-onWrite-an-Ansible-playbook tasks
Answer
- name: Deploy with rollback
block:
- name: Switch symlink to new release
ansible.builtin.file:
src: "/opt/app/releases/{{ version }}"
dest: /opt/app/current
state: link
notify: Restart app
- ansible.builtin.meta: flush_handlers
- name: Health check
ansible.builtin.uri: { url: "http://localhost:8080/health" }
register: hc
retries: 10
delay: 3
until: hc.status == 200
rescue:
- name: Roll back symlink
ansible.builtin.file:
src: "/opt/app/releases/{{ previous_version }}"
dest: /opt/app/current
state: link
- name: Restart on old release
ansible.builtin.systemd: { name: app, state: restarted }
- ansible.builtin.fail:
msg: "Deploy of {{ version }} failed, rolled back to {{ previous_version }}"
always:
- name: Record deploy attempt
ansible.builtin.lineinfile:
path: /var/log/deploys.log
line: "{{ now(utc=true).isoformat() }} {{ version }} {{ 'FAILED' if ansible_failed_task is defined else 'OK' }}"
create: true
Key trick → rescue runs only if a task in block fails, which works like try/except. The explicit fail at the end keeps the host marked as failed after the rollback so serial stops the rollout.
More on Write-an-Ansible-playbook tasks
Write a playbook that installs and starts Nginx on Ubuntu web servers.BeginnerWrite an inventory with groups, a group of groups, and per-group variables.BeginnerWrite a playbook that deploys a config file from a Jinja2 template and restarts the service only if it changed.BeginnerWrite a role structure for a Node.js app and show what goes in each folder.IntermediateWrite a task that creates multiple users with SSH keys from a list.BeginnerWrite a rolling deploy playbook: 2 servers at a time, removed from the load balancer during the update.Advanced