Below is a detailed Ansible tutorial covering execution strategies (linear vs free), task delegation, fact caching, and async jobs—with clear code examples, explanations, and a professional tutorial structure.
1. Understanding Ansible Execution Strategies
What is an Execution Strategy?
Ansible’s execution strategy determines how tasks are scheduled and run across all targeted hosts in your inventory during a playbook run.
The two main built-in strategies are linear
and free
.
A. The linear
Execution Strategy (Default)
How it works:
- Ansible runs each task on all hosts in the play before proceeding to the next task.
- If any host fails on a task, Ansible stops running tasks for that host (unless you use
ignore_errors
). - Ensures all hosts remain “in sync” across tasks.
Analogy: Like marching in step—everyone completes step 1, then step 2, together.
Example:
Suppose you have 3 web servers and the following playbook:
- name: Install and start nginx on all web servers (linear)
hosts: webservers
tasks:
- name: Install nginx
yum:
name: nginx
state: present
- name: Start nginx
service:
name: nginx
state: started
- Ansible will:
- Install nginx on all webservers.
- Only after step 1 is complete on all, start nginx on all.
B. The free
Execution Strategy
How it works:
- Ansible runs tasks on each host as soon as possible, without waiting for other hosts to catch up.
- Hosts “race ahead” independently if earlier tasks finish sooner.
- This can dramatically speed up playbook runs in environments where some hosts are slower/faster.
Analogy: Like a relay race—each host runs as fast as it can, independently.
How to Enable free
Strategy:
You can set it for an entire playbook or per-play:
- For a playbook run:
ansible-playbook play.yml -e 'ansible_strategy=free'
- Per play in a playbook:
- name: Do things in free mode hosts: all strategy: free tasks: # ...
Example:
- name: Use free strategy for faster parallel execution
hosts: webservers
strategy: free
tasks:
- name: Long-running task
shell: sleep 10 && echo done
- name: Quick task
shell: echo quick
Code language: PHP (php)
- Each host will run both tasks as soon as it can, independently of others.
Comparison Table
Feature | linear (default) | free |
---|---|---|
Sync between hosts | Yes | No |
Proceeds on error | No (unless ignore_errors) | Yes (for other hosts) |
Use case | Ordered changes, tight sync | Speed, high parallelism |
Set via | Default | strategy: free |
2. Task Delegation
What is Task Delegation in Ansible?
- Delegation allows you to run a task “for one host, but on another.”
- Useful for centralized actions (e.g., updating a load balancer, fetching from a jump host, registering DNS, etc.)
How to Use Task Delegation
- The
delegate_to
keyword is added to a task.
Example:
Suppose you want to copy a file from your Ansible control node to all webservers, but want to restart the load balancer only once (from your control node):
- name: Deploy app and update load balancer
hosts: webservers
tasks:
- name: Deploy app
copy:
src: app.tar.gz
dest: /var/www/app.tar.gz
- name: Restart load balancer after deploy
shell: systemctl reload haproxy
delegate_to: loadbalancer01
run_once: true
Code language: JavaScript (javascript)
Explanation:
- The
delegate_to: loadbalancer01
runs the task on hostloadbalancer01
. run_once: true
ensures it runs only once (not once per webserver).
More Delegation Examples
- Gather facts from a remote server, but run a task on localhost:
- name: Save the public IP of each host to a file on the control node lineinfile: path: "/tmp/public_ips.txt" line: "{{ inventory_hostname }}: {{ ansible_default_ipv4.address }}" delegate_to: localhost
3. Fact Caching
What is Fact Caching?
- Facts are system info collected by Ansible with the
setup
module (e.g., IP, OS, memory). - Fact caching saves these facts between playbook runs to speed up execution and reuse information, instead of recollecting facts every time.
- Useful for large inventories or when using dynamic inventories/cloud.
How to Enable Fact Caching
- Set
fact_caching
in youransible.cfg
.
Example (YAML file-based caching):
Add to your ansible.cfg
:
[defaults]
fact_caching = yaml
fact_caching_connection = /tmp/ansible_facts
Code language: JavaScript (javascript)
- This will cache facts as YAML files in
/tmp/ansible_facts/
.
Other supported backends:
jsonfile
memcached
redis
mongodb
- More: Ansible fact caching docs
Example Usage:
ansible all -m setup # Gather facts and cache them
ansible-playbook play.yml # Next run uses cached facts
Code language: PHP (php)
Tip:
- Use
gather_facts: false
if you want to use cached facts only, or manage fact collection manually.
4. Asynchronous Jobs (async and poll)
What are Async Jobs in Ansible?
- Async jobs allow you to run tasks in the background on a host, and optionally check for their completion later.
- Useful for long-running commands (package updates, service restarts, big file downloads, etc.).
- Avoids timeouts and makes playbooks faster.
How to Use Async and Poll
- Use
async
to specify a timeout (in seconds). - Use
poll
to set how often to check for completion:poll: 0
means “fire and forget” (don’t wait)poll: n
means “check every n seconds until done or timeout”
Example 1: Fire and Forget
- name: Start a long task in the background and don't wait
shell: /usr/local/bin/do_something_heavy
async: 1200 # 20 minutes allowed
poll: 0
Example 2: Async with Polling
- name: Run a task for up to 5 minutes, polling every 30 seconds
shell: /usr/local/bin/slow_task
async: 300
poll: 30
Code language: JavaScript (javascript)
Example 3: Start Async, Then Wait Later
- Start task async/poll: 0, register the job.
- Use the
async_status
module to wait for the result.
- name: Start a long task in the background
shell: /usr/local/bin/do_heavy_work
async: 600
poll: 0
register: async_job
- name: Wait for async job to complete
async_status:
jid: "{{ async_job.ansible_job_id }}"
register: job_result
until: job_result.finished
retries: 30
delay: 10
Code language: JavaScript (javascript)
Summary Table
Feature | Usage | Example Keyword | Example Code/Config |
---|---|---|---|
Execution Strategy | Ordered/sync or free/async | strategy: linear/free | strategy: free |
Delegation | Run task on other host | delegate_to | delegate_to: localhost |
Fact Caching | Speed up fact gathering | fact_caching in config | fact_caching: yaml |
Async Jobs | Background/parallel work | async /poll | async: 600 poll: 0 |
Best Practices
- Use
linear
for most playbooks,free
for maximum parallelism when order doesn’t matter. - Delegate tasks when you need actions to occur on “controller” or special nodes (DNS, LB, etc.).
- Enable fact caching in large or cloud environments to save time and API calls.
- Use async for long-running tasks, especially when scaling out!
References & Further Reading
- Ansible Strategies Documentation
- Delegation, Rolling Updates, and Local Actions
- Fact Caching Guide
- Async Actions and Polling
I’m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I have worked at Cotocus. I share tech blog at DevOps School, travel stories at Holiday Landmark, stock market tips at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow , and SEO strategies at Wizbrand.
Do you want to learn Quantum Computing?
Please find my social handles as below;
Rajesh Kumar Personal Website
Rajesh Kumar at YOUTUBE
Rajesh Kumar at INSTAGRAM
Rajesh Kumar at X
Rajesh Kumar at FACEBOOK
Rajesh Kumar at LINKEDIN
Rajesh Kumar at WIZBRAND