Turn Your Vehicle Into a Smart Earning Asset

While you’re not driving your car or bike, it can still be working for you. MOTOSHARE helps you earn passive income by connecting your vehicle with trusted renters in your city.

🚗 You set the rental price
🔐 Secure bookings with verified renters
📍 Track your vehicle with GPS integration
💰 Start earning within 48 hours

Join as a Partner Today

It’s simple, safe, and rewarding. Your vehicle. Your rules. Your earnings.

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


Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.

0
Would love your thoughts, please comment.x
()
x