Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Define an Ansible task as a YAML list item under a play’s tasks: key. Give it a descriptive name, call one module with YAML arguments, and add controls such as when, loop, register, or notify only when the task needs them. Ansible processes tasks from top to bottom for the hosts matched by the play.

What an Ansible task is

Ansible documentation describes a task as the definition of an action applied to a managed host. In practical terms, a task is one item in a YAML list. It normally invokes one Ansible module, and the module arguments describe the desired state or operation.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Tasks belong to a play. A play selects hosts with hosts:, then provides ordered tasks and optional variables, handlers, and other controls. Ansible normally runs the first task on all hosts in the play, then moves to the second task, rather than completing every task on one host before touching the next. A host that fails a task is removed from the remaining tasks in that play by default.

The smallest useful task

- name: Configure web servers
  hosts: web
  tasks:
    - name: Ensure the application directory exists
      ansible.builtin.file:
        path: /opt/myapp
        state: directory
        mode: '0755'

The list marker (-) begins the task. The name is the text shown in Ansible output. The key ansible.builtin.file selects the module, and the indented mapping supplies its arguments. The surrounding hosts and tasks keys make this task part of a complete play.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.

Task anatomy: the fields you use most

Field Purpose Typical value
name Human-readable description displayed during a run Ensure nginx is installed
Module key The operation Ansible performs ansible.builtin.package
Module arguments Parameters that express the desired state name: nginx, state: present
when Condition controlling whether the task runs ansible_facts['os_family'] == 'RedHat'
loop Repeats the task for each item in a sequence loop: '{{ packages }}'
register Saves the module result in a variable register: package_result
notify Queues a handler when the task reports a change notify: Restart application

These are task-level keywords. The module’s own parameters must remain under the module name at the correct indentation. A misplaced parameter can be interpreted as a task keyword or cause a parser error.

Choose a module before writing the task

Start with the operation you need, then select a purpose-built module. Modules provide Ansible’s semantics for desired state and usually make idempotence—running the play repeatedly without unnecessary changes—clearer than an opaque shell command.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common module choices

  • ansible.builtin.file creates directories, removes paths, and manages ownership, permissions, and file state.
  • ansible.builtin.copy transfers a known file and can set its destination attributes.
  • ansible.builtin.template renders a Jinja2 template with variables before placing the result.
  • ansible.builtin.package installs or removes packages through the target system’s package manager.
  • ansible.builtin.service starts, stops, enables, or restarts a service.
  • ansible.builtin.debug prints a value or message while you develop or troubleshoot a play.

Use ansible.builtin.command or ansible.builtin.shell when no suitable module expresses the operation. Treat those modules as an explicit choice: command execution can be harder to make idempotent, and shell additionally invokes a shell, with its quoting and expansion behavior. A module is not automatically safer for every action, but a purpose-built module exposes the state Ansible can check.

Use fully qualified collection names

Write module names such as ansible.builtin.copy instead of the short name copy. The official guidance recommends fully qualified collection names (FQCNs) for Ansible 2.10 and later. FQCNs identify exactly which collection supplies the module and reduce ambiguity when collections contain similarly named modules.

Pass module arguments as YAML

Indent arguments beneath the module key. Use mappings for named parameters and lists where a module expects multiple values.

- name: Install the web package
  ansible.builtin.package:
    name: nginx
    state: present

- name: Copy the static site
  ansible.builtin.copy:
    src: files/index.html
    dest: /var/www/html/index.html
    owner: root
    group: root
    mode: '0644'

Quote values when YAML’s type inference could change their meaning. File modes are the classic example: write '0644' or '0755' so the value is treated as a permission string rather than an unintended number. Quote a value that begins with YAML syntax, contains a colon or special characters, or must remain a string. Keep secrets out of plain task text; use Ansible’s variable and vault mechanisms appropriate to your environment.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Use variables and Jinja2 expressions

Variables let the same task work with different hosts or environments. They can be defined in a play, inventory, reusable task files, roles, or supplied on the command line. Reference a variable in a module argument with a Jinja2 expression.

- name: Create the application directory
  ansible.builtin.file:
    path: '{{ app_root }}'
    state: directory
    mode: '0755'

Do not put Jinja2 delimiters around a value that is already a complete YAML scalar when they are unnecessary; do use them when substituting a variable into a string or when the module expects the rendered value. Keep variable names descriptive and keep the data shape consistent. A list should be consumed as a list, while a mapping should be accessed by its keys.

Register a result for later tasks

Add register to save a task’s return data. The registered variable can be inspected by a later task, tested in a condition, or used to drive another operation.

- name: Check whether the application is responding
  ansible.builtin.uri:
    url: http://127.0.0.1:8080/health
    return_content: false
  register: health_check
  failed_when: false

- name: Show the HTTP status
  ansible.builtin.debug:
    msg: 'Health check returned {{ health_check.status }}'

A registered value is a result object, not merely the module’s primary output. Its available keys depend on the module. When a task is looped, the result generally contains a results list with one result per item, so inspect that structure before writing a condition against it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Repeat work with loop

A loop applies one task to each item. Put the sequence under loop: and refer to the current item as {{ item }} unless you deliberately choose another loop variable.

- name: Install required packages
  ansible.builtin.package:
    name: '{{ item }}'
    state: present
  loop:
    - curl
    - jq
    - git

For reusable data, store the list in a variable:

vars:
  packages:
    - curl
    - jq

tasks:
  - name: Install required packages
    ansible.builtin.package:
      name: '{{ item }}'
      state: present
    loop: '{{ packages }}'

One looped task is usually easier to maintain than many identical task blocks. Write separate tasks when each item needs a different module, different arguments, or a distinct explanation in the run output. If a loop item is a mapping, access its fields explicitly, for example {{ item.name }} and {{ item.version }}. If nested loops or included task files make item ambiguous, assign a deliberate variable name with the loop-control options.

Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

Conditionally run tasks with when

A when value is a raw Jinja2 expression. Do not wrap the expression in {{ }}.

- name: Report the configuration path on Red Hat systems
  ansible.builtin.debug:
    msg: 'Configuration is at {{ config_path }}'
  when: ansible_facts['os_family'] == 'RedHat'

Ansible evaluates a loop condition separately for each item. This allows one task to skip only the items that do not meet the condition.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
- name: Install packages supported by this host
  ansible.builtin.package:
    name: '{{ item.name }}'
    state: present
  loop: '{{ packages }}'
  when: item.os_family in ansible_facts['os_family']

Make conditions explicit about the data they test. Facts may be unavailable if fact gathering was disabled, and variable names are case-sensitive. If a value may be undefined, structure the condition so the undefined case is handled rather than allowing a templating error.

Trigger handlers only after a change

Use notify when a configuration change should cause follow-up work, such as restarting a service. A handler is a special task that runs only when notified by a task that reports changed. Handlers are normally run after the regular tasks in the relevant section, and repeated notifications with the same handler name are coalesced.

- name: Render application configuration
  ansible.builtin.template:
    src: app.conf.j2
    dest: /etc/myapp/app.conf
    mode: '0644'
  notify: Restart application

handlers:
  - name: Restart application
    ansible.builtin.service:
      name: myapp
      state: restarted

The notification string must match the handler name. A template task that finds no difference reports ok and does not restart the service, which avoids an unnecessary interruption. Use a handler for change-triggered follow-up, not for an operation that must run unconditionally at a particular point.

A complete task set using common controls

The following play combines a variable, loop, registered result, template deployment, conditional task, and handler.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.
- name: Deploy application configuration
  hosts: app
  vars:
    config_path: /etc/myapp/app.conf
    packages:
      - curl
      - jq
  tasks:
    - name: Install required packages
      ansible.builtin.package:
        name: '{{ item }}'
        state: present
      loop: '{{ packages }}'
      register: package_results

    - name: Render application configuration
      ansible.builtin.template:
        src: app.conf.j2
        dest: '{{ config_path }}'
        mode: '0644'
      notify: Restart application

    - name: Report configuration path on Red Hat systems
      ansible.builtin.debug:
        msg: 'Configuration is at {{ config_path }}'
      when: ansible_facts['os_family'] == 'RedHat'
  handlers:
    - name: Restart application
      ansible.builtin.service:
        name: myapp
        state: restarted

Each task still has one primary action. The loop repeats package installation, the registration preserves its results for later use, the template task can notify a restart, and the final task is gated by a host fact.

Decide between common task patterns

Choice Prefer it when Main trade-off
Purpose-built module vs. command/shell A module models the desired state or operation Modules are clearer and often idempotent; commands may be necessary for unsupported tools but require more care around repeat runs and return codes
One task with loop vs. explicit tasks Every item uses the same module and argument shape A loop reduces duplication; explicit tasks can be clearer when items have different behavior
Unconditional task vs. when The operation applies to every host or only to a defined subset Conditions improve selectivity but depend on correctly gathered facts and defined variables
Ordinary sequencing vs. handler notification Follow-up work should occur only after a change Handlers prevent needless restarts but run at handler time rather than immediately after the notifying task
import_tasks vs. include_tasks Reuse a task file statically or load it dynamically based on runtime data Imports are expanded when the playbook is parsed; includes are evaluated during execution, so condition and loop behavior differs

Use import_tasks for a known, static task set that should be visible during parsing and listing. Use include_tasks when the file to load depends on variables or a runtime condition. Both keep a large playbook maintainable; neither changes the fact that the resulting entries are ordinary tasks.

Understand execution order and failure behavior

Tasks run in the order written. For a play targeting several hosts, Ansible normally applies task one to all currently active hosts before proceeding to task two. A host that fails is marked failed and does not continue through the remaining tasks in that play unless you deliberately change error handling. This ordering matters when a later task assumes a package, directory, or service was prepared by an earlier one.

Keep dependencies visible in task order. If a service must be installed before it is enabled, place the package task first and the service task afterward. If configuration must exist before a service restart, have the configuration task notify a handler rather than placing an unconditional restart after it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate a playbook before applying changes

Run validation commands from the control node with the same Ansible installation and inventory you intend to use. These checks answer different questions:

  1. Check YAML and playbook parsing: run ansible-playbook --syntax-check site.yml. This catches structural and syntax problems before host changes are attempted.
  2. See which hosts are selected: run ansible-playbook site.yml --list-hosts. Confirm that the inventory group and host patterns match your intention.
  3. See which tasks are selected: run ansible-playbook site.yml --list-tasks. This is especially useful with imports, includes, tags, and conditional structures.
  4. Preview supported changes: run ansible-playbook site.yml --check. Check mode asks supported modules to predict changes without applying them, but exact behavior depends on the module and installed Ansible version.
  5. Preview file differences: add --diff, as in ansible-playbook site.yml --check --diff. Diff output is most useful for modules that manage file content, and it can expose sensitive data, so review where output is stored or displayed.

Check mode and diff mode are previews, not guarantees. A module may have limited check-mode support, a command may not be safely predictable, and runtime facts or external services can still affect the result. After syntax and selection checks, test against a non-production host or a narrowly targeted inventory pattern when the change is consequential.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.

Common task-definition failures and fixes

The module appears to be an unknown key

Verify indentation and use an FQCN such as ansible.builtin.file. The module key must be at the same indentation level as name, while its arguments are indented beneath it.

A mode or number behaves unexpectedly

Quote permission modes and other values whose YAML type matters: use mode: '0644'. Check the module documentation for whether it expects a string, integer, list, or mapping.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The condition never runs

Remove Jinja2 delimiters from when, confirm that the tested variable exists, and inspect facts with a temporary ansible.builtin.debug task. For a loop, remember that the condition is evaluated once per item.

A handler does not run

Confirm that the notifying task actually reports changed, that the notification text exactly matches the handler name, and that the handler is defined under handlers: in the same play or an appropriately included role.

A looped result is difficult to test

Inspect the registered variable. A loop normally creates a result collection, so a condition that expects a single module result may need to iterate over or otherwise address the individual entries.

The playbook parses but changes the wrong hosts

Use --list-hosts before a real run and check the inventory group named in hosts:. Host-pattern mistakes are selection errors, not task-module errors.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical checklist for every new task

  • Is the task under the intended play’s tasks: list?
  • Does its name explain the intended outcome rather than merely repeating the module name?
  • Is there a purpose-built module for the operation?
  • Is the module written with its FQCN?
  • Are arguments indented beneath the module and quoted where YAML typing could surprise you?
  • Should a variable, loop, or condition make the task reusable or selective?
  • If the task changes configuration, should it notify a handler instead of restarting something unconditionally?
  • Have you run syntax, host-selection, and task-list checks before using check or diff mode?

When these choices are deliberate, the YAML remains readable to the person operating it and predictable to Ansible: one named action, one module, explicit inputs, and a clear place in the play’s order.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.