Files
ansible/async.md
2026-03-24 16:13:33 +02:00

90 lines
2.8 KiB
Markdown

## Asynchronous Tasks in Ansible
### Problem: Blocking Long-Running Tasks
When executing long-running tasks (e.g., backups, migrations, or API calls), Ansible's default behavior blocks the playbook execution until the task completes. This creates delays and reduces efficiency, especially when managing large infrastructure.
### Solution: Async Mode
Ansible's async mode allows tasks to run asynchronously, freeing the playbook to continue executing other tasks while the async operation completes in the background.
### Key Parameters
- `async`: Maximum number of seconds to wait for the task to complete (e.g., `async: 30` waits 30 seconds)
- `poll`: Number of seconds between status checks (0 means no polling)
### Example: Database Migration
```yaml
- name: Initiate database migration
mysql_db:
name: production_db
state: restarted
async: 60
poll: 5
- name: Check migration status
async_status:
jid: "{{ async_jid }}"
register: migration_result
- name: Fail task if migration failed
fail:
msg: "Database migration failed: {{ migration_result.stdout }}"
when: migration_result.failed
"""
### Best Practices
1. Use async for I/O-bound tasks (e.g., API calls, file transfers)
2. Combine with `ignore_errors: yes` for resilient workflows
3. Always register async job IDs (`async_jid`) for monitoring
4. Use `--check` flag to simulate async operations without executing
### Monitoring Async Tasks
Use the `async_status` module to track progress:
```yaml
- name: Monitor async task
async_status:
jid: "{{ async_jid }}"
register: task_result
- name: Display task status
debug:
msg: "Task status: {{ task_result.status }}"
"""
### Troubleshooting
- Use `--verbosity=2` to see detailed async output
- Check the `ansible_async` directory for job logs
- Verify network connectivity for remote tasks
- Ensure correct credentials for authenticated operations
### When to Use Async
- API calls with long response times
- File transfers between nodes
- Scheduled maintenance windows
- Operations requiring user intervention
### When Not to Use Async
- Simple, fast operations
- Tasks requiring immediate feedback
- Operations with strict timing requirements
Async mode transforms Ansible from a sequential executor to a parallel orchestrator, enabling more efficient management of complex infrastructure workflows.
### Best Practices
1. Use async for long-running tasks (e.g., backups, migrations)
2. Combine with `ignore_errors: yes` for resilient task execution
3. Monitor task status using `async_status` module
4. Use `--check` flag to simulate async operations
### Troubleshooting
- Check task output with `--verbosity=2`
- Use `async_status` to track task progress:
```yaml
- name: Check async task status
async_status:
jid: "{{ async_jid }}"
register: task_result
```