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.
---
- name: Include extra tasks when x is not defined
hosts: all
gather_facts: false
tasks:
- name: Include other tasks when x is not defined
ansible.builtin.include_tasks:
file: other_tasks.yml
when: x is not definedHow it works
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-11
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 applies when: x is not defined to both tasks. The first task sets x. The second task is then skipped. Use include_tasks when the whole file must run after the condition is true.
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.