> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ubiquex.io/llms.txt
> Use this file to discover all available pages before exploring further.

# when — Conditional Resources

> Create or skip a resource entirely based on a condition.

`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 = condition` conditionally creates or skips a resource
* How to gate resources on environment, boolean inputs, or any resolved expression
* How `when = false` differs from `count = 0`

***

## Why this matters

<Info>
  `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.
</Info>

***

## The source code

<CodeGroup>
  ```hcl main.iac theme={"theme":"css-variables"}
  # This bucket always exists.
  unit "aws_s3_bucket_v2" "app" {
    bucket = "myapp-${input.env}"
  }

  # when = condition — the resource is only created when the condition is true.
  # In dev/staging, the replica bucket is skipped. In prod, it is created.
  unit "aws_s3_bucket_v2" "replica" {
    when   = input.env == "prod"
    bucket = "myapp-${input.env}-replica"

    tags = {
      ReplicaOf = "myapp-${input.env}"
    }
  }

  # when based on a bool input — enable via --var enable_audit_log=true.
  unit "aws_s3_bucket_v2" "audit_log" {
    when   = input.enable_audit_log
    bucket = "myapp-${input.env}-audit"

    tags = {
      Purpose = "audit-logging"
    }
  }
  ```

  ```hcl inputs.iac theme={"theme":"css-variables"}
  input "env" {
    type    = "string"
    default = "dev"
  }

  input "enable_audit_log" {
    type    = "bool"
    default = false
  }
  ```

  ```hcl outputs.iac theme={"theme":"css-variables"}
  output "app_bucket" {
    value = unit.aws_s3_bucket_v2.app.bucket
  }
  ```

  ```hcl ubx.iac theme={"theme":"css-variables"}
  ubx {
    name    = "when-conditional-resource"
    runtime = "typescript"
    stacks  = ["dev", "staging", "prod"]
  }

  backend "local" {
    path = ".ubx/state"
  }
  ```
</CodeGroup>

***

## How it works

<Steps>
  <Step title="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.
  </Step>

  <Step title="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.
  </Step>

  <Step title="References to conditional resources are checked">
    If another block references a resource that has `when = false`, the compiler raises a compile error — you cannot reference something that conditionally doesn't exist. This catches broken references before they reach Pulumi.
  </Step>
</Steps>

***

## What ubx generates

<CodeGroup>
  ```typescript index.ts theme={"theme":"css-variables"}
  // Generated by ubx — do not edit
  import * as pulumi from "@pulumi/pulumi";
  import * as aws from "@pulumi/aws";

  const config = new pulumi.Config();
  const env = config.get("env") || "dev";
  const enableAuditLog = config.getBoolean("enableAuditLog") ?? false;

  const app = new aws.s3.BucketV2("app", { bucket: `myapp-${env}` });

  const replica = env === "prod"
      ? new aws.s3.BucketV2("replica", {
          bucket: `myapp-${env}-replica`,
          tags: { ReplicaOf: `myapp-${env}` },
      }) : undefined;

  const auditLog = enableAuditLog
      ? new aws.s3.BucketV2("audit_log", {
          bucket: `myapp-${env}-audit`,
          tags: { Purpose: "audit-logging" },
      }) : undefined;

  export const appBucket = app.bucket;
  ```

  ```python __main__.py theme={"theme":"css-variables"}
  # Generated by ubx — do not edit
  import pulumi
  import pulumi_aws as aws

  config = pulumi.Config()
  env = config.get("env") or "dev"
  enable_audit_log = config.get_bool("enableAuditLog") or False

  app = aws.s3.BucketV2("app", bucket=f"myapp-{env}")

  replica = aws.s3.BucketV2("replica",
      bucket=f"myapp-{env}-replica",
      tags={"ReplicaOf": f"myapp-{env}"},
  ) if env == "prod" else None

  audit_log = aws.s3.BucketV2("audit_log",
      bucket=f"myapp-{env}-audit",
      tags={"Purpose": "audit-logging"},
  ) if enable_audit_log else None

  pulumi.export("app_bucket", app.bucket)
  ```

  ```go main.go theme={"theme":"css-variables"}
  // Generated by ubx — do not edit
  package main

  import (
      "github.com/pulumi/pulumi-aws/sdk/v6/go/aws/s3"
      "github.com/pulumi/pulumi/sdk/v3/go/pulumi"
      "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config"
  )

  func main() {
      pulumi.Run(func(ctx *pulumi.Context) error {
          cfg := config.New(ctx, "")
          env := cfg.Get("env")
          if env == "" { env = "dev" }
          enableAuditLog := cfg.GetBool("enableAuditLog")

          app, err := s3.NewBucketV2(ctx, "app", &s3.BucketV2Args{Bucket: pulumi.Sprintf("myapp-%s", env)})
          if err != nil { return err }

          if env == "prod" {
              _, err = s3.NewBucketV2(ctx, "replica", &s3.BucketV2Args{
                  Bucket: pulumi.Sprintf("myapp-%s-replica", env),
                  Tags:   pulumi.StringMap{"ReplicaOf": pulumi.Sprintf("myapp-%s", env)},
              })
              if err != nil { return err }
          }

          if enableAuditLog {
              _, err = s3.NewBucketV2(ctx, "audit_log", &s3.BucketV2Args{
                  Bucket: pulumi.Sprintf("myapp-%s-audit", env),
                  Tags:   pulumi.StringMap{"Purpose": pulumi.String("audit-logging")},
              })
              if err != nil { return err }
          }

          ctx.Export("appBucket", app.Bucket)
          return nil
      })
  }
  ```
</CodeGroup>

***

## Common mistakes

<Warning>
  Referencing a `when`-gated resource from another block without the same condition causes a compile error in stacks where the resource doesn't exist. If `unit.aws_s3_bucket_v2.replica` only exists in prod, any `output` or `deploy` block referencing `unit.aws_s3_bucket_v2.replica.bucket` must also have `when = input.env == "prod"`.
</Warning>

<Tip>
  `when` composes naturally with `for_each` and `count`. A resource can have both — if `when` is false, no copies are created regardless of the `for_each` value.
</Tip>

***

## Run it

```bash theme={"theme":"css-variables"}
ubx validate
ubx plan                                             # dev: only app bucket
ubx plan --var env=prod                              # prod: app + replica
ubx plan --var enable_audit_log=true                 # dev: app + audit
ubx plan --var env=prod --var enable_audit_log=true  # all three
```

***

## What you learned

<Check>`when = condition` skips a resource entirely when false — no state entry, no API calls, no generated code</Check>
<Check>`when` is evaluated at compile time against resolved input values</Check>
<Check>Referencing a `when`-gated resource requires the same condition on the referencing block</Check>

***

## Next steps

<CardGroup cols={2}>
  <Card title="Lifecycle block" href="/v1/tutorials/10-lifecycle-block">
    prevent\_destroy, ignore\_changes, create\_before\_destroy
  </Card>

  <Card title="Conditional expressions" href="/v1/tutorials/05-conditional-expressions">
    if/else, ??, and nested conditions
  </Card>
</CardGroup>

***

<Info>
  Full runnable example: [github.com/ubiquex/ubx-examples/09-when-conditional-resource](https://github.com/ubiquex/ubx-examples/tree/main/09-when-conditional-resource)
</Info>
