DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
VGSources
Blog

How to Use Conditionals in Ansible Playbooks

A practical, in-depth guide to Ansible conditionals: write correct when expressions, branch on facts and registered results, filter loops, control failure and change reporting, and troubleshoot skipped tasks.
WorldAnsible Playbooks Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Ansible conditionals let a playbook make a decision from facts, variables, or an earlier task result. Use when with a raw Jinja expression (without {{ }}), and Ansible evaluates it separately for every host, skipping the task wherever the expression is false.

How Ansible evaluates a conditional

A task with a when clause is still part of the play for every target host. Ansible renders the expression in that host’s variable context, converts the result to true or false, and then either runs the task or records it as skipped. A condition therefore controls execution; it does not remove the task from the playbook.

As an Amazon Associate I earn from qualifying purchases.

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

The normal inputs are gathered facts, ordinary variables, and values registered by previous tasks. Evaluation happens at the point where the task is reached, so a variable changed earlier in the play can alter a later decision. A condition has no effect until its referenced data exists and can be evaluated.

The expression is not wrapped in Jinja delimiters

when, failed_when, and changed_when are already templated by Ansible. Write the expression directly:

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
- name: Install a Debian-family package
  ansible.builtin.package:
    name: nginx
    state: present
  when: ansible_facts['os_family'] == "Debian"

Do not write when: {{ ansible_facts['os_family'] == "Debian" }}. The extra delimiters can produce warnings or parsing errors because Ansible is expecting an expression, not a complete template.

Basic when patterns

Run a task on one platform

Facts such as ansible_facts['os_family'], ansible_facts['distribution'], and ansible_facts['distribution_major_version'] are common selectors. The following task runs on Debian-family systems and is skipped on other operating systems:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
- name: Install a Debian-family package
  ansible.builtin.package:
    name: nginx
    state: present
  when: ansible_facts['os_family'] == "Debian"

Use the family fact when Debian derivatives should share the same path. Use the distribution fact when behavior is specific to one distribution. Check the actual values on your managed hosts instead of assuming that every system exposes the same facts.

Require several conditions

A YAML list is the clearest way to express multiple requirements. List entries have implicit and semantics, so every entry must be true:

- name: Enable a service only on a supported Debian release
  ansible.builtin.service:
    name: nginx
    state: started
  when:
    - ansible_facts['os_family'] == "Debian"
    - ansible_facts['distribution_major_version'] | int >= 12
    - nginx_enabled | default(false) | bool

Facts that look numeric are often strings. Cast them with | int or | float before comparing. Without a cast, a lexical string comparison can give a result that does not represent the version number.

Use explicit grouping for mixed logic

Use parentheses with and and or when the decision has alternatives. For example, this permits either Debian 12 or Red Hat 9:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
- name: Configure a supported server release
  ansible.builtin.template:
    src: server.conf.j2
    dest: /etc/myapp/server.conf
  when: >
    (ansible_facts['distribution'] == "Debian" and
     ansible_facts['distribution_major_version'] | int == 12) or
    (ansible_facts['distribution'] == "RedHat" and
     ansible_facts['distribution_major_version'] | int == 9)

For long expressions, consider setting a clearly named intermediate variable instead of embedding many platform checks in every task.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Facts and variables as condition inputs

Verify that a fact exists

Ansible facts are host attributes collected during fact gathering. Their availability depends on the target platform and on whether gathering was enabled. A task that references a missing key can fail while evaluating the condition rather than simply being skipped.

Inspect the complete fact set with:

- name: Inspect gathered facts
  ansible.builtin.debug:
    var: ansible_facts

For a narrower check, print a specific value:

- name: Show the operating-system family
  ansible.builtin.debug:
    msg: "{{ ansible_facts['os_family'] | default('unknown') }}"

The default filter is useful when a value is optional, but it should not hide a fact that your playbook genuinely requires. If a platform must provide a particular fact, fail early with a clear assertion or separate platform-specific task file.

Be careful with time facts

ansible_date_time is captured when facts are gathered and may become stale during a long-running play. It is suitable for decisions based on the collection time, not necessarily for the current clock at a later task. If timing matters, obtain a fresh value at the point of use rather than treating the original fact as continuously updated.

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.

Create an intermediate value with set_fact

When several tasks need the same normalized decision, calculate it once:

- name: Classify the host temperature
  ansible.builtin.set_fact:
    temperature_celsius: "{{ sensor_output.stdout | float }}"

- name: Stop the service when the temperature is unsafe
  ansible.builtin.service:
    name: myapp
    state: stopped
  when: temperature_celsius | float > 90

Intermediate names make later conditions easier to read and provide one place to normalize strings, numbers, or defaults. Keep platform-specific variables, templates, and task files separate when that is clearer than adding deeply nested expressions.

Use registered results in later conditions

Register the result and test its fields

register stores a task result in a host-level variable for the current playbook run. Common fields include stdout, stdout_lines, rc, failed, changed, and skipped.

- name: Check whether a marker exists
  ansible.builtin.command: test -f /etc/myapp/marker
  register: marker_check
  failed_when: false

- name: Rebuild only when the marker is absent
  ansible.builtin.command: /usr/local/bin/rebuild-myapp
  when: marker_check.rc != 0

The first task deliberately converts the expected nonzero return code into usable data instead of allowing the play to stop. The second task interprets that return code. If a command can fail in a way that you intend to handle later, use ignore_errors: true or an appropriate failed_when expression so execution reaches the conditional task.

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.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Use result tests instead of inspecting every field

Ansible provides tests for common states:

- name: Run an optional migration
  ansible.builtin.command: /usr/local/bin/migrate
  register: migration
  failed_when: false

- name: Report a failed migration
  ansible.builtin.debug:
    msg: Migration requires attention
  when: migration is failed

- name: Continue only after a successful migration
  ansible.builtin.debug:
    msg: Migration completed
  when: migration is succeeded

You can also test is skipped and is changed. These tests are generally easier to read than repeating the result object’s internal Boolean fields.

Registered variables are temporary

A registered value exists in memory for the current run and is associated with each host. It is not a persistent cache for a future playbook invocation. If a later run needs the value, store it deliberately using a fact cache or another persistent mechanism rather than relying on register.

Conditionals with loops

Each item is evaluated separately

When a task has both a loop and a when, Ansible evaluates the condition for every item. Some iterations can run while others are skipped:

- name: Print only unprivileged ports
  ansible.builtin.debug:
    msg: "{{ item }}"
  loop: [80, 8080, 8443]
  when: item > 1024

The task runs for 8080 and 8443, while the 80 iteration is skipped. A skipped item does not prevent eligible items from executing.

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

Protect optional loop data

If the loop source may be undefined, provide an empty default list:

- name: Configure requested listeners
  ansible.builtin.template:
    src: listener.conf.j2
    dest: "/etc/myapp/listeners/{{ item }}.conf"
  loop: "{{ listener_ports | default([]) }}"

For dictionary data, default to an empty mapping and test the value you need:

- name: Enable configured features
  ansible.builtin.debug:
    msg: "Enabling {{ item.key }}={{ item.value }}"
  loop: "{{ features | default({}) | dict2items }}"
  when: item.value | bool

Understand registered loop results

Registering a looped task produces a result object with a results list. Each element contains the response for one item, including the item value and that iteration’s return code, output, or skipped state.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC
- name: Check each configuration file
  ansible.builtin.command: "test -f {{ item }}"
  loop: "{{ config_files | default([]) }}"
  register: config_checks
  failed_when: false

- name: Display missing files
  ansible.builtin.debug:
    msg: "Missing: {{ item.item }}"
  loop: "{{ config_checks.results | default([]) }}"
  when: item.rc != 0

When per-iteration logic refers to a previous result, account for the first iteration having no previous item. A safe default prevents an undefined-variable failure at the start of the loop.

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

Static imports, dynamic includes, and roles

Static imports

A condition placed on a static import is applied to every task in the imported file. The imported tasks are expanded predictably, and the condition is inherited by each of them. This is useful when an entire, known set of tasks belongs to one platform or mode.

- name: Load Debian tasks
  ansible.builtin.import_tasks: debian.yml
  when: ansible_facts['os_family'] == "Debian"

Dynamic includes

A dynamic include is evaluated at runtime. The included file is selected when Ansible reaches the include, so variables can have changed since earlier tasks and undefined values may affect whether the file is loaded.

- name: Load optional hardening tasks
  ansible.builtin.include_tasks: hardening.yml
  when: hardening_enabled | default(false) | bool

Choose an import when static expansion and predictable visibility are more important. Choose an include when the decision must occur dynamically or when the included task set depends on values discovered during the run.

Roles

Conditions can also be attached when a role is reused. Apply a role-level condition when every task in the role shares the same prerequisite. If only a few tasks are conditional, keeping the checks beside those tasks usually makes the role easier to understand.

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

Define failure and change deliberately

failed_when changes failure semantics

Modules normally decide success from their own return data. failed_when overrides that decision. This is valuable for commands whose nonzero codes have documented, acceptable meanings.

- name: Query application status
  ansible.builtin.command: /usr/local/bin/app status
  register: app_status
  failed_when: app_status.rc not in [0, 3]

Here, return codes 0 and 3 are accepted; every other code fails the task. A list of multiple failed_when entries uses implicit and semantics, so all listed expressions must be true for the task to be marked failed. Use a single expression with explicit or when the failure rule is alternative rather than cumulative.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

changed_when controls idempotence reporting

Command and shell modules often report a change whenever they run, even when the underlying operation only queried state. Set changed_when: false for a read-only command, or derive the change state from its output:

- name: Query application status without reporting a change
  ansible.builtin.command: /usr/local/bin/app status
  register: app_status
  changed_when: false
  failed_when: app_status.rc not in [0, 3]

As with failed_when, list entries for changed_when are joined with implicit and. Explicitly define the state that matters to your play rather than allowing an exit code alone to imply that the system changed.

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

Check mode and conditional branches

Run a simulation with:

ansible-playbook site.yml --check

Check mode asks supported modules what they would change without modifying remote systems. Add diff mode when the module supports it and you need to inspect proposed file changes.

A task can override the play’s mode:

- name: Gather a value required for planning
  ansible.builtin.command: /usr/local/bin/read-state
  check_mode: false
  register: live_state

- name: Show the planned result
  ansible.builtin.debug:
    msg: "Current state: {{ live_state.stdout }}"
  check_mode: true

check_mode: true forces simulation for that task; check_mode: false forces normal execution even when the playbook was launched with --check. Use the latter cautiously because it performs a real remote action during an otherwise simulated run.

A pure check-mode run cannot provide ordinary registered output from tasks that are skipped or not executed by the module. Consequently, a later condition that depends on a prior registered result may have no useful data in simulation. Test those branches in a controlled environment, or make the data-gathering task explicitly run when that is safe.

A decision guide for choosing a conditional pattern

Pattern Decision data Evaluation scope Best fit Important caveat
Single when Fact or variable Once per host Platform or feature gate The referenced value must exist
List of when entries Several facts or variables Once per host Independent requirements joined by and Use one expression when you need or grouping
Registered-result test stdout, rc, or result status Once per host or per loop item Reacting to an earlier command or module The producer may be skipped in check mode
Loop plus when Current item Once per item Filtering a list or mapping Default undefined loop sources
Static import condition Facts or variables at expansion Every imported task Predictable platform-specific task sets The condition propagates through the imported file
Dynamic include condition Values available at runtime When the include is reached Decisions that depend on earlier changes Undefined or changed variables affect loading
failed_when or changed_when Task result fields On the producing task Custom command status and idempotence List entries use implicit and

Debug skipped or unexpected conditionals

  1. Confirm the data. Use ansible.builtin.debug: var=ansible_facts for facts or print a targeted variable with a default. Check spelling, capitalization, and the host on which the value is being evaluated.
  2. Remove template delimiters. In when, failed_when, and changed_when, write the raw expression rather than wrapping it in {{ }}.
  3. Cast before comparing. Apply | int to version-like strings and | float to measurements such as temperatures.
  4. Inspect registered fields. Print the result and look at stdout, stdout_lines, rc, failed, skipped, and changed. For loops, inspect the results list.
  5. Make optional collections safe. Use default([]) for lists and default({}) for mappings before looping.
  6. Check execution mode. Run with --check to see what supported modules would do, but remember that a branch depending on a registered result may lack that result because its producer did not execute.
  7. Separate platform logic when needed. If a task becomes a maze of nested expressions, move operating-system-specific variables, templates, or task files into clearly named imports or includes.

Complete example combining facts, results, loops, and status rules

---
- name: Configure the application
  hosts: app
  gather_facts: true
  tasks:
    - name: Install the package on Debian-family hosts
      ansible.builtin.package:
        name: myapp
        state: present
      when: ansible_facts['os_family'] == "Debian"

    - name: Check for the application marker
      ansible.builtin.command: test -f /etc/myapp/marker
      register: marker_check
      failed_when: false
      changed_when: false

    - name: Rebuild when the marker is absent
      ansible.builtin.command: /usr/local/bin/rebuild-myapp
      when: marker_check.rc != 0

    - name: Configure enabled listener ports
      ansible.builtin.template:
        src: listener.conf.j2
        dest: "/etc/myapp/listener-{{ item }}.conf"
      loop: "{{ listener_ports | default([]) }}"
      when:
        - item | int > 1024
        - ansible_facts['os_family'] in ["Debian", "RedHat"]

    - name: Query application status
      ansible.builtin.command: /usr/local/bin/app status
      register: app_status
      changed_when: false
      failed_when: app_status.rc not in [0, 3]

    - name: Report a stopped but valid application
      ansible.builtin.debug:
        msg: Application is installed but stopped
      when: app_status.rc == 3

This play uses a fact to select a platform, a registered return code to decide whether to rebuild, a per-item loop condition to filter ports, and explicit failure and change rules for a status command. Each decision is located next to the task whose behavior it controls.

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.