Interview Prep/Ansible/Vault, Privilege Escalation and Error Handling

How do `block`, `rescue` and `always` work?

IntermediateConceptVault, Privilege Escalation and Error Handling
Answer

block groups tasks. If any task in it fails, tasks in rescue run. always runs afterwards, whether or not the block failed. It works like try/except/finally.

- block:
    - ansible.builtin.command: /opt/app/deploy.sh
  rescue:
    - ansible.builtin.command: /opt/app/rollback.sh
  always:
    - ansible.builtin.service: { name: app, state: started }

If rescue succeeds, the host is counted as rescued, not failed, and the play continues. A block can also carry shared when, become, vars and tags.

All Ansible questions Roadmap: Ansible

More on Vault, Privilege Escalation and Error Handling