for_each and count let you create multiple resources from a single block. when is the complement: it lets you skip a resource entirely when a condition is false. A replica bucket that only exists in prod. An audit log bucket gated on a feature flag. A monitoring endpoint disabled in dev to save costs. Without when, you’d need a separate stack file per environment or a count = condition ? 1 : 0 hack borrowed from Terraform. when makes the intent explicit — this resource is conditionally present, and the condition is right there on the block. When when is false, ubx generates no code for that resource at all. It doesn’t exist in state, it doesn’t get planned, and no apply-time logic is needed to skip it.
What you’ll learn
- How
when = conditionconditionally creates or skips a resource - How to gate resources on environment, boolean inputs, or any resolved expression
- How
when = falsediffers fromcount = 0
Why this matters
when is evaluated at compile time — if the condition is false, the resource is entirely absent from the generated code. This is different from count = 0, which still registers the resource type with Pulumi. when produces genuinely absent resources with no state entry and no API calls.The source code
How it works
when is evaluated at compile time
input.env == "prod" is Resolved<T> — the compiler evaluates it against the resolved input value before generating code. If it evaluates to false, the entire unit block is removed from the IR.False means absent, not empty
When
when = false, the resource produces no output in the generated TypeScript/Python/Go. It doesn’t appear in the Pulumi resource graph, doesn’t get a state entry, and doesn’t generate any API calls.What ubx generates
Common mistakes
Run it
What you learned
when = condition skips a resource entirely when false — no state entry, no API calls, no generated codewhen is evaluated at compile time against resolved input valuesReferencing a
when-gated resource requires the same condition on the referencing blockNext steps
Lifecycle block
prevent_destroy, ignore_changes, create_before_destroy
Conditional expressions
if/else, ??, and nested conditions
Full runnable example: github.com/ubiquex/ubx-examples/09-when-conditional-resource

