Please enable JavaScript.
Coggle requires JavaScript to display documents.
Phase 14 — Error Handling - Coggle Diagram
Phase 14 — Error Handling
Purpose
What is Error Handling?
Error handling is the process of controlling what Ansible does when a task succeeds, fails, or encounters an unexpected condition.
Instead of stopping the entire playbook immediately, Ansible can recover, clean up, log information, or continue execution based on your design.
Why Error Handling is Important
Prevents incomplete deployments
Performs automatic rollback
Cleans temporary resources
Restarts failed services
Sends notifications
Records logs
Makes automation predictable
Increases reliability
Supports enterprise disaster recovery
Enterprise Use Cases
Application deployment
Database migration
Patch management
Kubernetes deployment
Cloud provisioning
Service restart
Configuration management
Security remediation
Backup and restore
CI/CD pipelines
Default Task Failure Behavior
Task Executes
Success
Continue to next task
Failure
Stop execution for that host
Mark host as FAILED
Skip remaining tasks on that host
Continue with other hosts unless configured otherwise
Error Handling Keywords
block
rescue
always
ignore_errors
failed_when
changed_when
any_errors_fatal
max_fail_percentage
meta
clear_host_errors
end_host
end_play
flush_handlers
block
Definition
Groups multiple tasks together
Similar to try block in programming languages
Allows common directives
Foundation for rescue and always
Purpose
Execute related tasks as one logical unit
Simplify error handling
Reduce duplication
Enterprise Uses
Software installation
Database deployment
Server provisioning
Kubernetes deployment
Patch management
Application upgrade
Syntax
block
tasks
Example
Install packages
Configure application
Start service
Behavior
All tasks execute sequentially
If one task fails
Block stops
Rescue starts if defined
Common Directives Inside Block
become
when
tags
vars
environment
delegate_to
run_once
rescue
Definition
Executes only if block fails
Purpose
Recover from failure
Rollback changes
Restart services
Restore backups
Remove temporary files
Notify administrators
Enterprise Uses
Rollback deployment
Restore database
Recover failed service
Remove failed containers
Restore configuration
Behavior
Executes only after failure inside block
Skipped if block succeeds
Example Workflow
Install application
Configuration fails
Rescue restores backup
Service returned to previous state
always
Definition
Executes regardless of success or failure
Purpose
Cleanup
Logging
Notification
Audit
Resource release
Enterprise Uses
Delete temporary files
Close database sessions
Send Slack message
Send email
Upload logs
Generate reports
Remove lock files
Behavior
Runs after block
Runs after rescue
Runs when everything succeeds
Runs when everything fails
block + rescue + always Workflow
Start Block
Execute Task 1
Execute Task 2
Execute Task 3
Block Success
Skip Rescue
Execute Always
Block Failure
Stop Remaining Block Tasks
Execute Rescue
Execute Always
ignore_errors
Definition
Ignore task failure
Purpose
Continue playbook execution even if task fails
Syntax
ignore_errors: true
Enterprise Uses
Optional package installation
Non-critical cleanup
Log collection
Testing environments
Best effort operations
Behavior
Task marked failed
Playbook continues
Risks
Can hide real problems
May produce inconsistent systems
Best Practice
Use only for non-critical tasks
failed_when
Definition
Manually define when a task should fail
Purpose
Override Ansible default success detection
Default Behavior
Return code 0
Success
Return code not 0
Failure
Enterprise Need
Some applications return 0 even when unhealthy
Some applications return non-zero although acceptable
Syntax
failed_when
expression
Examples
Fail if service output contains ERROR
Fail if disk usage greater than threshold
Fail if application health check returns DOWN
Fail if version mismatch detected
Benefits
Better validation
Accurate deployment
Custom health checks
changed_when
Definition
Controls when task is reported as changed
Purpose
Prevent false changes
Improve reporting
Enterprise Uses
Health checks
Read-only commands
Monitoring tasks
Compliance scans
Register Variables
Definition
Save task output
Purpose
Use output in failed_when
Use output in rescue
Use output in conditions
Stored Information
stdout
stderr
rc
changed
failed
start time
end time
execution duration
Return Codes
rc
0
Success
Non-zero
Failure
Enterprise Validation
failed_when can override return code logic
Ansible Facts During Failure
ansible_failed_task
Name of failed task
ansible_failed_result
Complete failed result
Enterprise Uses
Logging
Alerting
Troubleshooting
Reporting
Common Enterprise Recovery Actions
Rollback deployment
Restore configuration
Restore database
Restart service
Restart container
Restart Kubernetes pod
Restore backup
Remove temporary files
Release locks
Notify monitoring system
Logging
Log Success
Log Failure
Save Error Output
Upload Logs
Central Logging
ELK
Splunk
Graylog
Loki
Notifications
Email
Slack
Microsoft Teams
PagerDuty
ServiceNow
Jira Ticket
SMS Gateway
Integration with Handlers
Block changes configuration
Handler restart service
Failure before handler
Rescue rollback
Always flush handlers if required
meta flush_handlers
Interaction with Handlers
notify
handlers
meta flush_handlers
Error Handling During Loops
Loop item failure
Continue remaining items
Stop loop
Register failed items
Retry selected items
Retry Mechanism
until
retries
delay
Purpose
Retry unstable operations
Wait for services
Wait for APIs
Wait for Kubernetes resources
Host Failure Control
any_errors_fatal
One host fails
Stop all hosts
max_fail_percentage
Stop play after failure threshold reached
Meta Error Controls
meta clear_host_errors
Reset failed host state
meta end_host
Stop current host
meta end_play
Stop entire play
meta flush_handlers
Execute pending handlers immediately
Common Error Types
SSH Failure
Authentication Failure
Permission Denied
Package Installation Failure
Repository Unreachable
Service Start Failure
File Permission Error
Disk Full
Network Timeout
DNS Failure
API Failure
Kubernetes Failure
Docker Failure
Database Failure
Linux Paths Related to Error Handling
Project Directory
/home/automation/ansible/
Playbooks
/home/automation/ansible/playbooks/
Roles
/home/automation/ansible/roles/
Templates
/home/automation/ansible/templates/
Files
/home/automation/ansible/files/
Inventory
/home/automation/ansible/inventory/
Group Variables
/home/automation/ansible/group_vars/
Host Variables
/home/automation/ansible/host_vars/
ansible.cfg
/home/automation/ansible/ansible.cfg
Logs
/var/log/ansible.log
Temporary Files
/tmp/
System Logs
/var/log/messages
/var/log/syslog
/var/log/dnf.log
/var/log/yum.log
/var/log/apt/history.log
/var/log/secure
/var/log/auth.log
/var/log/audit/audit.log
Commands Used During Troubleshooting
ansible-playbook playbook.yml
ansible-playbook playbook.yml --check
ansible-playbook playbook.yml --diff
ansible-playbook playbook.yml --syntax-check
ansible-playbook playbook.yml --step
ansible-playbook playbook.yml --start-at-task
ansible-playbook playbook.yml -vv
ansible-playbook playbook.yml -vvv
ansible-playbook playbook.yml -vvvv
ansible-inventory --graph
ansible-inventory --list
ansible all -m ping
ansible-doc
ansible-config dump
journalctl
systemctl status
systemctl restart
dnf history
yum history
apt history
ssh
scp
rsync
Enterprise Best Practices
Never ignore critical errors
Use block for related tasks
Use rescue for rollback
Use always for cleanup
Keep rescue simple
Log every failure
Send notifications
Validate deployments
Use failed_when for application validation
Use changed_when for accurate reporting
Test failure scenarios
Keep playbooks idempotent
Document rollback procedures
Store logs centrally
Integrate monitoring
Follow Principle of Least Privilege
Test in Development
Test in QA
Test in Staging
Deploy to Production only after validation
Enterprise Deployment Flow
Start Playbook
Gather Facts
Validate Environment
Execute Block
Install
Configure
Validate
Start Service
Failure
Execute Rescue
Rollback
Restore Backup
Restart Previous Version
Collect Logs
Always
Cleanup
Upload Logs
Send Notification
Generate Report
End Playbook
Interview Questions
What is block?
What is rescue?
What is always?
Difference between block and rescue?
Difference between ignore_errors and failed_when?
Difference between failed_when and changed_when?
When should ignore_errors be avoided?
How does Ansible decide a task failed?
What is return code rc?
What information does register store?
What is ansible_failed_task?
What is ansible_failed_result?
What does meta flush_handlers do?
What does any_errors_fatal do?
What does max_fail_percentage do?
How do enterprise teams implement rollback?
How do you perform cleanup after failures?
How do you log deployment failures?
How do you notify administrators after failures?