The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →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
Antihost offers Linux VPS plans with full root access, unlimited traffic on a 1 Gbps port and a 14-day free trial.
Ansible conditionals determine whether a task runs, fails, or reports a change. In most playbooks, you use when with a raw Jinja expression based on facts, variables, or a registered result; Ansible evaluates that expression separately for every host and skips the task when it is false.
Understand the when conditional
Attach when to a task, block, role, import, or include to make execution depend on data available at that point in the play. The expression is evaluated on each host, so two hosts can take different branches in the same play.
- name: Install a Debian-family package
ansible.builtin.package:
name: nginx
state: present
when: ansible_facts['os_family'] == "Debian"
The task runs only where the operating-system family fact equals Debian. On other hosts, Ansible reports the task as skipped rather than attempting the package operation.
Do not wrap when in Jinja delimiters
The value of when is already templated as a Jinja expression. Write the expression directly:
#1 Best Overall
- 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.
when: ansible_facts['distribution'] == "Ubuntu"
Do not write when: "{{ ansible_facts['distribution'] }}" == "Ubuntu". The same rule applies to failed_when and changed_when. The Ansible Community Documentation FAQ states that these conditionals are always run through Jinja2, so adding {{ }} should be avoided.
Combine several tests
A YAML list gives each test implicit and semantics: every entry must be true.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
- name: Enable a service on supported Debian releases
ansible.builtin.service:
name: nginx
state: started
enabled: true
when:
- ansible_facts['os_family'] == "Debian"
- ansible_facts['distribution_major_version'] | int >= 12
Facts that represent versions are often strings. Cast them before numeric comparisons with | int (or | float for decimal values). Without a cast, a comparison can be lexicographic instead of numeric.
Use parentheses and explicit and/or when the logic needs a different grouping:
when: (ansible_facts['os_family'] == "Debian" and web_tier | bool) or emergency_mode | bool
Keep complicated expressions readable by assigning an intermediate Boolean with set_fact, or by moving platform-specific tasks and variables into separate files.
Choose the right input: facts, variables, and derived values
Most conditions read one of three data sources: facts gathered from the host, ordinary variables supplied by inventory or the play, or values calculated during the run.
Use host facts for platform decisions
Facts are host attributes collected by Ansible. Common keys include:
ansible_facts['distribution']for the distribution name.ansible_facts['distribution_major_version']for its major release.ansible_facts['os_family']for a family such as Debian or RedHat.
Confirm that a fact exists on every target before relying on it. Fact availability can vary with the operating system, the fact-gathering configuration, and the module or connection being used. A condition that references a missing key can fail while templating rather than simply evaluating to false.
Rank #2
- 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
- name: Install a Red Hat-family package
ansible.builtin.package:
name: nginx
state: present
when: ansible_facts['os_family'] == "RedHat"
ansible_date_time deserves special care: it reflects the moment facts were gathered and can be stale in a long-running playbook. If a decision depends on the current time, do not assume that fact changes as the play proceeds.
Derive a value once with set_fact
When a condition combines several checks, calculate a named value first. This makes the decision visible and lets later tasks use the same result without duplicating an expression.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →- name: Classify a hot host
ansible.builtin.set_fact:
host_is_hot: "{{ temperature | float > 90 }}"
- name: Start cooling service
ansible.builtin.service:
name: cooling
state: started
when: host_is_hot
The assignment uses normal Jinja interpolation because set_fact is producing a value. The later when uses the Boolean variable directly, with no delimiters.
Prefer structure over deeply nested conditions
If Debian and Red Hat hosts need substantially different variables, templates, or task sequences, separate those files instead of creating one task file with many nested branches. A condition should express a decision; it should not conceal an entire alternative implementation. Separate files also make it easier to verify that each platform receives all of the tasks it needs.
Use registered results in later conditions
register stores the result of a task in a host-level variable for the current playbook run. Typical 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 command normally returns a nonzero exit code when the file is absent. Setting failed_when: false keeps that expected result from stopping the play, while the registered return code remains available to the next task.
Account for failures and skips
Ansible creates a registered result for each host even if the task failed or was skipped. If a later branch must handle an expected command failure, allow the task to continue with ignore_errors: true or an appropriate failed_when expression, then test the recorded result explicitly.
- name: Query optional component
ansible.builtin.command: /usr/local/bin/component --status
register: component_status
ignore_errors: true
- name: Repair a missing component
ansible.builtin.command: /usr/local/bin/component --repair
when: component_status is failed
Registered-result tests include is failed, is succeeded, is skipped, and is changed. Use them when the status itself is more meaningful than a particular return code.
Rank #3
- 【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.
Registered data is not a cross-run cache
Registered variables live in memory for the current playbook execution and are scoped as host-level data. A subsequent run does not inherit them. Persist information explicitly if a later run must use it, rather than assuming that a previous register value still exists.
Inspect command output deliberately
Choose the field that matches the decision. Use result.stdout for the complete text, result.stdout_lines for line-oriented checks, and result.rc for an exit status. A condition that tests the wrong field can remain false even though the command produced the expected information.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchApply conditions item by item in loops
When when is attached to a looping task, Ansible evaluates it separately for every item. Some iterations can run while others are skipped.
- name: Print only ports above 1024
ansible.builtin.debug:
msg: "{{ item }}"
loop: [80, 8080, 8443]
when: item > 1024
This task prints 8080 and 8443, while the iteration for 80 is skipped.
Protect optional list and dictionary inputs
If a loop variable might be undefined, provide a safe empty value. An undefined list should become []; an optional mapping should become {}.
- name: Configure requested ports
ansible.builtin.debug:
msg: "Opening {{ item }}"
loop: "{{ requested_ports | default([]) }}"
when: item > 1024
- name: Process configured accounts
ansible.builtin.debug:
msg: "Account {{ item.key }} has role {{ item.value }}"
loop: "{{ accounts | default({}) | dict2items }}"
when: item.value == "admin"
With these defaults, an absent variable produces zero iterations instead of an undefined-variable error.
Free tools Windows power users keep installed
One-click scans. No signup required.
Use the loop result when one iteration depends on another
A registered variable from a loop contains a results list, with one response per item. Per-iteration logic that reads a result from an earlier iteration must also handle the first iteration, when no previous response exists. Supply a default for that first lookup rather than dereferencing an absent element.
Control reuse with imports, includes, and roles
Conditions behave differently depending on how reusable content is brought into a play.
Rank #4
- 【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.
Static imports
A condition placed on a static import is applied to all tasks in the imported file. The imported tasks are expanded predictably as the playbook is parsed. This is useful when the same decision should govern the complete task file.
- 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. Its condition can therefore be decided using variables that change earlier in the play, and the included tasks are loaded only when the include is selected.
- name: Load optional hardening tasks
ansible.builtin.include_tasks: hardening.yml
when: hardening_enabled | bool
Choose imports for predictable, static expansion. Choose includes when the decision must happen dynamically or when variables may be updated before the include is reached.
Roles
Role reuse can also receive a condition. Put the condition at the role call when every task in that role should be limited to the same hosts, and keep task-level conditions inside the role for decisions that vary by task or item.
Redefine failure and change reporting
Modules have normal rules for deciding whether a task failed or changed. Use failed_when to replace failure semantics and changed_when to replace change reporting, especially for command and shell tasks whose exit code does not describe idempotent state.
- 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]
Here, status code 0 means healthy and 3 is an accepted alternate state. The query never reports a change, and only other return codes fail the task.
Combine failure or change tests correctly
When you provide a YAML list under failed_when or changed_when, entries are joined with implicit and. Every listed expression must be true for the combined result. If you need an or relationship, put it in one expression with explicit grouping.
- name: Accept two expected status codes
ansible.builtin.command: /usr/local/bin/app status
register: app_status
failed_when: app_status.rc != 0 and app_status.rc != 3
Do not add Jinja delimiters to either keyword. The same raw-expression rule used by when applies here.
Best Value
- 【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.
Understand conditionals in check mode
Check mode simulates supported module changes without modifying remote systems:
ansible-playbook site.yml --check
Add diff mode when the module supports it and you need to see file content differences:
Recommended Free Tools
ansible-playbook site.yml --check --diff
Use check_mode: true on a task to force simulation, even during an ordinary run. Use check_mode: false to force normal execution for a task even when the playbook was launched with --check.
- name: Always query the live service
ansible.builtin.command: /usr/local/bin/app status
check_mode: false
Check mode is not a complete second execution. A task that is skipped or not executed in simulation may not produce the ordinary registered output that a later condition expects. Consequently, a branch based on a prior registered result can be unevaluable or uninformative in a pure check-mode run. Design simulation paths so they do not require data that check mode cannot create.
Debug a conditional that is unexpectedly skipped
When Ansible skips a task you expected to run, inspect the input and the expression in this order:
- Verify the variable or fact exists. Temporarily add
ansible.builtin.debug: var=ansible_facts, or debug the specific variable used by the condition. A missing key is different from a false value. - Check the expression syntax. Remove
{{ }}fromwhen,failed_when, andchanged_when. Keep interpolation only where a module argument or assignment expects a rendered value. - Check data types. Cast version or numeric strings with
| intor| floatbefore comparing them. A quoted value may not behave like a number. - Inspect registered fields. Debug
stdout,stdout_lines,rc,failed, andskipped. For a loop, inspect the registered variable’sresultslist rather than treating it as one command response. - Guard optional loops. Use
default([])for lists anddefault({})for mappings before iterating. - Compare normal and check-mode behavior. A registered-result branch may lack its prerequisite output when run with
--check.
- name: Show the value used by a branch
ansible.builtin.debug:
msg:
os_family: "{{ ansible_facts['os_family'] | default('missing') }}"
release: "{{ ansible_facts['distribution_major_version'] | default('missing') }}"
marker_rc: "{{ marker_check.rc | default('missing') }}"
Use targeted debugging after the first inspection; dumping every fact on every host can obscure the value that actually controls the branch.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsSelect a conditional pattern by decision type
| Decision | Evaluate | Typical input | Important behavior |
|---|---|---|---|
| Platform-specific task | Once per host | ansible_facts['os_family'] |
Hosts with a false expression skip the task. |
| Version or feature gate | Once per host | Fact or variable, usually cast with | int or | float |
Lists use implicit and; explicit grouping handles or. |
| Decision from an earlier command | Once per host after the command | Registered rc, output, or status test |
The earlier task must produce a result; expected failures need suitable failure handling. |
| Filter loop items | Once per item | item and optional loop data |
Some iterations run and others skip; undefined sources need safe defaults. |
| Reuse a complete task file | At import or include time | Host facts or runtime variables | Static imports apply conditions to imported tasks; dynamic includes decide at runtime. |
| Redefine status | After module execution | failed_when or changed_when |
List entries use implicit and; write explicit Boolean logic for alternatives. |
| Simulation-only behavior | During check-mode execution | --check, check_mode |
Supported modules simulate changes, but prerequisite registered output may be absent. |
Combine the techniques in one play
The following example gathers platform data, checks a marker, filters a list per item, and reports a command’s status with custom semantics.
- name: Configure application hosts
hosts: app
gather_facts: true
vars:
requested_ports: [80, 8080, 8443]
tasks:
- name: Install package on Debian-family hosts
ansible.builtin.package:
name: nginx
state: present
when: ansible_facts['os_family'] == "Debian"
- name: Check for an application marker
ansible.builtin.command: test -f /etc/myapp/marker
register: marker_check
failed_when: false
- name: Rebuild application when marker is absent
ansible.builtin.command: /usr/local/bin/rebuild-myapp
when: marker_check.rc != 0
- name: Display only high-numbered requested ports
ansible.builtin.debug:
msg: "Port {{ item }} is selected"
loop: "{{ requested_ports | default([]) }}"
when: item > 1024
- name: Read 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: Explain an unavailable application
ansible.builtin.debug:
msg: "Application is not currently ready"
when: app_status.rc == 3
Each branch uses the data that is available at its point in the run: facts for platform selection, a registered return code for marker handling, the current loop item for per-port filtering, and explicit status semantics for the final query.
Quick Recap
Conditional habits that keep playbooks reliable
- Write every
whenexpression as raw Jinja, without interpolation delimiters. - Cast values before numeric comparisons and verify that the fact exists on the systems you target.
- Give optional loop inputs an empty list or mapping default.
- Use registered variables only within the current run and inspect their actual result fields.
- Make expected command outcomes explicit with
failed_whenandchanged_when. - Choose static imports for predictable expansion and dynamic includes for runtime decisions.
- Test both ordinary execution and
--checkwhen later conditions depend on earlier task output.
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.

