Ansible in a Minute · Ansible Core ·
Use when on include_tasks, not import_tasks
Short answer
Put when on include_tasks so Ansible evaluates the condition once. import_tasks copies when onto every imported task.
Subscribe for updates
Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.
By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.
Request
include_tasks other_tasks.yml only when x is not defined
Example
A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.
---
# Prompt: include_tasks other_tasks.yml only when x is not defined
- name: Include other_tasks.yml only when x is not defined
hosts: all
gather_facts: false
tasks:
- name: Check if variable x is defined
ansible.builtin.set_fact:
x_is_defined: "{{ x is defined }}"
- name: Include other_tasks.yml if x is not defined
ansible.builtin.include_tasks:
file: other_tasks.yml
when: not (x_is_defined | bool)How it works
The first task records whether x is defined. when on include_tasks applies only to the include. If x is undefined, Ansible includes the file and runs every task inside it. import_tasks would copy the same when onto each imported task.
When to use it
- Loading a task file only when a value is missing
- Avoiding a skip after set_fact defines the variable you just tested
Requirements
- Ansible: >=2.14
- other_tasks.yml next to the playbook
Validation
- Syntax validated
- Not execution-tested
- Last verified 2026-10-15
Notes
Place this task file next to the playbook as other_tasks.yml:
---
- name: Set a variable
ansible.builtin.set_fact:
x: foo
- name: Print a variable
ansible.builtin.debug:
var: x
If you change include_tasks to import_tasks, Ansible copies the when onto every imported task. Use include_tasks when the whole file must run after the condition is true. | bool treats the set_fact string as a boolean.
Reference
- Conditionals with reuse (Ansible docs)
Built for every Ansible use case in every organization
BacklogZero can generate this kind of automation in your environment, just like it did here.