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 Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Should A Student Use ChatGPT To Learn DevOps Instead Of Courses?

As a student looking to learn DevOps, you might be wondering if ChatGPT is a good alternative to traditional courses. While there are some benefits to using…

Read More

Top 10 Digital Signature Software Tools in 2026: Features, Pros, Cons & Comparison

Introduction In 2026, digital transformation has reshaped the way businesses manage documents, sign agreements, and engage with clients. Digital signatures have become an essential component of this…

Read More

Top 10 Graphics Design Tools in 2026: Features, Pros, Cons & Comparison

Introduction In 2026, graphics design tools are more essential than ever for businesses, content creators, designers, and marketers across industries. From creating brand identities and advertising materials…

Read More

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

Introduction In 2026, creating engaging and impactful presentations is more than just slides with bullet pointsโ€”itโ€™s about telling a story, conveying ideas visually, and keeping your audience…

Read More

How to Optimize Your headless CMS for Multilingual Websites

A multilingual site enables a company to internationalize itself to different audiences for better engagement and ultimately, international brand awareness. However, without the proper considerations with the…

Read More

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

Introduction In 2026, AI SEO tools have become indispensable for digital marketers, businesses, and content creators aiming to dominate search engine rankings. These tools leverage artificial intelligence…

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