Find the Best Cosmetic Hospitals

Explore trusted cosmetic hospitals and make a confident choice for your transformation.

โ€œInvest in yourself โ€” your confidence is always worth it.โ€

Explore Cosmetic Hospitals

Start your journey today โ€” compare options in one place.

Ansible Execution: Strategies, Delegation, Fact Caching, and Async Jobs

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:
    1. Install nginx on all webservers.
    2. 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

Featurelinear (default)free
Sync between hostsYesNo
Proceeds on errorNo (unless ignore_errors)Yes (for other hosts)
Use caseOrdered changes, tight syncSpeed, high parallelism
Set viaDefaultstrategy: 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 host loadbalancer01.
  • 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 your ansible.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:

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

  1. Start task async/poll: 0, register the job.
  2. 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

FeatureUsageExample KeywordExample Code/Config
Execution StrategyOrdered/sync or free/asyncstrategy: linear/freestrategy: free
DelegationRun task on other hostdelegate_todelegate_to: localhost
Fact CachingSpeed up fact gatheringfact_caching in configfact_caching: yaml
Async JobsBackground/parallel workasync/pollasync: 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


Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
Iโ€™m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I have worked at <a href="https://www.cotocus.com/">Cotocus</a>. I share tech blog at <a href="https://www.devopsschool.com/">DevOps School</a>, travel stories at <a href="https://www.holidaylandmark.com/">Holiday Landmark</a>, stock market tips at <a href="https://www.stocksmantra.in/">Stocks Mantra</a>, health and fitness guidance at <a href="https://www.mymedicplus.com/">My Medic Plus</a>, product reviews at <a href="https://www.truereviewnow.com/">TrueReviewNow</a> , and SEO strategies at <a href="https://www.wizbrand.com/">Wizbrand.</a> Do you want to learn <a href="https://www.quantumuting.com/">Quantum Computing</a>? <strong>Please find my social handles as below;</strong> <a href="https://www.rajeshkumar.xyz/">Rajesh Kumar Personal Website</a> <a href="https://www.youtube.com/TheDevOpsSchool">Rajesh Kumar at YOUTUBE</a> <a href="https://www.instagram.com/rajeshkumarin">Rajesh Kumar at INSTAGRAM</a> <a href="https://x.com/RajeshKumarIn">Rajesh Kumar at X</a> <a href="https://www.facebook.com/RajeshKumarLog">Rajesh Kumar at FACEBOOK</a> <a href="https://www.linkedin.com/in/rajeshkumarin/">Rajesh Kumar at LINKEDIN</a> <a href="https://www.wizbrand.com/rajeshkumar">Rajesh Kumar at WIZBRAND</a> <a href="https://www.rajeshkumar.xyz/dailylogs">Rajesh Kumar DailyLogs</a>

Related Posts

Top 10 AI Data Integration Tools in 2026: Features, Pros, Cons & Comparison

Introduction In 2026, AI data integration tools are pivotal for businesses navigating the complexities of modern data ecosystems. These tools combine artificial intelligence with data integration processes…

Read More

Top 10 Fleet Management Tools in 2026: Features, Pros, Cons & Comparison

Introduction In 2026, the logistics and transportation industries are evolving rapidly, and managing a fleet of vehicles has never been more complex. Fleet management software has become…

Read More

Top 10 AI Academic Plagiarism Checkers Tools in 2026: Features, Pros, Cons & Comparison

Introduction In 2026, AI academic plagiarism checkers have become indispensable tools for students, educators, researchers, and institutions striving to uphold academic integrity. With the rise of AI-generated…

Read More

Top 10 Travel Management Software Tools in 2026: Features, Pros, Cons & Comparison

Introduction In 2026, travel management software (TMS) has become a crucial tool for businesses, travel agencies, and frequent travelers. These tools automate the booking, tracking, and management…

Read More

Top 10 No-Code Platforms Tools in 2026: Features, Pros, Cons & Comparison

Introduction In 2026, no-code platforms have become essential for businesses and individuals looking to build powerful applications, websites, and automations without the need for programming knowledge. These…

Read More

Top 10 AI Training Data Platforms Tools in 2026: Features, Pros, Cons & Comparison

Introduction In 2026, AI training data platforms have become the backbone of successful machine learning (ML) and artificial intelligence (AI) projects. These platforms streamline the process of…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x