main.yml imports other_tasks.yml with when: x is not defined. The file first sets x with set_fact, then prints x with debug. x starts undefined. What happens, and how do you fix it?
set_fact runs and defines x, then debug checks the same condition, now finds x defined, and is skipped. Use include_tasks instead, so the condition is checked only once, at the include.
* An import checks the condition again on every task. An include checks it once. *
After parsing, the import turns into two tasks that both carry when: x is not defined:
set_fact: x: foochecks the condition:xis undefined, so it runs and definesx.debug: var: xchecks the condition again:xis now defined, so the condition is false and the task is skipped.
The intention was "if x was not set, set it and show it", but only half of it happens. With include_tasks, the condition belongs to the include task alone: it is checked once, before the file is read, and if it is true all tasks in the file run normally, without any condition of their own.
Tip: if a task inside the file changes what the condition tests, use an include.
Go deeper:
Conditionals with imports (official docs) — the set_fact / debug example of a condition copied onto every imported task.
Conditionals with includes (official docs) — the same example with include_tasks, where the condition is checked once.