Pulumi: Infrastructure as Actual Code
Use Pulumi to define infrastructure using real programming languages—TypeScript, Python, Go, C#—enabling loops, conditionals, and full IDE support for IaC.
Pulumi runs programs in general-purpose languages to declare resources, then compares them with per-stack state and provider data to plan updates. This guide pins a TypeScript and AWS example, compares it with Terraform and OpenTofu, and covers state, locking, preview, secrets, drift, and recovery.
Pulumi: Infrastructure as Actual Code
Pulumi lets you declare infrastructure with TypeScript, Python, Go, C#, Java, and other supported languages. Your program can use ordinary language features, but Pulumi still builds a resource graph and compares the declared resources with stack state before it proposes updates. The syntax does not make a change safe on its own; the provider, current state, configuration, and review all matter.
HCL and general-purpose languages make different trade-offs. HCL is purpose-built for configuration and supports expressions, modules, and resource repetition. Pulumi can be convenient when infrastructure code shares types, functions, or tests with an existing application codebase, but it also brings that language’s runtime and package-management concerns.
Introduction
Pulumi and Terraform both compare declared configuration with state to work out resource operations. Terraform configurations use HCL; Pulumi programs use a supported language to register resources and their dependencies. A Pulumi program may contain imperative code, but that does not mean the engine executes an arbitrary list of provisioning steps.
Terraform and OpenTofu have related HCL workflows and use their own CLI and provider lock files. Pulumi has language SDK packages plus provider plugins. The tool you choose affects the provider schema, state workflow, plan review, and recovery steps; similar-looking resource code does not guarantee identical behavior.
Pulumi can store state in Pulumi Cloud or a self-managed backend. A local or remote DIY backend still needs secure access controls, backups, and recovery procedures, and cloud resources still require the provider’s API access. See Pulumi’s state and backend overview.
Version scope for the examples
The TypeScript examples below use Pulumi CLI 3.277.0, @pulumi/pulumi 3.276.0, and @pulumi/aws 7.55.0. These packages have separate version numbers; pin them separately and commit the package-manager lock file. See Pulumi’s CLI version list, the exact @pulumi/pulumi 3.276.0 package, and the exact @pulumi/aws 7.55.0 package.
The HCL comparison uses Terraform CLI 1.17.2 or OpenTofu CLI 1.13.9, with hashicorp/aws provider 6.74.0. See the Terraform 1.17.2 release, OpenTofu 1.13.9 release, and AWS provider 6.74.0 release. Pin the CLI and provider in the relevant configuration and commit the generated provider lock file. Later releases may change APIs or behavior; these versions define the examples, not a compatibility guarantee for every Pulumi integration.
Setting Up Pulumi Projects
Install the pinned CLI from Pulumi’s versioned install instructions, then create a project with pulumi new. Pin the language SDK and provider in the generated package manifest instead of accepting an unbounded latest version.
# Install the version pinned for this example using Pulumi's install instructions
# Pulumi CLI: 3.277.0
# Create a new TypeScript project
pulumi new aws-typescript --dir ./my-infra
cd my-infra
# Pin TypeScript SDK and AWS provider packages
npm install --save-exact @pulumi/pulumi@3.276.0 @pulumi/aws@7.55.0
# Preview the stack
pulumi preview
Each project contains a Pulumi.yaml file. A stack is a deployment target such as dev, staging, or production, with its own configuration and state. Terraform/OpenTofu workspaces also separate state, but their backend and workspace semantics differ; do not assume that a stack and workspace are interchangeable.
In a TypeScript project, the entry point is usually index.ts. Pulumi runs the program through its language host; the program registers resources and exports stack outputs. It does not require a universal main(ctx) function that returns an array.
Defining Resources in TypeScript
The AWS SDK exposes resource constructors. This small example declares one bucket; it does not create anything until an update is approved and applied.
import * as aws from "@pulumi/aws";
const bucket = new aws.s3.Bucket("review-assets", {
bucket: "replace-with-a-globally-unique-name",
tags: {
Environment: "dev",
Owner: "platform",
},
});
export const bucketName = bucket.id;
Replace the bucket name before using the example; S3 names must be globally unique. Check the Pulumi aws.s3.Bucket reference for the inputs and lifecycle behavior, selecting version 7.55.0.
State Management with Pulumi Backend
Each Pulumi stack has state in a selected backend. Pulumi Cloud coordinates updates and provides hosted history and access controls. DIY backends—including local files, S3, Azure Blob, Google Cloud Storage, S3-compatible storage, and PostgreSQL—use built-in file-based locks, but teams must manage storage permissions, backups, and recovery. The S3 DIY backend does not require DynamoDB for Pulumi’s lock files; see Using a DIY Backend for backend-specific setup and permissions.
import * as pulumi from "@pulumi/pulumi";
const config = new pulumi.Config();
// Use stack references to access outputs from other stacks
const otherStack = new pulumi.StackReference("acme/webapp/production");
// Reference outputs from the other stack
const vpcId = otherStack.getOutput("vpcId");
Stack references let you compose infrastructure across teams and stacks. One stack can export values that another stack imports, enabling modular infrastructure at scale.
Using Programming Constructs for DRY Code
Pulumi programs can use loops, conditionals, and functions to reduce repetition. Use those features when the resulting resource names, dependencies, and provider operations stay clear in a preview.
// Create multiple resources with a loop
const environments = ["dev", "staging", "production"];
const environment = "staging";
environments.forEach((env) => {
new aws.ec2.Instance(`server-${env}`, {
instanceType: env === "production" ? "t3.large" : "t3.micro",
ami: "ami-replace-for-your-region", // Choose an approved AMI for the target account and region
tags: { Name: `server-${env}` },
});
});
// Create resources conditionally
if (environment === "production") {
new aws.rds.Instance("database", {
instanceClass: "db.r6g.large",
allocatedStorage: 100,
engine: "postgres",
engineVersion: "15.3",
});
}
// Abstract common patterns into functions
function createAppServer(name: string, env: string, scale: number) {
const asg = new aws.autoscaling.Group(name, {
minSize: scale,
maxSize: scale * 3,
instanceType: "t3.micro",
tags: [{ key: "Name", value: `${name}-${env}`, propagateAtLaunch: true }],
});
return asg;
}
const apiServers = createAppServer("api", environment, 2);
You can also define custom components that encapsulate multiple resources into a single reusable abstraction. A Network component might create a VPC, subnets, NAT gateways, and route tables, exposing only the configuration it really needs.
Testing Infrastructure Code
Pulumi programs run in regular language runtimes, so teams can use familiar testing frameworks for program logic.
// Unit test with Jest
import { describe, it, expect } from "@jest/globals";
describe("EC2 Instance", () => {
it("should use t3.micro for non-production", () => {
// Programmatically verify instance type logic
const env = "staging";
const expectedType = env === "production" ? "t3.large" : "t3.micro";
expect(expectedType).toBe("t3.micro");
});
});
This test checks a local expression only; it does not inspect a resource registered with Pulumi. Use Pulumi resource mocks to assert registered resource types and inputs, or policy tests to check rules before deployment.
Tests can catch mistakes in the code paths and resource inputs they cover. Type checks and unit tests do not verify provider behavior against a live account or prove that a deployment is safe; review the preview against the target state.
When to Use / When Not to Use
When Pulumi makes sense
Pulumi may fit when a team already maintains substantial TypeScript, Python, Go, C#, or Java code and wants to share language tooling or abstractions with infrastructure.
General-purpose languages can make complex generation or shared libraries convenient. HCL also supports expressions, loops, conditionals, modules, and tests, so compare the actual provider coverage and team workflow rather than assuming one syntax is safer or more capable.
Pulumi offers language-level unit tests and resource mocks. Terraform and OpenTofu also support configuration tests and plan review. A passing unit test does not replace checking the provider plan against real state.
When to use Terraform instead
HCL may be easier to review for teams that prefer configuration-focused infrastructure. Pulumi requires a language runtime, package dependencies, and familiarity with how that SDK represents resources.
If a provider is available only in the Terraform/OpenTofu ecosystem, check whether Pulumi’s Any Terraform Provider can generate an SDK for it. Compare provider coverage, lifecycle behavior, and maintenance needs before choosing the workflow.
If your organization has existing Terraform/OpenTofu modules and runbooks, compare the migration cost and provider behavior before changing tools. A new project is not automatically a reason to choose Pulumi.
Pulumi Architecture Flow
flowchart TD
A[Pulumi Program .ts/.py/.go] --> B[pulumi up]
B --> C[Pulumi Engine]
C --> D[Compare Desired vs Actual]
D --> E[Build Resource Graph]
E --> F[Plan Resource Operations]
F --> G[Cloud Provider APIs]
G --> H[Real Infrastructure]
H --> I[State Updated]
I --> D
Trade-off Analysis
One bucket, three toolchains
The following snippets declare one tagged S3 bucket. Use a globally unique name and run only one tool against it; importing an object into another state does not make the two tools coordinate.
Pulumi TypeScript (CLI 3.277.0, core SDK 3.276.0, @pulumi/aws 7.55.0):
import * as aws from "@pulumi/aws";
const bucket = new aws.s3.Bucket("review-assets", {
bucket: "replace-with-a-globally-unique-name",
tags: { Environment: "dev", Owner: "platform" },
});
export const bucketName = bucket.id;
Terraform 1.17.2 or OpenTofu 1.13.9 with hashicorp/aws 6.74.0:
terraform {
# Use = "1.13.9" for OpenTofu instead of Terraform's = "1.17.2".
required_version = "= 1.17.2"
required_providers {
aws = {
source = "hashicorp/aws"
version = "= 6.74.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "review_assets" {
bucket = "replace-with-a-globally-unique-name"
tags = { Environment = "dev", Owner = "platform" }
}
| Concern | Pulumi TypeScript | Terraform / OpenTofu HCL |
|---|---|---|
| State and drift | One state per Pulumi stack. Preview compares code with recorded state; refresh is opt-in with pulumi refresh or --refresh. See Pulumi state. |
State is selected by the configured backend and workspace. A normal plan refreshes provider data by default; backend locking and storage settings vary. See Terraform state and OpenTofu state. |
| Locking | Pulumi Cloud coordinates updates. DIY backends use built-in file locks; the team still owns backend access, backups, and recovery. See DIY backends. | The backend locks writes if it supports locking. If it cannot acquire the lock, plan/apply stops; force-unlock is only for your own abandoned lock. See Terraform and OpenTofu locking docs. |
| Preview and review | pulumi preview --diff shows proposed operations. Update plans can constrain a later pulumi up, but are experimental in this scope. See Pulumi update plans. |
terraform plan -out=tfplan or tofu plan -out=tfplan saves a plan for review and later application by the matching CLI. See Terraform plan and OpenTofu plan. |
| Secrets | Values marked as secrets are encrypted through the stack’s configured secrets provider and remain marked through dependent outputs. Plain values, logs, and resource IDs may still expose sensitive data. See Pulumi secrets. | sensitive redacts CLI output but values can remain in state and plan. Encryption depends on the backend; OpenTofu also supports explicit state and plan encryption. See Terraform and OpenTofu. |
| Provider behavior | @pulumi/aws 7.55.0 is a distinct Pulumi package with its own schema and plugin release, based on the Terraform AWS provider. Review the selected Pulumi resource docs and preview. |
hashicorp/aws 6.74.0 has its own schema and lock entry. Similar resource names do not guarantee matching defaults or replacement behavior. Review the selected Terraform resource docs. |
| Team review | Review the language diff and preview together. Pin packages, protect the stack backend, and serialize updates to a stack. | Review the HCL diff and saved plan together. Pin the CLI/provider, secure plan artifacts, and serialize writes to the workspace. |
These tools all manage declared infrastructure, but they do not share one state lock or a single provider implementation. Keep one tool as the writer for a given resource. OpenTofu and Terraform use the same HCL resource pattern here, but still run under separate CLI versions and lock files.
Import, drift, and recovery
Import binds an existing cloud object to a resource address in one tool’s state; it does not prove that the code matches the object’s intended configuration. Pulumi’s pulumi import generates a resource definition and records the object. Terraform/OpenTofu support import blocks and CLI import; review a fresh plan after importing. Refresh updates tracked state from provider observations. It does not adopt every untracked object, and Pulumi does not refresh automatically during an ordinary preview or update. See Pulumi state refresh and Terraform import.
Treat an interrupted update as a partial operation, not a transaction that rolled back. Check the cloud provider first. For Pulumi, cancel a still-running update if appropriate, then follow the interrupted-update recovery steps: refresh state, resolve pending creates, and import an object if the provider created it but state does not record it. If the intended result is to undo the change, revert the program/config and run a reviewed update; restoring an old state file alone does not reverse cloud changes. Export/import state only as a deliberate recovery action after taking a backup, as described in editing Pulumi state.
Terraform/OpenTofu also need backend-specific recovery when an apply partially succeeds. Inspect state and provider reality before another apply, preserve the state backup, and use import or a refresh-only plan where appropriate. Do not disable locking to get past a blocked operation.
Preview and approval workflow
- Pin the CLI, language SDK, and provider versions; commit dependency lock files. Select the intended account, region, stack/workspace, and backend before planning.
- For Pulumi, generate a fresh diff with
pulumi preview --diff. If out-of-band drift is suspected, refresh and preview again; refresh updates state. For HCL, generate a plan with the selected CLI and provider. - Review the code diff and plan together. Check deletes, replacements, unknown values, provider changes, secrets, and the recovery path. Require an authorized human approval for production changes.
- Where Pulumi update plans are enabled, save and apply the reviewed plan with
PULUMI_EXPERIMENTAL=true pulumi preview --save-plan=plan.jsonandPULUMI_EXPERIMENTAL=true pulumi up --plan=plan.json. This experimental plan constrains the operations, but does not guarantee every value is known at preview time. For Terraform/OpenTofu, use the saved plan withterraform apply tfplanortofu apply tfplan. - Treat saved plans and state exports as sensitive artifacts, keep them access-controlled, and regenerate the plan if code, config, provider versions, or state changes before approval.
Production Failure Scenarios
Common Pulumi Failures
These are operational failure modes to plan for. The right recovery steps depend on the backend, provider, and whether a cloud operation completed before the CLI stopped.
| Failure | Impact | Mitigation |
|---|---|---|
| Update is interrupted after a provider request | A resource may exist even if the stack has a pending create or stale state | Check the provider, then follow interrupted-update recovery steps; do not assume automatic rollback |
| Stack reference points to a removed stack | Dependent update cannot resolve outputs | Coordinate stack removal and update or remove references first |
| Preview proposes an unexpected deletion | A resource could be removed during up |
Stop, confirm account/stack/state and inspect the diff; do not use a targeted update to hide an unexplained change |
| Language runtime or dependency changes | Resource inputs may change or the program may fail before registration | Pin runtime and package versions, then review the preview after upgrades |
| State differs from cloud reality | A plan may overwrite out-of-band changes or create a duplicate | Refresh tracked resources, import unmanaged resources when appropriate, then preview again |
Pulumi does not automatically roll back completed provider operations after an update fails. For an interrupted operation, inspect the cloud resource before changing state. If the CLI reports pending operations, cancel a still-running update when appropriate, then run pulumi refresh and resolve pending creates based on what the provider actually created. If you intend to undo a completed change, revert the program/config and run a new reviewed update. See Pulumi’s interrupted-update recovery guide and failed-update FAQ.
Stack references bind stacks together. Delete a referenced stack without updating the references, and your next deployment fails with an opaque error. Validate that a stack exists before you reference it. Treat stack deletions as a coordination event, not an individual team decision.
State desynchronization can follow manual changes, provider errors, or an interrupted update. pulumi refresh updates state for resources already tracked; it does not edit the Pulumi program or import every untracked resource. After refreshing, review a new preview before applying the desired configuration.
Policy Enforcement Flow
flowchart TD
A[pulumi up] --> B[Preview Changes]
B --> C[Pulumi Policy Engine]
C --> D{All policies pass?}
D -->|Yes| E[Apply Changes]
D -->|No| F[Show Policy Violations]
F --> G[Fix Code or Override]
G --> B
E --> H[Update State]
Observability Hooks
Track Pulumi operations to maintain operational awareness.
What to monitor:
- Deployment frequency and duration per stack
- Policy violation rate (catch non-compliant resources early)
- Stack reference chain health
- State file size and resource count per stack
- Failed deployments and error types
# View deployment history
pulumi stack history
# Check resource count
pulumi stack --show-urns | wc -l
# Export stack for audit
pulumi export --file state.json
# Validate stack
pulumi validate
# Preview with policy
pulumi preview --policy-pack policies/
Common Pitfalls / Anti-Patterns
Over-abstracting infrastructure
Pulumi’s expressiveness tempts you into building elaborate class hierarchies for infrastructure. A three-level inheritance chain for a VPC is harder to debug than three simple resource declarations. Start concrete, abstract only when repetition demands it.
The trap looks like this: you create a InfrastructureStack base class, then a NetworkLayer subclass, then a PrivateNetworkLayer that inherits from it. Six months later, debugging why your VPC has the wrong CIDR block means tracing through three levels of indirection. The resource declarations that would have taken ten lines sit buried under an abstraction hierarchy that took a day to build.
You know abstraction has gone too far when a component’s constructor needs more than five arguments, when methods exist only to call other methods, or when class names describe infrastructure types instead of business domains. If you find yourself writing new VpcComponent("prod-vpc", { ... }) and VpcComponent internally creates six sub-components, ask whether the nine lines of direct resource declarations would be clearer.
Abstraction earns its keep when you have the same pattern three or more times. A DatabaseCluster component used by four different stacks, each with slight variations, justifies the upfront cost. A VPC used once does not. Do not build a reusable framework for a problem you have not actually encountered yet.
When a Pulumi resource wrapper is missing
If a resource is missing from a prebuilt Pulumi package, first check whether the Any Terraform Provider can generate an SDK from an existing Terraform or OpenTofu provider. A low-level custom resource is another option, but without a generated schema you lose TypeScript’s input and output checks. The resource still participates in Pulumi state and dependency tracking; the type token, properties, provider support, and lifecycle behavior must match the provider. Check its documentation and inspect a preview before applying the change.
Not using policy-as-code
Pulumi CrossGuard or the Policy as Code feature catches problems before they deploy. Skipping policy enforcement means misconfigured resources reach production. Integrate policies into your CI pipeline.
Policy packs are written in the same language as your infrastructure. A TypeScript policy might enforce that all S3 buckets have encryption enabled, that RDS instances are not publicly accessible, or that EC2 instances run in approved VPCs. The policy runs during pulumi preview and blocks deployments that violate rules.
import { PolicyPack, resourceValidationPolicy } from "@pulumi/policy";
new PolicyPack("aws-policies", {
policies: [
resourceValidationPolicy({
name: "s3-bucket-encryption",
description: "Ensures S3 buckets have encryption enabled.",
validateResource: validateResourceOfType(
aws.s3.Bucket,
(bucket, args) => {
if (!bucket.serverSideEncryptionConfiguration) {
return {
message: "S3 buckets must have encryption enabled.",
};
}
},
),
}),
],
});
Without policies, someone can ship a public RDS instance or an unencrypted S3 bucket and only find out during an incident. With policies enforced in CI, violations show up during code review, where they are cheap to fix. Spend time writing policies for your non-negotiables before you are in a situation where you need them.
Storing secrets in plain text
Mark sensitive configuration as a Pulumi secret with pulumi config set --secret, or mark program values with pulumi.secret. Pulumi encrypts marked values through the stack’s configured secrets provider. Pulumi Cloud manages a per-stack key by default; a DIY backend can use a configured passphrase or KMS provider. Unmarked values are not automatically secret, and the program can still expose decrypted values through logs or external systems.
Secret values propagate through dependent resource inputs and outputs, and are encrypted in state. However, the physical resource ID remains plain text, and secrets are decrypted for use by the program. Treat the full state and any plan or export as sensitive; secret marking is not a replacement for access controls and secure logs. See Pulumi’s secrets documentation.
For Terraform, sensitive redacts displayed values but does not remove them from state or saved plan files; protect the backend and artifact. OpenTofu also supports explicit encryption for state and plan files, but losing the required key can make them unrecoverable. See Terraform’s sensitive-data guide and OpenTofu’s state and plan encryption guide.
Teams with more complex secrets needs can use Pulumi ESC (Environments, Secrets, and Configuration), which provides a managed secrets vault with audit logging and environment layering. It connects to AWS Secrets Manager, Azure Key Vault, and GCP Secret Manager so you can reuse existing secrets infrastructure instead of maintaining a second one.
Skipping pulumi preview
Run a preview or plan for changes that need review, including in CI. Make the preview part of an approval process for production updates.
pulumi preview reports proposed operations based on the program and stack’s recorded state; by default, Pulumi does not refresh state first. Values may still be unknown until apply, and external changes can make the preview stale. Use pulumi preview --refresh when you need to reconcile tracked resources before reviewing the diff, then review the new result. Refresh updates state even though preview does not apply resource changes.
The selected account, region, stack, provider version, and state all affect the result. Verify those before reviewing a diff. Do not treat preview as a guarantee that up will succeed or that no external actor will change the infrastructure afterward.
For an approval workflow, run preview on the pull request and show the resource diff next to the code change. Require an authorized reviewer to approve the specific creates, updates, deletes, and replacements. Then apply the reviewed saved plan when available, or generate and inspect a fresh preview immediately before pulumi up. Platform settings or CI policy must enforce this gate; displaying a preview by itself does not block an update.
Pay close attention to replacements and deletes, plus values that remain unknown. If the plan does not match the PR’s intent, stop and investigate the stack, provider schema, or state before approving it.
Interview Questions
Expected answer points:
- TypeScript, Python, Go, C#, and Java
- All languages have full access to Pulumi SDK and providers
- Language choice affects team productivity and existing skill sets
Expected answer points:
- All three tools compare declared resources with state and provider data to propose resource operations.
- Terraform and OpenTofu use HCL; Pulumi registers resources through a general-purpose language SDK.
- Pulumi programs can use ordinary language features, but the engine still builds a dependency graph.
- The language choice does not guarantee safer infrastructure; review the provider's preview or plan.
Expected answer points:
- Stack represents a deployment target (dev, staging, production)
- Each stack has its own state file and configuration
- Similar to Terraform workspaces in purpose
- Stacks can reference each other via StackReference for cross-stack dependencies
Expected answer points:
- Pulumi Service manages state automatically (SaaS)
- Backends include Pulumi Cloud and DIY storage such as local files, S3, Azure Blob, GCS, S3-compatible storage, or PostgreSQL.
- Pulumi Cloud coordinates stack updates; DIY backends have built-in file locks, while the team manages access, backups, and recovery.
pulumi refreshreconciles tracked resources;pulumi importadopts an existing resource.- Export/import can repair state but should follow a backup and a documented recovery plan.
Expected answer points:
- Use standard language loops (for, forEach, etc.)
- Example: environments.forEach((env) => { new aws.ec2.Instance(...); })
- Loops work with any language construct: for, while, map, filter
- No special HCL syntax needed
Expected answer points:
- Pulumi supports language tests and resource mocks; those can verify program logic and registered resource inputs.
- Terraform and OpenTofu provide configuration tests and reviewable plans.
- Provider previews/plans still need review against the real target state.
- Type checks and unit tests do not prove that an update is safe or will succeed.
Expected answer points:
- StackReference imports outputs from another stack
- Syntax: new pulumi.StackReference("org/project/stackname")
- Use getOutput("outputName") to access outputs from referenced stack
- Shares outputs across stacks, creating an explicit dependency between them
Expected answer points:
- Check whether the Any Terraform Provider can generate a Pulumi SDK from the existing Terraform/OpenTofu provider.
- A low-level custom resource is possible, but without a generated schema TypeScript cannot check its input and output properties.
- Confirm the provider token, property names, and lifecycle behavior against provider documentation.
- Review the Pulumi preview before applying the change.
Expected answer points:
- Use standard if/else statements
- Example: if (environment === "production") { new aws.rds.Instance(...); }
- Conditional logic executes at program runtime
- No special configuration syntax needed
Expected answer points:
- Pulumi policy as code enforces compliance rules before deployment
- Policy packs written in the same language as infrastructure
- Run pulumi preview --policy-pack to check policies before apply
- Enforce policy in CI or another approval point when the organization requires a deployment gate.
- Integrate into CI pipeline for automated enforcement
Expected answer points:
- Terraform ecosystem is larger (more providers, modules, community examples)
- Pulumi growing but smaller - check provider coverage before committing
- Major cloud providers (AWS, Azure, GCP) have first-class Pulumi support
- Community contributions increasing but behind Terraform
Expected answer points:
- Mark sensitive config with
pulumi config set --secretor a programmatic secret wrapper; a configured secrets provider encrypts marked values. - Unmarked values, program logs, and physical resource IDs can still expose sensitive information.
- Treat state and plan files as sensitive and protect backend access.
- Terraform's
sensitivemarker redacts display but does not remove values from state; OpenTofu also offers explicit state/plan encryption. - Pulumi ESC can manage shared environment secrets, but it does not replace reviewing secret flow through the program.
Expected answer points:
- The language host runs the project's entry file, commonly
index.ts. - Constructing SDK resources registers them and their dependencies with the Pulumi engine.
- The engine compares declared resources with stack state and provider observations to propose operations.
- A program can use language functions and control flow; it does not need a universal
main(ctx)signature.
Expected answer points:
- Define custom components encapsulating multiple resources
- Example: Network component creates VPC, subnets, NAT gateways, route tables
- Components expose only the configuration they need
- Functions can also abstract patterns (createAppServer, createDatabase)
- Avoid over-abstracting - three-level inheritance chains are hard to debug
Expected answer points:
- Pulumi does not automatically roll back provider operations that already completed.
- Inspect provider reality and pending operations before changing state.
- Cancel an update only if it is still active, then use
pulumi refreshto resolve pending creates. - Import a resource if the provider created it but the stack does not track it.
- If you intend to reverse completed work, revert code/config and run a reviewed update; an old state file does not undo cloud changes.
Expected answer points:
- Pulumi engine determines if update is possible in place or requires recreation
- Changing instance type updates in place for EC2
- Changing VPC CIDR block requires recreation (not possible)
pulumi previewshows the proposed update or replacement, subject to values the provider can resolve during preview.
Expected answer points:
- Local backend: state in the filesystem, useful for individual workflows as well as experiments.
- DIY backends include local files, S3, Azure Blob, Google Cloud Storage, S3-compatible storage, and PostgreSQL.
- DIY backends provide built-in file-based state locks; S3 locking does not require DynamoDB.
- The team must secure storage access, backups, and recovery for a DIY backend.
- Choose a backend based on operational requirements, not a general compliance guarantee.
Expected answer points:
- Stop and verify account, stack, and resource identity; do not hide an unexpected change with targeting.
- If a delete already completed, restore the resource through its provider or recover its data from an appropriate backup.
- Reconcile Pulumi state with
pulumi refresh, then review a fresh preview. - Use resource protection where supported and keep a tested recovery procedure.
Expected answer points:
- Preview reports proposed operations against the current program and recorded state; some values may remain unknown.
- External drift can make a preview stale; refresh tracked resources when needed and review a fresh result.
- Show the plan with the code change and require an authorized approval before production updates.
- Use an update plan or saved HCL plan when available, and protect the plan artifact.
Expected answer points:
- The team prefers configuration-focused HCL workflows and has less need for a general-purpose language runtime
- Need a specific Terraform provider with no Pulumi equivalent
- Organization has existing Terraform modules and runbooks - migration cost too high
- Ops-focused engineers without application development experience
- The existing workflow, provider schema, and review process fit the team's needs better
Further Reading
- Pulumi Documentation - Official Pulumi docs
- Pulumi Blog - Tutorials and best practices
- Pulumi state and backends - State, refresh, and backend choices
- Pulumi secrets - Secret marking and encryption providers
- Pulumi update plans - Restricting an update to reviewed operations
- Pulumi ESC - Environments, Secrets, and Configuration
- Pulumi AWS provider registry - Provider resources and API references
- Pulumi stacks - Per-stack state and configuration
Conclusion
Pulumi lets teams write infrastructure programs in a language they already use, while still relying on resource providers, state, and reviewed updates. Its flexibility comes with runtime and dependency choices that the team has to pin and maintain.
For securing your infrastructure, see Cloud Security for IAM policies, encryption, and access controls. For monitoring infrastructure changes and drift detection, see Observability Engineering.
HCL may suit teams that prefer configuration files or already maintain Terraform/OpenTofu modules. Pulumi may suit teams that want language-level reuse. In either case, review the provider plan and protect the state backend; familiar syntax does not make infrastructure changes safe.
For more on infrastructure approaches, see our post on Cost Optimization and other IaC topics in this roadmap.
Category
Related Posts
Terraform: Declarative Infrastructure Provisioning
Learn Terraform from the ground up—state management, providers, modules, and production-ready patterns for managing cloud infrastructure as code.
AWS CDK v2: A Safe TypeScript Walkthrough
Build a small AWS CDK v2 stack in TypeScript, inspect its CloudFormation diff, bootstrap carefully, deploy with review, and clean it up safely.
IaC Module Design: Reusable and Composable Infrastructure
Design Terraform modules that are reusable, composable, and maintainable—versioning, documentation, and publish patterns for infrastructure building blocks.