In Ansible, a block logically groups multiple tasks together, allowing you to control execution flow and handle errors as a single unit. The always keyword defines a sequence of tasks within a block that execute regardless of whether the tasks inside the block succeeded or failed.
1. How the block and always Structure Works
This combination is conceptually similar to a try/finally construct in programming languages such as Python and Java.
- block: The primary sequence of tasks you want to execute.
- rescue (optional): A sequence of tasks that runs only if a task inside the block fails.
- always: A sequence of tasks that runs unconditionally, whether the block succeeds, fails, or is handled by the rescue section.
2. When to Use always
The always section is best suited for guaranteed cleanup operations and state restoration that must occur regardless of playbook execution outcomes.
- Deleting temporary files, scripts, or installer packages.
- Releasing locks or closing connections.
- Restoring maintenance windows or re-enabling monitoring alerts.
- Ensuring specific services are restarted or left in a healthy state.
3. Code Example
The following playbook demonstrates how block, rescue, and always work together:
- hosts: web_servers
tasks:
- name: Run main operations with error handling
block:
- name: Step 1 - Perform deployment tasks
ansible.builtin.command: /bin/deploy_app
- name: Step 2 - Verify application status
ansible.builtin.command: /bin/verify_app
rescue:
- name: Rollback deployment on failure
ansible.builtin.command: /bin/rollback_deploy
always:
- name: Clean up temporary installer files
ansible.builtin.file:
path: /tmp/app_installer.tar.gz
state: absent
- name: Re-enable monitoring alerts
ansible.builtin.uri:
url: https://monitoring.local
method: POST
4. Execution Scenarios
| Scenario | block | rescue | always |
|---|---|---|---|
| All tasks succeed | ✅ Runs | ❌ Skipped | ✅ Runs |
| Task fails inside block | ❌ Fails | ✅ Runs | ✅ Runs |
| Rollback succeeds | Completed | Completed | ✅ Runs |
5. Key Takeaway
block → rescue → always
- block performs the primary work.
- rescue handles failures and recovery actions.
- always guarantees cleanup and state restoration.
No comments:
Post a Comment