Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Resources and Programs

Loops, Conditionals and Functions in Pulumi Programs

Use real programming features in Pulumi: loops and maps to create many resources, conditionals per stack, helper functions and types, stable names, and the pitfalls of looping over Outputs.

Your Pulumi program is ordinary code, so you can use ordinary tools to avoid repetition: loops, conditions, functions, classes and data files. This lesson shows the patterns that scale, and the one trap (looping over Outputs) that catches everyone once.

Pulumi examples are read-only. The runnable stand-ins imitate resource registration with plain JavaScript so you can practise the patterns.

Loops over plain data

Create one resource per item in a list, object or config value:

TypeScript
const buckets = ["assets", "logs", "backups"];

const created = buckets.map(name =>
  new aws.s3.BucketV2(name, { tags: { purpose: name } }));

export const bucketIds = created.map(b => b.id);

Python:

Python
buckets = {}
for name in ["assets", "logs", "backups"]:
    buckets[name] = aws.s3.BucketV2(name, tags={"purpose": name})

pulumi.export("bucket_ids", [b.id for b in buckets.values()])

Stable names matter

The logical name is part of the URN, so:

  • use stable keys ("assets", a customer ID), not list positions (bucket-0, bucket-1);
  • if you remove the first item of a list that is named by position, every later resource gets a new name and is replaced.
TypeScript
// Fragile: index-based names
users.forEach((u, i) => new aws.iam.User(`user-${i}`, { name: u }));

// Stable: key-based names
users.forEach(u => new aws.iam.User(`user-${u}`, { name: u }));

This is the same lesson as count versus for_each in Terraform.

Conditionals

Branch on plain values: configuration, the stack name, constants.

TypeScript
const config = new pulumi.Config();
const enableBackups = config.getBoolean("enableBackups") ?? false;

if (enableBackups) {
  new aws.s3.BucketV2("backups", { versioning: { enabled: true } });
}

const instanceType = pulumi.getStack() === "prod" ? "m6i.large" : "t3.micro";

Setting the flag per stack keeps the code identical in every environment (Config per Environment). A removed if branch results in a delete of that resource at the next update.

Optional values

TypeScript
new aws.ec2.Instance("vm", {
  instanceType,
  keyName: config.get("keyName"),        // undefined means "not set"
  tags: { ...(isProd ? { backup: "daily" } : {}) },
});

Helper functions

Wrap repeated patterns in functions that take Inputs and return resources:

TypeScript
interface BucketArgs { name: string; versioned?: boolean }

function privateBucket(args: BucketArgs): aws.s3.BucketV2 {
  const bucket = new aws.s3.BucketV2(args.name);
  new aws.s3.BucketPublicAccessBlock(`${args.name}-block`, {
    bucket: bucket.id,
    blockPublicAcls: true,
    blockPublicPolicy: true,
    ignorePublicAcls: true,
    restrictPublicBuckets: true,
  });
  if (args.versioned) {
    new aws.s3.BucketVersioningV2(`${args.name}-versioning`, {
      bucket: bucket.id,
      versioningConfiguration: { status: "Enabled" },
    });
  }
  return bucket;
}

const assets = privateBucket({ name: "assets", versioned: true });

A function is the lightest form of reuse. When you want a single named node in the resource tree with its own inputs and outputs, upgrade it to a component class (Components).

Data files

Keep configuration data separate from code:

TypeScript
import * as fs from "fs";
const sites = JSON.parse(fs.readFileSync("sites.json", "utf-8")) as { name: string; domain: string }[];
sites.forEach(s => new aws.route53.Record(s.name, { name: s.domain, /* ... */ }));

The trap: looping over an Output

TypeScript
// WRONG: subnetIds is Output<string[]>, unknown during preview
subnetIds.apply(ids => ids.forEach(id => new aws.ec2.Instance(`vm-${id}`, { subnetId: id })));

Resources created inside apply are hidden from the preview, may be created late, and break dependency tracking. Prefer:

  1. Loop over something known before deployment (a config list of AZ names, a count).
  2. Use the index, not the Output value, in names, and give the Output to the resource as an input:
TypeScript
const azs = ["a", "b", "c"];
azs.forEach((az, i) => new aws.ec2.Subnet(`private-${az}`, {
  vpcId: vpc.id,                       // Output as input: fine
  availabilityZone: `eu-west-1${az}`,
  cidrBlock: `10.0.${i}.0/24`,
}));
  1. If the list really only exists after another deployment, put that part into a separate stack and read the result with a StackReference.

Stand-in: a loop that registers resources

JS Stand-in: generate resources from data

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in: unstable versus stable names

JS Stand-in: index names versus key names

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should resource names come from stable keys instead of list indexes?

    The name is part of the URN, so unstable names cause unnecessary replacements.
  2. 2. What should conditionals in a program branch on?

    Plain values are known during preview, so the plan is accurate.
  3. 3. What is wrong with creating resources inside outputs.apply?

    apply may not run during preview, so the resources are invisible to the plan.
  4. 4. When should a helper function become a component?

    Components group children and give a clean interface.

Summary

  • Loops, conditions, functions and data files all work, because the program is real code.
  • Use stable, key-based logical names.
  • Branch on plain values (config, stack name), never on Outputs.
  • Do not create resources inside apply; loop over known data and pass Outputs as inputs.
  • Promote repeated patterns to functions, then to components.

Next: Config Basics: pulumi config and the Config Object