Interview Prep/Real-World Interview/Write-an-Ansible-playbook tasks

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.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-an-Ansible-playbook tasks