
pulumi
Teach your agent Pulumi: infrastructure as code in TypeScript, Python, Go, C#, Java, YAML, or HCL. Skills for writing and operating cloud infrastructure, migrating from Terraform, CloudFormation, CDK, and ARM, and delegating work to Pulumi Neo, Pulumi's AI platform engineer.
- GitHub stars
- 80
Install
/plugin install pulumi@pulumi-agent-skillsRun it inside Claude Code after adding the marketplace with /plugin marketplace add pulumi/agent-skills.
Contents
Discovered from sourceSkills 17
Pulumi Neo Handoff
Transfer the current in-progress work to a new Pulumi Neo task. This is a one-way handoff: control passes to Neo and does not return to the calling agent.
Calling agent behavior
When this skill activates, act as a handoff coordinator, not the operator:
- Do not narrate the handoff turn-by-turn. The user has decided; carry it out quietly.
- Do not paste the assembled prompt body into chat. Show only the temp file path so the user can inspect on demand.
- Do not continue working on the task after launching. Exit cleanly once the task URL is returned.
What gets transferred
The Neo task receives a single opening prompt with three sections:
- Goal — one sentence describing what Neo should do next.
- Repository pointers — repo root, branch, working directory, working-tree state, and 3 to 5 files most relevant to the in-progress work.
- Conversation summary — a compact account of what has been discussed, decided, and left open.
Do not include diffs, full file contents, or tool output. Neo sees the local working tree directly (including uncommitted changes); duplicating that content wastes Neo's opening context.
Workflow
0. Preflight
Verify the CLI is available before drafting anything:
command -v pulumi >/dev/null || { echo "pulumi CLI not installed"; exit 1; }
pulumi neo --help >/dev/null 2>&1 || { echo "pulumi neo unavailable — run 'pulumi login' or upgrade the CLI"; exit 1; }
If preflight fails, surface the error to the user and stop. Do not assemble the prompt only to fail at launch.
1. Determine the goal
The goal is one sentence describing what Neo should do next. If the user's handoff message contains it ("hand this off to Neo and apply the staging migration"), use it directly. Otherwise ask once: "What would you like Neo to do next?"
Do not restate the goal back for confirmation — the handoff should feel seamless, and if Neo receives a misread goal the user can redirect inside the Neo task.
2. Gather repository context
Capture the canonical repo pointer and branch state:
git rev-parse --show-toplevel # repo root (canonical pointer)
git rev-parse --abbrev-ref HEAD # branch; returns "HEAD" if detached
git status --short # working-tree summary
If git rev-parse --show-toplevel fails the directory is not a git repo — omit the Repository section and note the working directory only. Neo can still operate, but its repo context will be limited.
If the branch reads HEAD, record the commit SHA and label the entry "detached at <sha>".
Identify 3 to 5 files most relevant to the in-progress work from the conversation (files read, edited, or repeatedly discussed). If the conversation does not clearly identify files, list none rather than guessing — wrong files mislead Neo more than missing files do.
3. Draft the conversation summary
Write a compact summary against the structure below. Sections with nothing useful to say should be omitted, not padded.
## What's been done
<bullets: decisions made, code changed, dead ends ruled out>
## Open questions
<bullets: things the user has not resolved>
## Next step
<one or two sentences describing what Neo should do first>
Target ~400 words for the summary. Compress aggressively. The goal is to give Neo enough to pick up cleanly, not to replay the conversation.
4. Assemble the prompt and write to a temp file
Combine the three sections into a single markdown document. Use mktemp for a portable temp path:
PROMPT_FILE="$(mktemp -t neo-handoff.XXXXXX.md)"
Shape:
# Goal
<one-sentence goal>
# Repository
- Root: <repo root>
- Branch: <branch or "detached at <sha>">
- Working directory: <cwd>
- Working tree: <clean | dirty>
- Files in play:
- <file 1>
- <file 2>
# Conversation summary
<summary from step 3>
5. Launch
Print the temp file path with a one-line size summary so the user can inspect on demand:
Prompt written to <PROMPT_FILE> (<line count> lines, <byte count> bytes).
Launching Neo task...
Invoke the CLI:
pulumi neo "$(cat "$PROMPT_FILE")"
pulumi neo accepts the prompt as a single positional argument; it has no --file flag, and stdin redirection launches the TUI instead of consuming the prompt. The "$(cat ...)" form captures the file's bytes as data (the shell does not re-evaluate $, backticks, or \ inside command substitution) and passes them as one argument. Do not "fix" this to pulumi neo --file ... or pulumi neo < ... — both forms are broken against the current CLI.
If the CLI exits non-zero, surface its stderr verbatim and leave the prompt file in place so the user can retry. Do not pretend the handoff succeeded.
6. Surface the task URL
The CLI prints a task URL on success. Echo it verbatim. Then stop.
What not to do
- Do not invoke this skill without explicit handoff intent. Detecting infrastructure-shaped work is not a trigger; capability questions like "can Neo do X" are not handoffs. Activating on those would make the skill noisy and incorrect.
- Do not include diffs, file contents, or command output in the prompt. Neo sees the local working tree directly, so duplicating that content wastes its opening context.
- Do not paste the assembled prompt into chat for confirmation. Summaries can be long; the file path is sufficient for the user to inspect when they care.
- Do not commit, push, or modify the working tree on the user's behalf. The user owns their git state — the skill is a context handoff, not a workflow controller.
Notes
- One-way handoff. Control passes to the Neo task and does not return to the calling agent.
- Neo tasks are interruptible. If the summary turns out to be wrong, the user can redirect inside the Neo task; the skill does not need to guard against summary errors at launch time.
- Surfacing the task URL is the skill's success criterion, not successful completion of the underlying work. Neo may decline or redirect the request inside the task.
IMPORTANT: PLAN ADJUSTMENT REQUIRED
If you have already generated a migration plan before loading this skill, you MUST:
- Review your existing plan against the workflows and requirements in this skill
- Identify any gaps, missing steps, or incorrect assumptions
- Update and revise your plan to align with this skill's guidance
- Communicate the adjusted plan to the user before proceeding
CRITICAL SUCCESS REQUIREMENTS
The migration output MUST meet all of the following:
-
Complete Resource Coverage
- Every CloudFormation resource MUST be represented in the Pulumi program OR explicitly justified in the final report.
-
CloudFormation Logical ID as Resource Name
- CRITICAL: Every Pulumi resource MUST use the CloudFormation Logical ID as its resource name.
- This enables the
cdk-importertool to automatically find import IDs. - DO NOT rename resources. Automated import will FAIL if you change the logical IDs.
-
Successful Deployment
- The produced Pulumi program must be structurally valid and capable of a successful
pulumi preview(assuming proper config).
- The produced Pulumi program must be structurally valid and capable of a successful
-
Zero-Diff Import Validation (if importing existing resources)
- After import,
pulumi previewmust show NO updates, replaces, creates, or deletes.
- After import,
-
Final Migration Report
- Always output a formal migration report suitable for a Pull Request.
WHEN INFORMATION IS MISSING
If the user has not provided a CloudFormation template, you MUST fetch it from AWS using the stack name.
MIGRATION WORKFLOW
Follow this workflow exactly and in this order:
1. INFORMATION GATHERING
1.1 Verify AWS Credentials (ESC)
Running AWS commands requires credentials loaded via Pulumi ESC.
- If the user has already provided an ESC environment, use it.
- If no ESC environment is specified, ask the user which ESC environment to use before proceeding.
For detailed ESC information: Use skill pulumi-esc.
You MUST confirm the AWS region with the user.
1.2 Get the CloudFormation Template
If user provided a template file: Read the template directly.
If user only provided a stack name: Fetch the template from AWS:
aws cloudformation get-template \
--region <region> \
--stack-name <stack-name> \
--query 'TemplateBody' \
--output json > template.json
1.3 Build Resource Inventory
List all resources in the stack:
aws cloudformation list-stack-resources \
--region <region> \
--stack-name <stack-name> \
--output json
This provides:
LogicalResourceId- Use this as the Pulumi resource namePhysicalResourceId- The actual AWS resource IDResourceType- The CloudFormation resource type
1.4 Analyze Template Structure
Extract from the template:
- Parameters and their defaults
- Mappings
- Conditions
- Outputs
- Resource dependencies (Ref, GetAtt, DependsOn)
2. CODE CONVERSION (CloudFormation → Pulumi)
IMPORTANT: There is NO automated conversion tool for CloudFormation. You MUST convert each resource manually.
2.1 Resource Name Convention (CRITICAL)
Every Pulumi resource MUST use the CloudFormation Logical ID as its name.
// CloudFormation:
// "MyAppBucketABC123": { "Type": "AWS::S3::Bucket", ... }
// Pulumi - CORRECT:
const myAppBucket = new aws.s3.Bucket("MyAppBucketABC123", { ... });
// Pulumi - WRONG (DO NOT do this - import will fail):
const myAppBucket = new aws.s3.Bucket("my-app-bucket", { ... });
This naming convention is REQUIRED because the cdk-importer tool matches resources by name.
2.2 Provider Strategy
⚠️ CRITICAL: ALWAYS USE aws-native BY DEFAULT ⚠️
- Use
aws-nativefor all resources unless there's a specific reason to useaws. - CloudFormation types map directly to aws-native (e.g.,
AWS::S3::Bucket→aws-native.s3.Bucket). - Only use
aws(classic) when aws-native doesn't support a required feature.
This is MANDATORY for successful imports with cdk-importer. The cdk-importer works by matching CloudFormation resources to Pulumi resources, and CloudFormation maps 1:1 to aws-native. Using the classic aws provider will cause import failures.
2.3 CloudFormation Intrinsic Functions
Map CloudFormation intrinsic functions to Pulumi equivalents:
| CloudFormation | Pulumi Equivalent |
|---|---|
!Ref (resource) | Resource output (e.g., bucket.id) |
!Ref (parameter) | Pulumi config |
!GetAtt Resource.Attr | Resource property output |
!Sub "..." | pulumi.interpolate |
!Join [delim, [...]] | pulumi.interpolate or .apply() |
!If [cond, true, false] | Ternary operator |
!Equals [a, b] | === comparison |
!Select [idx, list] | Array indexing with .apply() |
!Split [delim, str] | .apply(v => v.split(...)) |
Fn::ImportValue | Stack references or config |
Example: !Sub
// CloudFormation: !Sub "arn:aws:s3:::${MyBucket}/*"
// Pulumi:
const bucketArn = pulumi.interpolate`arn:aws:s3:::${myBucket.bucket}/*`;
Example: !GetAtt
// CloudFormation: !GetAtt MyFunction.Arn
// Pulumi:
const functionArn = myFunction.arn;
2.4 CloudFormation Conditions
Convert CloudFormation conditions to TypeScript logic:
// CloudFormation:
// "Conditions": {
// "CreateProdResources": { "Fn::Equals": [{ "Ref": "Environment" }, "prod"] }
// }
// Pulumi:
const config = new pulumi.Config();
const environment = config.require("environment");
const createProdResources = environment === "prod";
if (createProdResources) {
// Create production-only resources
}
2.5 CloudFormation Parameters
Convert parameters to Pulumi config:
// CloudFormation:
// "Parameters": {
// "InstanceType": { "Type": "String", "Default": "t3.micro" }
// }
// Pulumi:
const config = new pulumi.Config();
const instanceType = config.get("instanceType") || "t3.micro";
2.6 CloudFormation Mappings
Convert mappings to TypeScript objects:
// CloudFormation:
// "Mappings": {
// "RegionMap": {
// "us-east-1": { "AMI": "ami-12345" },
// "us-west-2": { "AMI": "ami-67890" }
// }
// }
// Pulumi:
const regionMap: Record<string, { ami: string }> = {
"us-east-1": { ami: "ami-12345" },
"us-west-2": { ami: "ami-67890" },
};
const ami = regionMap[aws.config.region!].ami;
2.7 Custom Resources
CloudFormation Custom Resources (AWS::CloudFormation::CustomResource or Custom::*) require special handling:
- Identify the purpose: Read the Lambda function code to understand what it does
- Find native replacement: Check if Pulumi has a native resource that provides the same functionality
- If no replacement: Document in the migration report that manual implementation is needed
2.8 TypeScript Output Handling
aws-native outputs often include undefined. Avoid ! non-null assertions. Always safely unwrap with .apply():
// WRONG
functionName: lambdaFunction.functionName!,
// CORRECT
functionName: lambdaFunction.functionName.apply(name => name || ""),
3. RESOURCE IMPORT
After conversion, import existing resources to be managed by Pulumi.
3.0 Pre-Import Validation (REQUIRED)
Before proceeding with import, verify your code:
- Check Provider Usage: Scan your code to ensure all resources use
aws-native - Document Exceptions: Any use of
aws(classic) provider must be justified - Verify Resource Names: Confirm all resources use CloudFormation Logical IDs as names
3.1 Automated Import with cdk-importer
Because you used CloudFormation Logical IDs as resource names, you can use the cdk-importer tool to automatically import resources.
Follow cfn-importer.md for detailed import procedures.
3.2 Manual Import for Failed Resources
For resources that fail automatic import:
- Follow cloudformation-id-lookup.md to find the import ID format
- Use
pulumi import:
pulumi import <pulumi-resource-type> <logical-id> <import-id>
3.3 Running Preview After Import
After import, run pulumi preview. There must be:
- NO updates
- NO replaces
- NO creates
- NO deletes
If there are changes, investigate and update the program until preview is clean.
OUTPUT FORMAT (REQUIRED)
When performing a migration, always produce:
- Overview (high-level description)
- Migration Plan Summary
- Pulumi Code Outputs (TypeScript; organized by file)
- Resource Mapping Table:
| CloudFormation Logical ID | CFN Type | Pulumi Type | Provider |
|---|---|---|---|
MyAppBucketABC123 | AWS::S3::Bucket | aws-native.s3.Bucket | aws-native |
MyLambdaFunction456 | AWS::Lambda::Function | aws-native.lambda.Function | aws-native |
- Custom Resources Summary (if any)
- Final Migration Report (PR-ready)
- Next Steps (import instructions)
FOR DETAILED DOCUMENTATION
Fetch content from official Pulumi documentation:
IMPORTANT: PLAN ADJUSTMENT REQUIRED
If you have already generated a migration plan before loading this skill, you MUST:
- Review your existing plan against the workflows and requirements in this skill
- Identify any gaps, missing steps, or incorrect assumptions
- Update and revise your plan to align with this skill's guidance
- Communicate the adjusted plan to the user before proceeding
CRITICAL SUCCESS REQUIREMENTS
The migration output MUST meet all of the following:
-
Complete Resource Coverage
- Every ARM template resource MUST:
- Be represented in the Pulumi program OR
- Be explicitly justified in the final report.
- Every ARM template resource MUST:
-
Successful Deployment
- The produced Pulumi program must be structurally valid and capable of a successful
pulumi preview(assuming proper config).
- The produced Pulumi program must be structurally valid and capable of a successful
-
Zero-Diff Import Validation (if importing existing resources)
- After import,
pulumi previewmust show:- NO updates
- NO replaces
- NO creates
- NO deletes
- Any diffs must be resolved using the Preview Resolution Workflow. See arm-import.md.
- After import,
-
Final Migration Report
- Always output a formal migration report suitable for a Pull Request.
- Include:
- ARM → Pulumi resource mapping
- Provider decisions (azure-native vs azure)
- Behavioral differences
- Missing or manually required steps
- Validation instructions
WHEN INFORMATION IS MISSING
If a user-provided ARM template is incomplete, ambiguous, or missing artifacts, ask targeted questions before generating Pulumi code.
If there is ambiguity on how to handle a specific resource property on import, ask targeted questions before altering Pulumi code.
MIGRATION WORKFLOW
Follow this workflow exactly and in this order:
1. INFORMATION GATHERING
1.1 Verify Azure Credentials
Running Azure CLI commands (e.g., az resource list, az resource show). Requires initial login using ESC and az login
- If the user has already provided an ESC environment, use it.
- If no ESC environment is specified, ask the user which ESC environment to use before proceeding with Azure CLI commands.
Setting up Azure CLI using ESC:
- ESC environments can provide Azure credentials through environment variables or Azure CLI configuration
- Login to Azure using ESC to provide credentials, e.g:
pulumi env run {org}/{project}/{environment} -- bash -c 'az login --service-principal -u "$ARM_CLIENT_ID" --tenant "$ARM_TENANT_ID" --federated-token "$ARM_OIDC_TOKEN"'. ESC is not required after establishing the session - Verify credentials are working:
az account show - Confirm subscription:
az account list --query "[].{Name:name, SubscriptionId:id, IsDefault:isDefault}" -o table
For detailed ESC information: Load the pulumi-esc skill by calling the tool "Skill" with name = "pulumi-esc"
1.2 Analyze ARM Template Structure
ARM templates do not have the concept of "stacks" like CloudFormation. Read the ARM template JSON file directly:
# View template structure
cat template.json | jq '.resources[] | {type: .type, name: .name}'
# View parameters
cat template.json | jq '.parameters'
# View variables
cat template.json | jq '.variables'
Extract:
- Resource types and names
- Parameters and their default values
- Variables and expressions
- Dependencies (dependsOn arrays)
- Nested templates or linked templates
- Copy loops (iteration constructs)
- Conditional deployments (condition property)
Documentation: ARM Template Structure
1.3 Build Resource Inventory (if importing existing resources)
If the ARM template has already been deployed and you're importing existing resources:
# List all resources in a resource group
az resource list \
--resource-group <resource-group-name> \
--output json
# Get specific resource details
az resource show \
--ids <resource-id> \
--output json
# Query specific properties using JMESPath
az resource show \
--ids <resource-id> \
--query "{name:name, location:location, properties:properties}" \
--output json
Documentation: Azure CLI Documentation
2. CODE CONVERSION (ARM → PULUMI)
IMPORTANT: ARM to Pulumi conversion requires manual translation. There is NO automated conversion tool for ARM templates. You are responsible for the complete conversion.
Key Conversion Principles
-
Provider Strategy:
- Default: Use
@pulumi/azure-nativefor full Azure Resource Manager API coverage - Fallback: Use
@pulumi/azure(classic provider) when azure-native doesn't support specific features or when you need simplified abstractions
Documentation:
- Default: Use
-
Language Support:
- TypeScript/JavaScript: Most common, excellent IDE support
- Python: Great for data teams and ML workflows
- C#: Natural fit for .NET teams
- Go: High performance, strong typing
- Java: Enterprise Java teams
- YAML: Simple declarative approach
- Choose based on user preference or existing codebase
-
Complete Coverage:
- Convert ALL resources in the ARM template
- Preserve all conditionals, loops, and dependencies
- Maintain parameter and variable logic
Follow conversion patterns in arm-conversion-patterns.md.
arm-conversion-patterns.md provides:
- Parameters, variables, and outputs mapping
- Copy loops, conditionals, and dependsOn translation
- Nested templates → ComponentResource
- Azure Classic provider examples (VNet, App Service)
- TypeScript output handling and common pitfalls
3. RESOURCE IMPORT (EXISTING RESOURCES) - OPTIONAL
After conversion, you can optionally import existing resources to be managed by Pulumi. If the user does not request this, suggest it as a follow-up step to conversion.
CRITICAL: When the user requests importing existing Azure resources into Pulumi, see arm-import.md for detailed import procedures and zero-diff validation workflows.
arm-import.md provides:
- Inline import ID patterns and examples
- Azure Resource ID format conventions
- Child resource handling (e.g., WebAppApplicationSettings)
- Preview Resolution Workflow for achieving zero-diff after import
- Step-by-step debugging for property conflicts
Key Import Principles
-
Inline Import Approach:
- Use
importresource option with Azure Resource IDs - No separate import tool (unlike
pulumi-cdk-importer)
- Use
-
Azure Resource IDs:
- Follow predictable pattern:
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - Can be generated by convention or queried via Azure CLI
- Follow predictable pattern:
-
Zero-Diff Validation:
- Run
pulumi previewafter import - Resolve all diffs using Preview Resolution Workflow
- Goal: NO updates, replaces, creates, or deletes
- Run
4. PULUMI CONFIGURATION
Set up stack configuration matching ARM template parameters:
# Set Azure region
pulumi config set azure-native:location eastus --stack dev
# Set application parameters
pulumi config set storageAccountName mystorageaccount --stack dev
# Set secret parameters
pulumi config set --secret adminPassword MyS3cr3tP@ssw0rd --stack dev
5. VALIDATION
After achieving zero diff in preview (if importing), validate the migration:
-
Review all exports:
pulumi stack output -
Verify resource relationships:
pulumi stack graph -
Test application functionality (if applicable)
-
Document any manual steps required post-migration
WORKING WITH THE USER
If the user asks for help planning or performing an ARM to Pulumi migration, use the information above to guide the user through the conversion and import process.
FOR DETAILED DOCUMENTATION
When the user wants additional information, use the web-fetch tool to get content from the official Pulumi documentation:
- ARM Migration Guide: https://www.pulumi.com/docs/iac/adopting-pulumi/migrating-to-pulumi/from-arm/
- Azure Native Provider: https://www.pulumi.com/registry/packages/azure-native/
- Azure Classic Provider: https://www.pulumi.com/registry/packages/azure/
Microsoft Azure Documentation:
- ARM Template Reference: https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/
- Azure CLI Reference: https://learn.microsoft.com/en-us/cli/azure/
- Azure Resource IDs: https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions-resource
OUTPUT FORMAT (REQUIRED)
When performing a migration, always produce:
- Overview (high-level description)
- Migration Plan Summary
- ARM template resources identified
- Conversion strategy (language, providers)
- Import approach (if applicable)
- Pulumi Code Outputs (organized by file)
- Main program file
- Component resources (if any)
- Configuration instructions
- Resource Mapping Table (ARM → Pulumi)
- ARM resource type → Pulumi resource type
- ARM resource name → Pulumi logical name
- Import ID (if importing)
- Preview Resolution Notes (if importing)
- Diffs encountered
- Resolution strategy applied
- Properties ignored vs. added
- Final Migration Report (PR-ready)
- Summary of changes
- Testing instructions
- Known limitations
- Next steps
- Configuration Setup
- Required config values
- Example
pulumi config setcommands
Keep code syntactically valid and clearly separated by files.
CRITICAL SUCCESS REQUIREMENTS
The migration output MUST meet all of the following:
-
Complete Resource Coverage
- Every CloudFormation resource synthesized by CDK MUST:
- Be represented in the Pulumi program OR
- Be explicitly justified in the final report.
- Every CloudFormation resource synthesized by CDK MUST:
-
Successful Deployment
- The produced Pulumi program must be structurally valid and capable of a successful
pulumi up(assuming proper config).
- The produced Pulumi program must be structurally valid and capable of a successful
-
Final Migration Report
- Always output a formal migration report suitable for a Pull Request.
- Include:
- CDK → Pulumi resource mapping
- Provider decisions (aws-native vs aws)
- Behavioral differences
- Missing or manually required steps
- Validation instructions
WHEN INFORMATION IS MISSING
If a user-provided CDK project is incomplete, ambiguous, or missing artifacts (such as cdk.out), ask targeted questions before generating Pulumi code.
MIGRATION WORKFLOW
Follow this workflow exactly and in this order:
1. INFORMATION GATHERING
1.1 Verify AWS Credentials (ESC)
Running AWS commands (e.g., aws cloudformation list-stack-resources) and CDK commands (e.g. cdk synth) requires credentials loaded via Pulumi ESC.
- If the user has already provided an ESC environment, use it.
- If no ESC environment is specified, ask the user which ESC environment to use before proceeding with AWS commands.
You MUST confirm the AWS region with the user. The cdk synth results may be incorrect if ran with the wrong AWS Region.
1.2 Synthesize CDK
Run/inspect:
npx cdk synth --quiet
- ALWAYS run
synthwith--quietto prevent the template from being output on stdout.
If failing, inspect cdk.json or package.json for custom synth behavior.
1.3 Identify CDK Stacks & Environments
Read cdk.out/manifest.json:
jq '.artifacts | to_entries | map(select(.value.type == "aws:cloudformation:stack") | {displayName: .key, environment: .value.environment}) | .[]' cdk.out/manifest.json
Example output:
{
"displayName": "DataStack-dev",
"environment": "aws://616138583583/us-east-2"
}
{
"displayName": "AppStack-dev",
"environment": "aws://616138583583/us-east-2"
}
In the Pulumi stack you create you MUST set both the aws:region and aws-native:region config variables. For example:
pulumi config set aws-native:region us-east-2 --stack dev
pulumi config set aws:region us-east-2 --stack dev
1.4 Build Resource Inventory
For each stack:
aws cloudformation list-stack-resources \
--region <region> \
--stack-name <stack> \
--output json
1.5 Analyze CDK Structure
Extract:
- Environment-specific conditionals
- Stack dependencies & cross-stack references
- Runtime config (context/env vars)
- Construct types (L1, L2, L3)
2. CODE CONVERSION (CDK → PULUMI)
- Perform the initial conversion using the
cdk2pulumitool. Follow cdk-convert.md to perform the conversion. - Read the conversion report and fill in any gaps. For example, if the conversion fails to convert a resource you have to convert it manually yourself.
2.1 Custom Resources Handling
CDK uses Lambda-backed Custom Resources for functionality not available in CloudFormation. In synthesized CloudFormation, these appear as:
- Resource type:
AWS::CloudFormation::CustomResourceorCustom::<name> - Metadata contains
aws:cdk:pathwith the handler name (e.g.,aws-s3/auto-delete-objects-handler)
Default behavior: cdk2pulumi rewrites custom resources to aws-native:cloudformation:CustomResourceEmulator, which invokes the original Lambda. This works but has tradeoffs (Lambda dependency, cold starts, eventual consistency).
Migration strategies by handler type:
| Handler | Strategy |
|---|---|
aws-certificatemanager/dns-validated-certificate-handler | Replace with aws.acm.Certificate, aws.route53.Record, and aws.acm.CertificateValidation |
aws-ec2/restrict-default-security-group-handler | Replace with aws.ec2.DefaultSecurityGroup resource with empty ingress/egress rules |
aws-ecr/auto-delete-images-handler | Replace aws-native:ecr:Repository with aws.ecr.Repository with forceDelete: true |
aws-s3/auto-delete-objects-handler | Replace aws-native:s3:Bucket with aws.s3.Bucket with forceDestroy: true |
aws-s3/notifications-resource-handler | Replace with aws.s3.BucketNotification |
aws-logs/log-retention-handler | Replace with aws.cloudwatch.LogGroup with explicit retentionInDays |
aws-iam/oidc-handler | Replace with aws.iam.OpenIdConnectProvider |
aws-route53/delete-existing-record-set-handler | Replace with aws.route53.Record with allowOverwrite: true |
aws-dynamodb/replica-handler | Replace with aws.dynamodb.TableReplica |
Cross-account/region handlers:
aws-cloudfront/edge-function→ Useaws.lambda.Functionwithregion: "us-east-1"aws-route53/cross-account-zone-delegation-handler→ Use separate aws provider with cross-account role assumption
Graceful degradation for unknown handlers:
- Keep the
CustomResourceEmulator(default behavior) - Document the custom resource in the migration report with:
- Original handler name and purpose (if discernible from CDK path)
- Note that it uses Lambda invocation at runtime
- Recommend user review for potential native replacement
2.2 Provider Strategy
- Default: Use
aws-nativewhenever the resource type is available. - Fallback: Use
awswhen aws-native does not support equivalent features.
2.3 Assets & Bundling
CDK uses Assets and Bundling to handle deployment artifacts. These are processed by the CDK CLI before CloudFormation deployment and appear in the cdk.out directory alongside *.assets.json metadata files. CloudFormation templates contain hard-coded references to asset locations (S3 bucket/key or ECR repo/tag).
# Inspect asset definitions
jq '.files, .dockerImages' cdk.out/*.assets.json
Migration strategies by asset type:
| Asset Type | Detection | Pulumi Migration |
|---|---|---|
| Docker Image | dockerImages in assets.json | Use docker-build.Image to build and push. Replace hard-coded ECR URI with image output. |
| File with build command | files with executable field | Flag to user - build command needs setup in Pulumi |
| Static file | files without executable, no bundling in CDK source | Use pulumi.FileArchive or pulumi.FileAsset |
| Bundled file | files without executable, but CDK source uses bundling | Flag to user - bundling needs setup in Pulumi |
Detecting Bundling in CDK Source:
Check the CDK source code for bundling constructs (NodejsFunction, PythonFunction, GoFunction, or resources using the bundling option). If bundling is used, the build step needs to be replicated in Pulumi for ongoing development - otherwise source changes would require manually re-running cdk synth.
When bundling is detected, inform the user:
Build Step Detected: This CDK application uses <BUNDLING_TYPE> which builds deployable artifacts during synthesis. This build step needs to be replicated in Pulumi for ongoing development.
Options:
- CI/CD Pipeline (Recommended): Move the build step to your CI pipeline and reference the pre-built artifact in Pulumi
- Pulumi Command Provider: Use
command.local.Commandto run the build command duringpulumi up- Pre-build Script: Create a build script that runs before
pulumi upand outputs to a known locationEach option has tradeoffs around caching, reproducibility, and deployment speed. For production workloads, option 1 is typically preferred.
2.4 TypeScript Handling for aws-native
aws-native outputs often include undefined. Avoid ! non-null assertions. Always safely unwrap with .apply():
// ❌ WRONG - Will cause TypeScript errors
functionName: lambdaFunction.functionName!,
// ✅ CORRECT - Handle undefined safely
functionName: lambdaFunction.functionName.apply(name => name || ""),
2.5 Environment Logic Preservation
Carry forward all conditional behaviors:
if (currentEnv.createVpc) {
// create resources
} else {
const vpcId = pulumi.output(currentEnv.vpcId);
}
3. Resource Import (optional)
After conversion you can optionally import the existing resources to now be managed by Pulumi. If the user does not request this you should suggest this as a follow up step to conversion.
- Always start with automated import using the
cdk-importertool. Follow cdk-importer.md to perform the automated import. - For any resources that fail to import with the automated tool, import them manually.
If you need to manually import resources:
-
Follow cloudformation-id-lookup.md to look up CloudFormation import identifiers.
-
Use the web-fetch tool to get content from the official Pulumi documentation.
-
Finding AWS import IDs -> https://www.pulumi.com/docs/iac/guides/migration/aws-import-ids/
-
Manual migration approaches -> https://www.pulumi.com/docs/iac/guides/migration/migrating-to-pulumi/migrating-from-cdk/migrating-existing-cdk-app/#approach-b-manual-migration
3.1 Running preview after import
After performing an import you need to run pulumi preview to ensure there are no changes. No changes means:
- NO updates
- NO replaces
- NO creates
- NO deletes
If there are changes you must investigate and update the program until there are no changes.
Working with the User
If the user asks for help planning or performing a CDK to Pulumi migration use the information above to guide the user towards the automated migration approach.
For Detailed Documentation
When the user wants to deviate from the recommended path detailed above, use the web-fetch tool to get content from the official Pulumi documentation -> https://www.pulumi.com/docs/iac/guides/migration/migrating-to-pulumi/migrating-from-cdk/migrating-existing-cdk-app
This documentation covers topics:
- Migration Strategy
- Convert vs. Rewrite
- Import vs. Rehydrate
- Best Practices
- Handling Multiple CDK Stacks
- Handling CDK Stages
- Code organization
- Converting CDK Constructs
- Execution Strategies
- Automated Migration (recommended)
- Manual Migration
OUTPUT FORMAT (REQUIRED)
When performing a migration, always produce:
- Overview (high-level description)
- Migration Plan Summary
- Pulumi Code Outputs (TypeScript; structured by file)
- Resource Mapping Table (CDK → Pulumi)
- Custom Resources Summary (if any):
- Handlers migrated to native Pulumi resources
- Handlers kept as
CustomResourceEmulatorwith rationale - Any handlers requiring user attention
- Assets & Bundling Summary (if any):
- Migrated: Assets successfully converted (e.g., Docker images →
docker-build.Image, static files →pulumi.FileArchive) - Requires attention: Assets with bundling steps, options presented, and decision if made
- Migrated: Assets successfully converted (e.g., Docker images →
- Final Migration Report (PR-ready)
- Next Steps (optional refactors)
Keep code syntactically valid and clearly separated by files.
Scope: this skill only applies to stacks Pulumi Cloud's Discovery feature has already scanned and exposed through the discovered-stacks API (GET .../discovered-stacks/{projectName}/{stackName}/resources, see below). It is not for migrating an arbitrary CloudFormation/ARM template or account that Discovery hasn't scanned yet — if no discovered stack exists for the source, this skill has nothing to read and does not apply.
Do not load
cloudformation-to-pulumiorpulumi-arm-to-pulumialongside this skill. Those two skills prescribe a template-first workflow (mechanical translation → import) and mandateaws-nativefor AWS. This skill is cloud-state-first (import from discovered state → optional refactor against the template later) and defaults toawsclassic /azure-native. The useful reference material from those two skills has been curated intocloudformation.mdandarm.mdin this folder.
Plan adjustment
If you already generated a migration plan before loading this skill, review it against the workflow below and update it — the phases here supersede any earlier plan. Communicate the adjusted plan to the user before proceeding.
Success criteria
A migration is complete when:
- Complete resource coverage — every discovered resource is imported OR has an annotation explaining why not.
- Zero-diff —
pulumi previewshows no changes. This proves the code matches the cloud state exactly. - Progress tracked via the API — use
compareToand migration annotations so progress is visible in Pulumi Cloud, not just in agent memory. - PR as the output — a pull request with the migrated code and a migration report.
THE DISCOVERED-STACKS API
Fetching resources
GET /api/preview/insights/{orgName}/discovered-stacks/{projectName}/{stackName}/resources?compareTo={targetProject}/{targetStack}
Always include compareTo if the target Pulumi stack exists (it may already have state from a previous migration attempt). Returns a list of DiscoveredResourceInfo objects. The JSON paths below are exact — verify before consuming:
name— top-level: logical name (CF Logical ID / ARM resource name). Use this as the Pulumi resource name.originType— top-level: native cloud type (e.g.AWS::S3::Bucket,Microsoft.Storage/storageAccounts)providerType— top-level: mapped Pulumi type token (e.g.aws:s3/bucket:Bucket).nullif unmapped.resource.inputs.providerId— physical cloud ID forpulumi import.resource.urn— the URN to use asresourceUrnin annotation requests (copy verbatim).migrationStatus— top-level: one of the statuses below.annotation— top-level: user/agent annotation if one exists (see Annotations below).
The resource.inputs object also carries raw cloud-provider data:
For CloudFormation — resource.inputs.cloudFormation:
physicalResourceId— the original CF physical IDresourceType— the CF type (e.g.AWS::IAM::Role)resourceStatus— e.g.CREATE_COMPLETE,DELETE_COMPLETEdriftStatus—NOT_CHECKED,IN_SYNC,DRIFTED
For CDK-synthesized CF stacks, inputs.cdkPath is also present — see cloudformation.md §5 for how to use it.
For ARM — resource.inputs.arm. ARM resources are grouped by resource group, not by
deployment, so a resource with no deployment currently backing it (its deployment history
aged out of Azure's retention window, or it was created outside any tracked deployment) is
still returned — just as a placeholder, with resource.inputs.deploymentName empty and a
different arm shape:
- Deployment-backed (
resource.inputs.deploymentNamenon-empty) —armis a deployment-operation object:properties.targetResource.id/.resourceType/.resourceName,properties.provisioningState(e.g.Succeeded). - Placeholder (
resource.inputs.deploymentNameempty) —armis the raw Azure generic-resource object instead: top-levelid,name,type,location,tags. Noproperties.targetResource— don't look for it.
Either way, prefer the top-level resource.inputs.providerId for the import ID (see
above) rather than reaching into arm — it's already normalized across both shapes.
Migration statuses
Statuses are PascalCase. First match wins:
Migrated— the resource was found in thecompareToPulumi stack. Already under Pulumi management; skip.Ready—providerTypeandproviderIdare set and the scanner confirmed the resource exists. Import withpulumi import <providerType> <name> <providerId> --generate-code --out <file>.ts(NEVER without--generate-code --out— see Phase 4).NotFound—providerTypeandproviderIdare set, but the scanner could not confirm the resource's current state. May be deleted, mapping may be imperfect, or scanner hit a gap. Verify before importing.NotApplicable— container or wrapper types (AWS::CloudFormation::Stack,Microsoft.Resources/deployments,Microsoft.Resources/resourceGroups,pulumi:providers:*) are not individually migratable. Skip silently.NoMatch—providerTypeisnull. No mapping found. Common examples:- CF Custom Resources (e.g.
Custom::VpcRestrictDefaultSG) — no direct Pulumi equivalent. - Inline policies —
AWS::IAM::Policymodeled as an inline property ofaws:iam/role:Role. Once the parent Role is migrated, annotate the policy as migrated.
- CF Custom Resources (e.g.
PulumiOnly— exists in thecompareTostack with no discovered counterpart, or those created to migrate NoMatch resources. Surface to user.
Resources with annotation.statusOverride should be treated as resolved per the override, even if the computed status disagrees.
Annotations
PUT /api/preview/insights/{orgName}/discovered-stacks/{projectName}/{stackName}/migration
DELETE /api/preview/insights/{orgName}/discovered-stacks/{projectName}/{stackName}/migration?resourceUrn={urn}
PUT body:
{
"resourceUrn": "<copy verbatim from resource.urn in the list response>",
"note": "explanation of what happened",
"statusOverride": "Migrated" | "",
"linkedResourceUrn": "<optional: URN of the Pulumi resource paired 1:1 with this origin>"
}
Use the Pulumi Cloud API for all annotation requests. At least one of note or statusOverride must be non-empty. Omit statusOverride entirely (do not send null) when updating only the note. The DELETE endpoint clears both the note and any statusOverride.
Use annotations to:
- Flag deleted resources as
Migratedwith a note explaining they no longer exist - Flag inline/child resources covered by a parent's migration as
Migratedwith a note naming the parent — do not uselinkedResourceUrnhere (it's a 1:many relationship and the UI only merges 1:1 pairs) - Bridge a
NotFoundorNoMatchorigin to itsPulumiOnlycounterpart after a corrected mapping (statusOverride=Migrated+linkedResourceUrn→ the PulumiOnly URN). This is the only valid use oflinkedResourceUrn. - Leave notes explaining blockers or manual steps taken
- Track decisions for resources the automatic classifier can't resolve
The annotation endpoint is the shared place to track migration progress — always read existing annotations before acting on a resource, and respect overrides left by the user.
The note field is user-authored context. Treat it as a high-priority instruction about that specific resource. Common uses: naming preferences, import ID hints, resources to skip, or special handling instructions. Notes reach the agent through two channels:
-
Starting prompt — when the user kicks off a migration task, any note on a selected resource is appended to that resource's line:
- aws:s3/bucket:Bucket "my-bucket" (provider ID: my-bucket-prod) — note: use logical name "appBucket" in codeRead these before calling the API.
-
API response — the
annotation.notefield on eachDiscoveredResourceInfowhen you callGET .../resources. Theannotationobject is omitted entirely when no annotation has been set.
MIGRATION WORKFLOW
Phase 0 — Preconditions and scoping
Before any tool call, gather and confirm all of the following. If anything is missing, ask — don't proceed with a guess.
Source (the discovered stack):
- Org name (e.g.
pulumi_local) - Discovered project name (e.g.
AcmeCdkExampleStack) - Discovered stack name (e.g.
dev-sandbox-disc_us-west-2__Dev) — this is the scanner-generated name, usually encoding account + region + CF/ARM stack name. - Region (confirm even if the stack name suggests it).
Target (where the Pulumi code and state will live):
- Target git repo URL — ask the user. All work happens inside this repo from the start.
- Subfolder (optional) — ask if the user has a preference; default to repo root.
- Target project + stack names — ask the user, don't invent. If the stack already exists, use
compareToin Phase 1; if not, create it in Phase 2. - Target language — TypeScript default.
Refactor preferences (for Phase 7):
- Does the user have the original source code (CDK repo, Bicep project, Terraform modules)? If yes, path or URL. This is the primary structural reference for Phase 7 — the refactored Pulumi code will draw on its component boundaries, file layout, and naming conventions as a guide, adapted to what the import model actually produced.
- Does the user have a preferred program layout for the Pulumi output? (e.g. "one file per service", "match my existing repo shape", "I don't care")
- Does the user want Phase 7 at all, or stop after zero-diff (Phase 6)?
Credentials:
- ESC environment for cloud credentials (ask if not given; never invent). ESC is preferred — see
cloudformation.md §1orarm.md §1.
Don't start Phase 1 until all of the above are confirmed. Summarize the plan back to the user and wait for approval.
Phase 1 — Resource fetch and triage
Start here every time, even when resuming an existing migration. The API + any existing annotations are the source of truth for what's been done so far. If the target repo already has Pulumi code, read it — it tells you the conventions, existing resources, and how far a previous attempt got.
- Fetch discovered resources:
GET .../discovered-stacks/{projectName}/{stackName}/resources.- Target stack exists (resumed migration): append
?compareTo=<targetProject>/<targetStack>. - Target stack does not exist (greenfield): omit
compareTo— the API returns 404 if the target stack isn't found. After Phase 2 creates the stack, subsequent calls can include it.
- Target stack exists (resumed migration): append
- Save the response to disk —
./.migration/resources-baseline.json. - Run triage:
python3 <skill-base-dir>/scripts/triage.py .migration/resources-baseline.json— prints status counts (accounting for annotation overrides) and a per-resource table. - Present the plan to the user:
"Found N resources. A already Migrated, M Ready, K NotFound, J NoMatch, L non-migratable containers. I'll import Ready first, then verify NotFound, then triage NoMatch with you. Sound good?"
Get confirmation before writing any code.
Phase 2 — Target repo and Pulumi stack setup
- Clone the target git repo (from Phase 0) and work inside it for all subsequent phases. If the repo already has code, read it to understand existing conventions and resources before adding new ones.
- If the target stack already exists (Phase 0 check), select it. Otherwise:
- Create the Pulumi project:
pulumi new <language> --name <project> --stack <org>/<project>/<stack> --yes.
- Create the Pulumi project:
- Set provider config:
pulumi config set aws:region <r>(orazure-native:location). - Link the ESC environment if provided.
No empty pulumi up needed.
Concrete commands for project + stack setup, region config, and provider install:
cloudformation.md §2orarm.md §2.
Phase 3 — Build the import file
Generate the import file: python3 <skill-base-dir>/scripts/build_import.py .migration/resources-baseline.json .migration/import.json. This filters Ready/NotFound resources (excluding already-annotated ones) and maps API fields to the Pulumi import format (type ← providerType, name ← name, id ← resource.inputs.providerId).
Phase 4 — Import
Using the import.json from Phase 3.
Always use --generate-code --out — without it, resources land in state with no code, breaking pulumi preview.
pulumi import --file import.json --generate-code --out batch.<ext>
# then: append generated code into the main program file and delete the batch file
Per-batch loop: import → preview → commit → annotate. Aim for ~20 resources per batch. For CDK stacks, batch by cdkPath top-level group; otherwise batch by resource type prefix.
- Import the batch.
pulumi preview— zero diff required. Fix any diffs before moving on.- Commit the program changes to a branch.
- Annotate each imported resource —
PUT .../migrationwith note and nostatusOverride. Annotations survive context resets and are visible in the UI.
?compareTo is a live progress signal — pulumi import writes state immediately, so migrationStatus flips to Migrated after each import. Do not run pulumi up (see Phase 6).
Reserve statusOverride for cases where the computed status will be wrong:
statusOverride=Migrated(withlinkedResourceUrn) — resource covered by another (inline IAM policy → parent Role, IGW attachment → IGW, etc.).statusOverride=Migrated(with a note, nolinkedResourceUrn) — resource is deleted, dangling, or has no Pulumi equivalent. Flag it resolved so it drops out of the outstanding work.
Phase 5 — NotFound and NoMatch triage
Default strategy: try first, annotate second. For both NotFound and corrected-mapping cases, attempting pulumi import is the fastest way to learn what's actually wrong. The error messages are precise and actionable.
NotFound (providerType set, state unconfirmed):
Common outcomes:
-
Resource is deleted.
pulumi importreturnsPreview failed: resource '<id>' does not exist. AnnotatestatusOverride=Migratedwith the literal error in the note. Don't retry. In practice, a substantial share of NotFound resources turn out to be deleted rather than a mapping error. -
Wrong
providerTypemapping. Import fails with a type-validation error or schema mismatch. Several CF types have multiple valid Pulumi mappings (VPC gateway attachment / VPN vs IGW; S3 vs s3control; RDS instance vs cluster instance; SES v2 vs v1; etc.) — our scanner picks a primary that doesn't always match your resource. Look up theoriginTypeincloudformation.md §7, overrideproviderTypein the import file, retry. Then handle the fingerprint side-effect (next bullet). -
Wrong-mapping side-effect: PulumiOnly appears. When the agent imports with a corrected
providerType, fingerprint matching against the discovered resource fails. The discovered resource staysNotFound(orNoMatch) and a newPulumiOnlyentry appears. Annotate the original origin row asstatusOverride=MigratedwithlinkedResourceUrnpointing to the PulumiOnly URN. This bridges them in the UI and keeps the bookkeeping clean. -
Resource is alive and mapping is correct. Import succeeds. Status flips to
Migratedautomatically.
NoMatch (providerType is null):
Common patterns:
-
Inline IAM policies.
AWS::IAM::Policywhose name matches a migrated Role's prefix is an inline policy already captured asinlinePolicieson the Role's import. AnnotatestatusOverride=Migratedwith note:"inline policy of <RoleName>". -
AWS::SecretsManager::SecretTargetAttachment has no direct Pulumi mapping. The link between secret and target (RDS cluster, etc.) is implicit via the cluster's credentials config. Annotate
statusOverride=Migratedwith a note explaining the implicit link. -
CDK Custom Resources (
Custom::*). Typically a Lambda handler doing the actual work. Checkcloudformation.md §5for known handler → Pulumi replacement mappings. Don't annotateMigratedwithout confirming with the user — surface what the handler does and let them decide. -
Other NoMatch types. Look up the
originTypein the cloud provider docs (CF resource type reference or ARM resource type reference) to understand what the resource is, then search the Pulumi registry for a matching provider type. If the mapping is ambiguous, surface to the user and ask.
Pre-existing PulumiOnly entries. Beyond the corrected-mapping artifacts above, PulumiOnly also covers resources already in the target stack that aren't part of this migration. Leave those as-is — no annotation needed.
For cloud-specific lookup commands (verifying resources exist, finding import IDs, querying the cloud), provider-choice rules (
awsclassic vsaws-native,azure-nativevsazure), the Preview Resolution Workflow, and known import quirks, seecloudformation.md §3–§6orarm.md §3–§6.
Phase 6 — Reconciliation & PR
-
Run
pulumi preview— confirm there are NO changes. Any diff means the generated code doesn't match the imported state. Diffs come in three shapes:- Removed (
-) — a field the cloud has but your code doesn't set. Add it to the code with the real cloud value. Don'tignoreChanges. - Added (
+) — a field your code sets that the provider didn't return. If computed/read-only →ignoreChanges. If a provider default re-statement → remove from code. - Changed (
~) — value mismatch. Query the cloud, determine the correct value, update code. Never silence withignoreChanges.
Expect 2–5 preview rounds for complex resources. Never run
pulumi upto resolve diffs — that modifies the cloud, not the code. Seecloudformation.md §6orarm.md §6for cloud-specific diff patterns. - Removed (
-
Do one final
GET resources?compareTo=...and verify the expected distribution (this reflects the current backend state —migrationStatusis already up-to-date since everypulumi importwrites state):Migrated— all imported resourcesPulumiOnly— Pulumi-only resources, including any corrected-mapping imports linked via annotationNoMatchremaining — every one should have an annotationNotApplicable(containers) — silently skipped
-
Proceed to Phase 7 (refactor offer) before opening the PR.
The migration is functionally complete when preview is clean and the API triage shows no unresolved resources. Do not run pulumi up. The imported state is already synced to Pulumi Cloud via pulumi import; there's nothing for pulumi up to do that serves the migration.
Phase 7 — Refactor and maintainability review (before the PR)
Zero-diff is achieved, but the imported code is "flat" — hardcoded values, no cross-resource references, all resources at the top level. Before opening the PR, offer the user a readability refactor.
7a — Offer and orient
If Phase 0 didn't capture explicit refactor preferences, or the user hasn't explicitly declined, ask now:
"Preview is clean and all resources are accounted for. Before I open the PR, I'd like to refactor the code for maintainability — replacing any hardcoding with cross-resource references, extracting config parameters, and grouping related resources. (If you gave me a source repo, I'll use it as the structural blueprint, matching the intended file layout and component names.) Want me to go ahead?"
If they decline, skip to Phase 8.
7b — Implement the refactor
Read refactor.md for strategies, invariants, and template-reading references. Key priorities in order:
- Take structural cues from the source repo first — if the user provided a source repo, read it now (clone or use the local path from Phase 0). Use its file layout, component/module boundaries, and naming conventions as a guide. Where a group of resources maps naturally to a class, module, or subdirectory in the source and that grouping still feels natural for the imported Pulumi program, mirror that structure; otherwise avoid forcing artificial groupings just to match the source mechanically.
- Replace literal ARN/ID references with cross-resource output references.
- Extract config parameters (region, account ID, environment tag).
- Consolidate into
ComponentResourceclasses where the source repo or CDK paths suggest a natural grouping. - Split into files only last — and only when a natural isle warrants it.
Run pulumi preview after every non-trivial change. Zero-diff must hold throughout. If preview shows a diff, revert that single change before trying anything else — see refactor.md § The invariant for recovery steps.
7c — User walkthrough and maintainability sign-off
After the refactor, present the result to the user before opening the PR:
- Show a summary of what changed: files created/renamed, components introduced, literals replaced, config keys added.
- Walk through the top-level
index.ts(or equivalent) line by line if it's under ~80 lines; otherwise describe the module breakdown. - Highlight any judgment calls (e.g. "I grouped the IAM resources into
iam.tsto match thelib/iam/directory in your source repo — let me know if you'd prefer a different name"). - Ask explicitly: "Does this structure match how you'd expect to maintain this code?" Wait for the user's answer. If they request changes, make them (always preview after) and repeat the walkthrough until they're satisfied.
Only proceed to Phase 8 once the user confirms the structure is acceptable.
Phase 8 — PR and migration report
Produce the migration report (see below) and open the PR. The PR includes whatever state the code is in — raw imported code (if the user skipped Phase 7) or the refactored version (if they opted in).
MIGRATION REPORT FORMAT
Include in the PR description:
- Overview — source discovered stack → target Pulumi stack, region, language.
- Triage summary — counts by status at start and end.
- Resource mapping table — name, origin type, provider type, status, notes.
- Gaps — unmapped resources and why, with annotations.
- Progress URL — link to the discovered-stacks comparison endpoint for ongoing tracking.
- Next steps — pending user decisions, optional refactoring.
Migrating from Terraform to Pulumi
Critical constraints — read before acting:
- Do NOT run
pulumi convert— use the terraform-migrate plugin instead, which preserves state mapping.- Do NOT run
pulumi package add terraform-module— this is for a different workflow.- Do NOT create the Pulumi project under
/workspace— create it inside the checked-out repo.- Replace
${terraform_dir}and${pulumi_dir}below with the actual paths confirmed with the user.
First establish scope and plan the migration by working out with the user:
- where the Terraform sources are (
${terraform_dir}) - where the migrated Pulumi project lives (
${pulumi_dir}) - what is the target Pulumi language (such as TypeScript, Python, YAML)
- whether migration aims to setup Pulumi stack states, or only translate source code
Confirm the plan with the user before proceeding.
Create a new Pulumi project in ${pulumi_dir} in the chosen language. Edit sources to be empty and not declare any
resources. Ensure a Pulumi stack exists.
You must run pulumi_up tool before proceeding to ensure initial stack state is written.
If no local .tfstate file exists in ${terraform_dir}, the state may be in a remote backend (S3, Pulumi Cloud, Terraform Cloud, etc.). Pull it before proceeding:
cd ${terraform_dir} && terraform state pull > terraform.tfstate
This works for all backends, including Pulumi Cloud. If terraform is not available, try tofu state pull instead.
Now produce a draft Pulumi state translation:
pulumi plugin run terraform-migrate -- stack \
--from ${terraform_dir} \
--to ${pulumi_dir} \
--out /tmp/pulumi-state.json \
--plugins /tmp/required-providers.json
Do NOT install the plugin as it will auto-install as needed.
Sometimes terraform-migrate plugin fails because tofu refresh is not authorized. DO NOT skip this step. Work with the
user to find or build a Pulumi ESC environment that provides the necessary credentials so the command can succeed. If setting up an ESC environment is not feasible, inform the user that the migration cannot proceed automatically.
Read the generated /tmp/required-providers.json and install all these Pulumi providers into the new project,
respecting the suggested versions even if they downgrade an already installed provider. The file will contain records
such as [{"name":"aws","version":"7.12.0"}].
Install providers as project dependencies using the language-specific package manager (NOT pulumi plugin install,
which only downloads plugins without adding dependencies):
# TypeScript/JavaScript
npm install @pulumi/aws@7.12.0
# Python
pip install pulumi_aws==7.12.0
# Go
go get github.com/pulumi/pulumi-aws/sdk/v7@v7.12.0
# C#
dotnet add package Pulumi.Aws --version 7.12.0
Import the translated state draft (/tmp/pulumi-state.json) into the Pulumi stack:
pulumi stack import --file /tmp/pulumi-state.json
Translate source code to match both the Terraform source and the translated state. Aim for exact match. You can consult
the state draft /tmp/pulumi-state.json for Pulumi resource types and names to use.
Iterate on fixing the source code until pulumi_preview tool confirms that there are no changes to make and the diff
is empty or almost empty. Provider diffs or diffs on tags may be OK.
Offer the user to link an ESC environment to the stack so that each Pulumi stack can seamlessly have access to the provider credentials it needs.
When all looks good, create a Pull Request with the migrated source code.
API Reference
Query the Pulumi Cloud API with the pulumi api CLI subcommand. It authenticates with your existing Pulumi credentials and returns JSON.
Get the latest version of a package
pulumi api /api/registry/packages -F name={package_name} -F orgLogin={orgName}
Include orgLogin with the user's organization name. Omit -F name=... to list all packages visible to the organization (useful when the user has not named a specific package). The response contains a packages array. Each entry has a version field (the latest version), plus name, publisher, source, and packageStatus.
Get stack usage for a package
pulumi api /api/orgs/{orgName}/packages/usage -F packageName={package_name}
Replace {orgName} with the org name from context, PULUMI_ORG, or ask the user. packageName is required; query one package at a time.
Response fields:
packageName: The queried packagestacks: Array of{stackName, projectName, version, lastUpdate}totalStacks: Total count
Workflow: Find outdated stacks
Use when the user wants to know which stacks are using an outdated version of a package.
- Get the latest version of the package
- Get stack usage for the package
- Compare each stack's
versionagainst the latest to identify outdated stacks - Present results using the output format below
Output Format
Present results as a markdown table followed by a summary line:
| Project | Stack | Current Version | Latest Version | Status |
|---------|-------|-----------------|----------------|--------|
| my-app | dev | 6.40.0 | 6.52.0 | Outdated |
| my-app | prod | 6.52.0 | 6.52.0 | Up-to-date |
2 of 2 stacks checked. 1 outdated.
Out of scope: upgrading a specific stack
This skill identifies outdated stacks. It does not perform the upgrade itself. For actually bumping a package version in a project — editing package.json, requirements.txt, pyproject.toml, go.mod, or Pulumi.yaml, running pulumi preview, and reconciling the diff — hand off to the provider-upgrade skill.
Upgrading Pulumi Providers
The Principle
A provider upgrade is a translation, not a change request.
The user's infrastructure intent hasn't changed - they still want the same bucket, the same function, the same cluster. What changed is how the provider's API expresses that intent. Your job is to translate their existing code into the new API so that Pulumi sees no difference between what the code says and what already exists.
There are four layers to keep in mind:
- User intent - what the user wants in the cloud (unchanged during an upgrade)
- Code - how the program expresses that intent using the provider API (may need updating)
- Pulumi state - Pulumi's stored representation of what exists (may need reconciliation)
- Real cloud - the actual infrastructure (should not change during an upgrade)
During an upgrade, layers 2 and 3 may need to change so that they continue to correctly represent the unchanged layers 1 and 4.
A correct translation produces zero diff. The Pulumi engine doesn't have a concept of "upgrade" - it just compares goal state (your code) against actual state (the state file) and reconciles. If the translation is correct, those two states match and nothing happens. If you see a diff, either your translation is wrong, or something beyond a code change is needed (import, alias, manual step). In all cases, the diff is a problem to solve, not a consequence to accept.
The Core Loop
flowchart TD
A[Bump version] --> B[Run preview with env vars]
B --> C{Clean?}
C -->|Yes| D[Create PR]
C -->|No| E[Diff Checkpoint: categorize every diff]
E --> F{Any Category A?}
F -->|Yes| G[Fix wrong translations]
G --> B
F -->|No| H{Any Category B?}
H -->|Yes| I[Investigate with toolbox]
I --> J[Fix or document]
J --> B
H -->|No| D
- Bump the provider dependency
- Preview with required CLI flags
- Diff Checkpoint - categorize every non-
sameresource (see next section) - Fix Category A - code changes that didn't produce
same - Investigate Category B - diffs on resources you didn't change
- Repeat until clean or remaining diffs are fully investigated
- Create PR with upgrade summary
The Diff Checkpoint
This is the most important section. Run this after EVERY preview.
For each non-same resource, answer one question:
"Did any of my code changes affect this resource - directly or indirectly?"
"Directly" means you edited the resource block itself. "Indirectly" means you changed something that feeds into this resource - a shared variable, an output from another resource, a helper function, a default value, or a resource that this one depends on. If your changes could have altered what Pulumi computes for this resource, it's Category A.
Then follow the category that applies.
Category A: I changed code for this resource
Your code change was supposed to translate the same intent into the new API. If the
resource shows same, your translation is correct. If it shows anything else, your
translation is wrong. Not "the diff is expected because I changed the code" - if the
change were semantically equivalent, there would be no diff.
I modified an existing resource and it shows update:
Your rename, restructure, or value adjustment changed the meaning, not just the syntax.
The resource would show same if the old and new code compiled to the same goal state.
The update means they don't.
Ask yourself: "If this rename were truly equivalent, the resource would show same.
It doesn't. What is semantically different between my old code and my new code?"
Common causes: the new property name maps to a different underlying field; the value shape changed and your conversion lost or added information; a default value changed in the new version and you need to explicitly set the old value; additional properties now appear in the diff because the new provider version tracks fields it didn't before (these need to be set explicitly to match the current state).
If the update includes properties you didn't change - new fields appearing, type
normalizations (string->number), additional defaults - that's the provider changing what
it tracks. But if the diff is there, pulumi up WILL send those values to the cloud API.
Don't assume they're no-ops. Investigate each changed property.
I added a new resource block and it shows create:
During an upgrade, a new resource block almost always represents infrastructure that already exists in the cloud. The old provider managed it implicitly (as part of another resource); the new provider needs an explicit resource. But the cloud object is already there. Pulumi wants to create NEW infrastructure - that's not what you want.
The fix is import, not create. Tell Pulumi to adopt the existing cloud resource.
Ask yourself: "What cloud object does this new resource represent? Does it already exist? How was it managed before the upgrade?"
// Wrong - creates duplicate infrastructure
const stage = new aws.apigateway.Stage("prodStage", { ... });
// Right - adopts the existing resource
const stage = new aws.apigateway.Stage("prodStage", { ... }, {
import: "<rest-api-id>/prod", // import ID format varies by resource type
});
I removed a resource block and it shows delete:
A delete in the preview means pulumi up will call the provider's Delete API to
destroy or unconfigure this cloud resource. This is real destruction - not just state
cleanup. The cloud infrastructure still exists and is almost certainly still needed.
This is different from pulumi state delete, which removes the resource from Pulumi's
tracking WITHOUT calling the provider's API. When a resource type is removed in a new
provider version, the correct approach is:
pulumi state delete '<urn>'- manual step, removes from tracking only- Add replacement resources (if any) with imports - adopts the cloud state under new types
- Verify with preview
Do NOT leave a delete in the preview and proceed to PR creation. A delete that runs
via pulumi up will destroy real infrastructure. If the resource must be removed from
state, document it as a manual step for the user.
Ask yourself: "What cloud infrastructure does this resource manage? If pulumi up runs
this delete, what gets destroyed or unconfigured?"
Category B: I didn't change code for this resource
This diff was not caused by your code changes. It comes from the provider version change
itself - a different default, a changed state representation, or a behavioral difference.
Read references/diagnostic-toolbox.md and investigate.
These diffs might be:
- Fixable with code - set an explicit value for a changed default, add an alias
- A documented no-op - the upgrade guide says it resolves on
pulumi upwithout affecting real infrastructure. This classification REQUIRES a citation from the upgrade guide or provider documentation. Your own judgment that "this looks like a no-op" is not sufficient - the user is trusting you to distinguish real infrastructure changes from artifacts, and getting it wrong means unexpected changes to their cloud. - Requiring manual steps - state removal + reimport, documented for the user
- Unknown - present what you've found to the user and ask for guidance
Category C: Provider version bump
An update on pulumi:providers:{name} showing only a version change is the one
expected diff. Verify no other properties changed on the provider resource.
After categorizing
Completeness check: Every resource in the preview that shows any non-same state
must appear in your checkpoint - including resources with [diff: ...] annotations,
even if they don't have an explicit create/update/delete marker. If you didn't list it,
your checkpoint is incomplete. Go back and categorize the missing resources.
Evidence requirement for accepted diffs: If you want to accept any diff as "OK" (not fix it), you need evidence - whether it's Category A or Category B. "I believe the API treats these equivalently" or "this looks like state reconciliation" is not evidence. Acceptable evidence: the upgrade guide documents it, a GitHub issue confirms it, or the provider documentation explains the behavior. If you can't find evidence, either fix the diff or flag it to the user.
Ordering: Fix all Category A issues before investigating Category B. Your code corrections will change the preview output, so investigating Category B diffs first wastes effort. Fix your own mistakes first, re-preview, then look at what remains.
No delete or replace in the final preview. If a delete or replace remains when
you're ready to create a PR, stop. A delete means pulumi up will destroy cloud
infrastructure. A replace means it will destroy and recreate. These are never acceptable
as "remaining diffs" - they must be resolved (via code fix, alias, or documented manual
steps) before proceeding.
Hard Rules
Required CLI flags
Use these flags when running preview. A preview without them can show false diffs (phantom tag removals, region additions) that aren't real. Don't interpret a preview that was run without them.
pulumi preview --refresh --run-program
--refreshrefreshes actual cloud state before diffing.--run-programruns the Pulumi program during refresh.
Don't chase deprecations
If something is deprecated but still works, leave it alone. Migrating to the replacement introduces risk for no benefit. A deprecation warning is acceptable - a diff is not.
// BAD: migrating deprecated-but-working properties introduces risk
new aws.s3.Bucket('bucket');
new aws.s3.BucketLogging('bucketLogging', {...}); // unnecessary migration
// GOOD: fix only the actual error, leave working code alone
new aws.s3.Bucket('bucket', {
logging: {...}, // "loggings" renamed to "logging" - real breaking change
website: {...}, // deprecated but works - don't touch
});
Be minimally invasive
Every line changed could introduce a regression. Prefer the smallest change that works.
Do not run pulumi up
Provider upgrades modify source code and need code review before deployment. PR -> review -> merge -> deploy via CI/CD.
Getting Started
1. Get version information
Determine the target version from the user's request, the Pulumi Registry, package manager metadata, or the repository's existing dependency constraints.
Default to the latest stable version if the user hasn't specified a target version.
If the user asks which stacks or projects are affected, use skill package-usage or
the best available package inventory tooling before making changes.
1a. Check for a provider-specific reference
Some major versions have breaking changes that destroy live resources if fixed in the wrong
order, which preview alone does not reveal. If references/ has a file for this provider and
target major (for example gcp-v10.md for pulumi-gcp to 10.x), read it now and follow its
"Before the bump" section before step 2. For that upgrade it overrides the "Do not research
breaking changes first" rule in step 3.
2. Update the dependency
- TypeScript/JavaScript:
npm install @pulumi/{provider}@^{version}oryarn add @pulumi/{provider}@^{version} - Python: Update
pyproject.tomlorrequirements.txtwithpulumi_{provider}>={version}(underscore, not hyphen), then install - Go:
go get github.com/pulumi/pulumi-{provider}/sdk/v{major}@latest, update all import paths (e.g.,v6->v7), rungo mod tidy - .NET:
dotnet add package Pulumi.{Provider} --version {version} - Java: Update
pom.xmlorbuild.gradledependency version - YAML: Update provider version in resource options or provider configuration. See https://www.pulumi.com/docs/iac/languages-sdks/yaml/yaml-language-reference/#providers-and-provider-versions for examples.
After installing, check the actual installed version from the lockfile (package-lock.json, go.sum, etc.) - use these exact versions for schema-tools comparisons.
3. Run preview
Run pulumi preview --refresh --run-program immediately after updating the dependency.
Do not research breaking changes first - many upgrades just work, especially minor
versions.
If the preview is clean (only the provider version bump), create a PR.
Preview Progress
Preview can fail on the first error and hide others. Fixing one error often reveals new errors. This is normal progress, not a sign that fixes are making things worse.
- New or different errors -> progress, continue
- Error set shrank -> progress, continue
- Same error persists -> your fix didn't work, try a different approach
- No errors but diffs -> run the diff checkpoint
Upgrade Summary
Once the preview is clean (or as clean as possible), present the summary:
## Upgrade Summary: {provider} v{current} -> v{target}
### Code Changes
| File | Change | Why it preserves intent |
|------|--------|------------------------|
| package.json | Version bump | - |
| index.ts:15 | loggings -> logging | Property renamed, same underlying field |
### Preview Result
All resources show `same` except provider version bump.
{Or: N resources show diffs - see below}
### Remaining Diffs (if any)
| Resource | Operation | What happens on `pulumi up` | Risk | Source |
|----------|-----------|---------------------------|------|--------|
| aws:s3:Bucket (myBucket) | update (-tags) | No-op, state reconciles | None | AWS v7 guide section 3.2 |
Every remaining diff MUST cite an authoritative source (upgrade guide, provider docs,
upstream GitHub issue). "I believe this is expected" is not a source.
### Manual Steps Required (if any)
1. `pulumi state delete '<urn>'` - remove old type binding
2. `pulumi import <type> <name> <id>` - adopt under new type
3. `pulumi preview --refresh --run-program` - verify clean
### Deprecation Warnings (no action taken)
- List deprecated-but-working code left intentionally
If the preview is clean (or all remaining diffs are documented no-ops with cited sources), create a pull request. If unresolved diffs remain, present the summary as an exception report and ask the user how they'd like to proceed before creating a PR.
References
references/diagnostic-toolbox.md- upgrade guides, schema-tools (install, run, interpret output), stack state inspection, SDK types, GitHub issues. Read when investigating Category B diffs.references/gcp-v10.md- every pulumi-gcp v10 breaking change with state scan, grep patterns, fix order and risk. Read before bumping pulumi-gcp to 10.x (see step 1a).
Pulumi Automation API
When to Use This Skill
Invoke this skill when:
- Orchestrating deployments across multiple Pulumi stacks
- Embedding Pulumi operations in custom applications
- Building self-service infrastructure platforms
- Replacing fragile Bash/Makefile orchestration scripts
- Creating custom CLIs for infrastructure management
- Building web applications that provision infrastructure
What is Automation API
Automation API provides programmatic access to Pulumi operations. Instead of running pulumi up from the CLI, you call functions in your code that perform the same operations.
import * as automation from "@pulumi/pulumi/automation";
// Create or select a stack
const stack = await automation.LocalWorkspace.createOrSelectStack({
stackName: "dev",
projectName: "my-project",
program: async () => {
// Your Pulumi program here
},
});
// Run pulumi up programmatically
const upResult = await stack.up({ onOutput: console.log });
console.log(`Update summary: ${JSON.stringify(upResult.summary)}`);
When to Use Automation API
Good Use Cases
Multi-stack orchestration:
When you split infrastructure into multiple focused projects, Automation API helps offset the added complexity by orchestrating operations across stacks:
infrastructure → platform → application
↓ ↓ ↓
(VPC) (Kubernetes) (Services)
Automation API ensures correct sequencing without manual intervention.
Self-service platforms:
Build internal tools where developers request infrastructure without learning Pulumi:
- Web portals for environment provisioning
- Slack bots that create/destroy resources
- Custom CLIs tailored to your organization
Embedded infrastructure:
Applications that provision their own infrastructure:
- SaaS platforms creating per-tenant resources
- Testing frameworks spinning up test environments
- CI/CD systems with dynamic infrastructure needs
Replacing fragile scripts:
If you have Bash scripts or Makefiles stitching together multiple pulumi commands, Automation API provides:
- Proper error handling
- Type safety
- Programmatic access to outputs
When NOT to Use
- Single project with standard deployment needs
- When you don't need programmatic control over operations
Architecture Choices
Local Source vs Inline Source
Local Source - Pulumi program in separate files:
const stack = await automation.LocalWorkspace.createOrSelectStack({
stackName: "dev",
workDir: "./infrastructure", // Points to existing Pulumi project
});
When to use:
- Different teams maintain orchestrator vs Pulumi programs
- Pulumi programs already exist
- Want independent version control and release cycles
- Platform team orchestrating application team's infrastructure
Inline Source - Pulumi program embedded in orchestrator:
import * as aws from "@pulumi/aws";
const stack = await automation.LocalWorkspace.createOrSelectStack({
stackName: "dev",
projectName: "my-project",
program: async () => {
const bucket = new aws.s3.Bucket("my-bucket");
return { bucketName: bucket.id };
},
});
When to use:
- Single team owns everything
- Tight coupling between orchestration and infrastructure is desired
- Distributing as compiled binary (no source files needed)
- Simpler deployment artifact
Language Independence
The Automation API program can use a different language than the Pulumi programs it orchestrates:
Orchestrator (Go) → manages → Pulumi Program (TypeScript)
This enables platform teams to use their preferred language while application teams use theirs.
Common Patterns
Multi-Stack Orchestration
Deploy multiple stacks in dependency order:
import * as automation from "@pulumi/pulumi/automation";
async function deploy() {
const stacks = [
{ name: "infrastructure", dir: "./infra" },
{ name: "platform", dir: "./platform" },
{ name: "application", dir: "./app" },
];
for (const stackInfo of stacks) {
console.log(`Deploying ${stackInfo.name}...`);
const stack = await automation.LocalWorkspace.createOrSelectStack({
stackName: "prod",
workDir: stackInfo.dir,
});
await stack.up({ onOutput: console.log });
console.log(`${stackInfo.name} deployed successfully`);
}
}
async function destroy() {
// Destroy in reverse order
const stacks = [
{ name: "application", dir: "./app" },
{ name: "platform", dir: "./platform" },
{ name: "infrastructure", dir: "./infra" },
];
for (const stackInfo of stacks) {
console.log(`Destroying ${stackInfo.name}...`);
const stack = await automation.LocalWorkspace.selectStack({
stackName: "prod",
workDir: stackInfo.dir,
});
await stack.destroy({ onOutput: console.log });
}
}
Passing Configuration
Set stack configuration programmatically:
const stack = await automation.LocalWorkspace.createOrSelectStack({
stackName: "dev",
workDir: "./infrastructure",
});
// Set configuration values
await stack.setConfig("aws:region", { value: "us-west-2" });
await stack.setConfig("dbPassword", { value: "secret", secret: true });
// Then deploy
await stack.up();
Reading Outputs
Access stack outputs after deployment:
const upResult = await stack.up();
// Get all outputs
const outputs = await stack.outputs();
console.log(`VPC ID: ${outputs["vpcId"].value}`);
// Or from the up result
console.log(`Outputs: ${JSON.stringify(upResult.outputs)}`);
Error Handling
Handle deployment failures gracefully:
try {
const result = await stack.up({ onOutput: console.log });
if (result.summary.result === "failed") {
console.error("Deployment failed");
process.exit(1);
}
} catch (error) {
console.error(`Deployment error: ${error}`);
throw error;
}
Parallel Stack Operations
When stacks are independent, deploy in parallel:
const independentStacks = [
{ name: "service-a", dir: "./service-a" },
{ name: "service-b", dir: "./service-b" },
{ name: "service-c", dir: "./service-c" },
];
await Promise.all(independentStacks.map(async (stackInfo) => {
const stack = await automation.LocalWorkspace.createOrSelectStack({
stackName: "prod",
workDir: stackInfo.dir,
});
return stack.up({ onOutput: (msg) => console.log(`[${stackInfo.name}] ${msg}`) });
}));
Best Practices
Separate Configuration from Code
Externalize configuration into files or environment variables:
import * as fs from "fs";
interface DeployConfig {
stacks: Array<{ name: string; dir: string; }>;
environment: string;
}
const config: DeployConfig = JSON.parse(
fs.readFileSync("./deploy-config.json", "utf-8")
);
for (const stackInfo of config.stacks) {
const stack = await automation.LocalWorkspace.createOrSelectStack({
stackName: config.environment,
workDir: stackInfo.dir,
});
await stack.up();
}
This enables distributing compiled binaries without exposing source code.
Stream Output for Long Operations
Use onOutput callback for real-time feedback:
await stack.up({
onOutput: (message) => {
process.stdout.write(message);
// Or send to logging system, websocket, etc.
},
});
Quick Reference
| Scenario | Approach |
|---|---|
| Existing Pulumi projects | Local source with workDir |
| New embedded infrastructure | Inline source with program function |
| Different teams | Local source for independence |
| Compiled binary distribution | Inline source or bundled local |
| Multi-stack dependencies | Sequential deployment in order |
| Independent stacks | Parallel deployment with Promise.all |
Related Skills
- pulumi-best-practices: Code-level patterns for Pulumi programs
References
Pulumi Best Practices
When to Use This Skill
Invoke this skill when:
- Writing new Pulumi programs or components
- Reviewing Pulumi code for correctness
- Refactoring existing Pulumi infrastructure
- Debugging resource dependency issues
- Setting up configuration and secrets
Practices
1. Never Create Resources Inside apply()
Why: Resources created inside apply() don't appear in pulumi preview, making changes unpredictable. Pulumi cannot properly track dependencies, leading to race conditions and deployment failures.
Detection signals:
new aws.or other resource constructors inside.apply()callbacks- Resource creation inside
pulumi.all([...]).apply() - Dynamic resource counts determined at runtime inside apply
Wrong:
const bucket = new aws.s3.Bucket("bucket");
bucket.id.apply(bucketId => {
// WRONG: This resource won't appear in preview
new aws.s3.BucketObject("object", {
bucket: bucketId,
content: "hello",
});
});
Right:
const bucket = new aws.s3.Bucket("bucket");
// Pass the output directly - Pulumi handles the dependency
const object = new aws.s3.BucketObject("object", {
bucket: bucket.id, // Output<string> works here
content: "hello",
});
When apply is appropriate:
- Transforming output values for use in tags, names, or computed strings
- Logging or debugging (not resource creation)
- Conditional logic that affects resource properties, not resource existence
Reference: https://www.pulumi.com/docs/concepts/inputs-outputs/
2. Pass Outputs Directly as Inputs
Why: Pulumi builds a directed acyclic graph (DAG) based on input/output relationships. Passing outputs directly ensures correct creation order. Unwrapping values manually breaks the dependency chain, causing resources to deploy in wrong order or reference values that don't exist yet.
Detection signals:
- Variables extracted from
.apply()used later as resource inputs awaiton output values outside of apply- String concatenation with outputs instead of
pulumi.interpolate
Wrong:
const vpc = new aws.ec2.Vpc("vpc", { cidrBlock: "10.0.0.0/16" });
// WRONG: Extracting the value breaks the dependency chain
let vpcId: string;
vpc.id.apply(id => { vpcId = id; });
const subnet = new aws.ec2.Subnet("subnet", {
vpcId: vpcId, // May be undefined, no tracked dependency
cidrBlock: "10.0.1.0/24",
});
Right:
const vpc = new aws.ec2.Vpc("vpc", { cidrBlock: "10.0.0.0/16" });
const subnet = new aws.ec2.Subnet("subnet", {
vpcId: vpc.id, // Pass the Output directly
cidrBlock: "10.0.1.0/24",
});
For string interpolation:
// WRONG
const name = bucket.id.apply(id => `prefix-${id}-suffix`);
// RIGHT - use pulumi.interpolate for template literals
const name = pulumi.interpolate`prefix-${bucket.id}-suffix`;
// RIGHT - use pulumi.concat for simple concatenation
const name = pulumi.concat("prefix-", bucket.id, "-suffix");
Reference: https://www.pulumi.com/docs/concepts/inputs-outputs/
3. Use Components for Related Resources
Why: ComponentResource classes group related resources into reusable, logical units. Without components, your resource graph is flat, making it hard to understand which resources belong together, reuse patterns across stacks, or reason about your infrastructure at a higher level.
Detection signals:
- Multiple related resources created at top level without grouping
- Repeated resource patterns across stacks that should be abstracted
- Hard to understand resource relationships from the Pulumi console
Wrong:
// Flat structure - no logical grouping, hard to reuse
const bucket = new aws.s3.Bucket("app-bucket");
const bucketPolicy = new aws.s3.BucketPolicy("app-bucket-policy", {
bucket: bucket.id,
policy: policyDoc,
});
const originAccessIdentity = new aws.cloudfront.OriginAccessIdentity("app-oai");
const distribution = new aws.cloudfront.Distribution("app-cdn", { /* ... */ });
Right:
interface StaticSiteArgs {
domain: string;
content: pulumi.asset.AssetArchive;
}
class StaticSite extends pulumi.ComponentResource {
public readonly url: pulumi.Output<string>;
constructor(name: string, args: StaticSiteArgs, opts?: pulumi.ComponentResourceOptions) {
super("myorg:components:StaticSite", name, args, opts);
// Resources created here - see practice 4 for parent setup
const bucket = new aws.s3.Bucket(`${name}-bucket`, {}, { parent: this });
// ...
this.url = distribution.domainName;
this.registerOutputs({ url: this.url });
}
}
// Reusable across stacks
const site = new StaticSite("marketing", {
domain: "marketing.example.com",
content: new pulumi.asset.FileArchive("./dist"),
});
Component best practices:
- Use a consistent type URN pattern:
organization:module:ComponentName - Call
registerOutputs()at the end of the constructor - Expose outputs as class properties for consumers
- Accept
ComponentResourceOptionsto allow callers to set providers, aliases, etc.
For in-depth component authoring guidance (args design, multi-language support, testing, distribution), use skill pulumi-component.
Reference: https://www.pulumi.com/docs/concepts/resources/components/
4. Always Set parent: this in Components
Why: When you create resources inside a ComponentResource without setting parent: this, those resources appear at the root level of your stack's state. This breaks the logical hierarchy, makes the Pulumi console hard to navigate, and can cause issues with aliases and refactoring. The parent relationship is what makes the component actually group its children.
Detection signals:
- ComponentResource classes that don't pass
{ parent: this }to child resources - Resources inside a component appearing at root level in the console
- Unexpected behavior when adding aliases to components
Wrong:
class MyComponent extends pulumi.ComponentResource {
constructor(name: string, opts?: pulumi.ComponentResourceOptions) {
super("myorg:components:MyComponent", name, {}, opts);
// WRONG: No parent set - this bucket appears at root level
const bucket = new aws.s3.Bucket(`${name}-bucket`);
}
}
Right:
class MyComponent extends pulumi.ComponentResource {
constructor(name: string, opts?: pulumi.ComponentResourceOptions) {
super("myorg:components:MyComponent", name, {}, opts);
// RIGHT: Parent establishes hierarchy
const bucket = new aws.s3.Bucket(`${name}-bucket`, {}, {
parent: this
});
const policy = new aws.s3.BucketPolicy(`${name}-policy`, {
bucket: bucket.id,
policy: policyDoc,
}, {
parent: this
});
}
}
What parent: this provides:
- Resources appear nested under the component in Pulumi console
- Deleting the component deletes all children
- Aliases on the component automatically apply to children
- Clear ownership in state files
Reference: https://www.pulumi.com/docs/concepts/resources/components/
5. Encrypt Secrets from Day One
Why: Secrets marked with --secret are encrypted in state files, masked in CLI output, and tracked through transformations. Starting with plaintext config and converting later requires credential rotation, reference updates, and audit of leaked values in logs and state history.
Detection signals:
- Passwords, API keys, tokens stored as plain config
- Connection strings with embedded credentials
- Private keys or certificates in plaintext
Wrong:
# Plaintext - will be visible in state and logs
pulumi config set databasePassword hunter2
pulumi config set apiKey sk-1234567890
Right:
# Encrypted from the start
pulumi config set --secret databasePassword hunter2
pulumi config set --secret apiKey sk-1234567890
In code:
const config = new pulumi.Config();
// This retrieves a secret - the value stays encrypted
const dbPassword = config.requireSecret("databasePassword");
// Creating outputs from secrets preserves secrecy
const connectionString = pulumi.interpolate`postgres://user:${dbPassword}@host/db`;
// connectionString is also a secret Output
// Explicitly mark values as secret
const computed = pulumi.secret(someValue);
Use Pulumi ESC for centralized secrets:
# Pulumi.yaml
environment:
- production-secrets # Pull from ESC environment
# ESC manages secrets centrally across stacks
esc env set production-secrets db.password --secret "hunter2"
What qualifies as a secret:
- Passwords and passphrases
- API keys and tokens
- Private keys and certificates
- Connection strings with credentials
- OAuth client secrets
- Encryption keys
References:
6. Use Aliases When Refactoring
Why: Renaming resources, moving them into components, or changing parents causes Pulumi to see them as new resources. Without aliases, refactoring destroys and recreates resources, potentially causing downtime or data loss. Aliases preserve resource identity through refactors.
Detection signals:
- Resource rename without alias
- Moving resource into or out of a ComponentResource
- Changing the parent of a resource
- Preview shows delete+create when update was intended
Wrong:
// Before: resource named "my-bucket"
const bucket = new aws.s3.Bucket("my-bucket");
// After: renamed without alias - DESTROYS THE BUCKET
const bucket = new aws.s3.Bucket("application-bucket");
Right:
// After: renamed with alias - preserves the existing bucket
const bucket = new aws.s3.Bucket("application-bucket", {}, {
aliases: [{ name: "my-bucket" }],
});
Moving into a component:
// Before: top-level resource
const bucket = new aws.s3.Bucket("my-bucket");
// After: inside a component - needs alias with old parent
class MyComponent extends pulumi.ComponentResource {
constructor(name: string, opts?: pulumi.ComponentResourceOptions) {
super("myorg:components:MyComponent", name, {}, opts);
const bucket = new aws.s3.Bucket("bucket", {}, {
parent: this,
aliases: [{
name: "my-bucket",
parent: pulumi.rootStackResource, // Was at root
}],
});
}
}
Alias types:
// Simple name change
aliases: [{ name: "old-name" }]
// Parent change
aliases: [{ name: "resource-name", parent: oldParent }]
// Full URN (when you know the exact previous URN)
aliases: ["urn:pulumi:stack::project::aws:s3/bucket:Bucket::old-name"]
Lifecycle:
- Add alias during refactor
- Run
pulumi upon all stacks - Remove alias after all stacks updated (optional, but keeps code clean)
Reference: https://www.pulumi.com/docs/iac/concepts/resources/options/aliases/
7. Preview Before Every Deployment
Why: pulumi preview shows exactly what will be created, updated, or destroyed. Surprises in production come from skipping preview. A resource showing "replace" when you expected "update" means imminent destruction and recreation.
Detection signals:
- Running
pulumi up --yesinteractively without reviewing changes - No preview step anywhere in the CI/CD workflow for a given change
- Preview output not reviewed before merge or deployment approval
Wrong:
# Deploying blind
pulumi up --yes
Right:
# Always preview first
pulumi preview
# Review the output, then deploy
pulumi up
What to look for in preview:
+ create- New resource will be created~ update- Existing resource will be modified in place- delete- Resource will be destroyed+-replace- Resource will be destroyed and recreated (potential downtime)~+-replace- Resource will be updated, then replaced
Warning signs:
- Unexpected
replaceoperations (check for immutable property changes) - Resources being deleted that shouldn't be
- More changes than expected from your code diff
CI/CD integration:
# GitHub Actions example
jobs:
preview:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Pulumi Preview
uses: pulumi/actions@v5
with:
command: preview
stack-name: production
env:
PULUMI_ACCESS_TOKEN: ${{ secrets.PULUMI_ACCESS_TOKEN }}
deploy:
needs: preview
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- name: Pulumi Up
uses: pulumi/actions@v5
with:
command: up
stack-name: production
PR workflow:
- Run preview on every PR
- Post preview output as PR comment
- Require preview review before merge
- Deploy only on merge to main
References:
- https://www.pulumi.com/docs/cli/commands/pulumi_preview/
- https://www.pulumi.com/docs/iac/packages-and-automation/continuous-delivery/github-actions/
Quick Reference
| Practice | Key Signal | Fix |
|---|---|---|
| No resources in apply | new Resource() inside .apply() | Move resource outside, pass Output directly |
| Pass outputs directly | Extracted values used as inputs | Use Output objects, pulumi.interpolate |
| Use components | Flat structure, repeated patterns | Create ComponentResource classes |
| Set parent: this | Component children at root level | Pass { parent: this } to all child resources |
| Secrets from day one | Plaintext passwords/keys in config | Use --secret flag, ESC |
| Aliases when refactoring | Delete+create in preview | Add alias with old name/parent |
| Preview before deploy | pulumi up --yes | Always run pulumi preview first |
Validation Checklist
When reviewing Pulumi code, verify:
- No resource constructors inside
apply()callbacks - Outputs passed directly to dependent resources
- Related resources grouped in ComponentResource classes
- Child resources have
{ parent: this } - Sensitive values use
config.requireSecret()or--secret - Refactored resources have aliases preserving identity
- Deployment process includes preview step
Related Skills
- pulumi-overview: Entry-point skill that orients an agent across the three Pulumi surfaces (
pulumi doCLI, IaC projects, and Pulumi Cloud) and routes to specialized skills. Load it first when the task begins with general infrastructure phrasing or spans multiple Pulumi surfaces. Use skillpulumi-overview. - pulumi-component: Deep guide to authoring ComponentResource classes, designing args interfaces, multi-language support, testing, and distribution. Use skill
pulumi-component. - pulumi-automation-api: Programmatic orchestration of multiple stacks. Use skill
pulumi-automation-api. - pulumi-esc: Centralized secrets and configuration management. Use skill
pulumi-esc.
Authoring Pulumi Components
A ComponentResource groups related infrastructure resources into a reusable, logical unit. Components make infrastructure easier to understand, reuse, and maintain. Components appear as a single node with children nested underneath in pulumi preview/pulumi up output and in the Pulumi Cloud console.
This skill covers the full component authoring lifecycle. For general Pulumi coding patterns (Output handling, secrets, aliases, preview workflows), use the pulumi-best-practices skill instead.
When to Use This Skill
Invoke this skill when:
- Creating a new ComponentResource class
- Designing the args interface for a component
- Making a component consumable from multiple Pulumi languages
- Publishing or distributing a component package
- Refactoring inline resources into a reusable component
- Debugging component behavior (missing outputs, stuck creating, children at wrong level)
Component Anatomy
Every component has four required elements:
- Extend ComponentResource and call
super()with a type URN - Accept standard parameters: name, args, and
ComponentResourceOptions - Set
parent: thison all child resources - Call
registerOutputs()at the end of the constructor
TypeScript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
interface StaticSiteArgs {
indexDocument?: pulumi.Input<string>;
errorDocument?: pulumi.Input<string>;
}
class StaticSite extends pulumi.ComponentResource {
public readonly bucketName: pulumi.Output<string>;
public readonly websiteUrl: pulumi.Output<string>;
constructor(name: string, args: StaticSiteArgs, opts?: pulumi.ComponentResourceOptions) {
// 1. Call super with type URN: <package>:<module>:<type>
super("myorg:index:StaticSite", name, {}, opts);
// 2. Create child resources with parent: this
const bucket = new aws.s3.Bucket(`${name}-bucket`, {}, { parent: this });
const website = new aws.s3.BucketWebsiteConfigurationV2(`${name}-website`, {
bucket: bucket.id,
indexDocument: { suffix: args.indexDocument ?? "index.html" },
errorDocument: { key: args.errorDocument ?? "error.html" },
}, { parent: this });
// 3. Expose outputs as class properties
this.bucketName = bucket.id;
this.websiteUrl = website.websiteEndpoint;
// 4. Register outputs -- always the last line
this.registerOutputs({
bucketName: this.bucketName,
websiteUrl: this.websiteUrl,
});
}
}
// Usage
const site = new StaticSite("marketing", {
indexDocument: "index.html",
});
export const url = site.websiteUrl;
Python
import pulumi
import pulumi_aws as aws
class StaticSiteArgs:
def __init__(self,
index_document: pulumi.Input[str] = "index.html",
error_document: pulumi.Input[str] = "error.html"):
self.index_document = index_document
self.error_document = error_document
class StaticSite(pulumi.ComponentResource):
bucket_name: pulumi.Output[str]
website_url: pulumi.Output[str]
def __init__(self, name: str, args: StaticSiteArgs,
opts: pulumi.ResourceOptions = None):
super().__init__("myorg:index:StaticSite", name, None, opts)
bucket = aws.s3.Bucket(f"{name}-bucket",
opts=pulumi.ResourceOptions(parent=self))
website = aws.s3.BucketWebsiteConfigurationV2(f"{name}-website",
bucket=bucket.id,
index_document=aws.s3.BucketWebsiteConfigurationV2IndexDocumentArgs(
suffix=args.index_document,
),
error_document=aws.s3.BucketWebsiteConfigurationV2ErrorDocumentArgs(
key=args.error_document,
),
opts=pulumi.ResourceOptions(parent=self))
self.bucket_name = bucket.id
self.website_url = website.website_endpoint
self.register_outputs({
"bucket_name": self.bucket_name,
"website_url": self.website_url,
})
site = StaticSite("marketing", StaticSiteArgs())
pulumi.export("url", site.website_url)
Type URN Format
The first argument to super() is the type URN: <package>:<module>:<type>.
| Segment | Convention | Example |
|---|---|---|
| package | Organization or package name | myorg, acme, pkg |
| module | Usually index | index |
| type | PascalCase class name | StaticSite, VpcNetwork |
Full examples: myorg:index:StaticSite, acme:index:KubernetesCluster
registerOutputs Is Required
Why: Without registerOutputs(), the component appears stuck in a "creating" state in the Pulumi console and outputs are not persisted to state.
Wrong:
class MyComponent extends pulumi.ComponentResource {
public readonly url: pulumi.Output<string>;
constructor(name: string, args: MyArgs, opts?: pulumi.ComponentResourceOptions) {
super("myorg:index:MyComponent", name, {}, opts);
const bucket = new aws.s3.Bucket(`${name}-bucket`, {}, { parent: this });
this.url = bucket.bucketRegionalDomainName;
// Missing registerOutputs -- component stuck "creating"
}
}
Right:
class MyComponent extends pulumi.ComponentResource {
public readonly url: pulumi.Output<string>;
constructor(name: string, args: MyArgs, opts?: pulumi.ComponentResourceOptions) {
super("myorg:index:MyComponent", name, {}, opts);
const bucket = new aws.s3.Bucket(`${name}-bucket`, {}, { parent: this });
this.url = bucket.bucketRegionalDomainName;
this.registerOutputs({ url: this.url });
}
}
Derive Child Names from the Component Name
Why: Hardcoded child names cause collisions when the component is instantiated multiple times.
Wrong:
// Collides if two instances of this component exist
const bucket = new aws.s3.Bucket("my-bucket", {}, { parent: this });
Right:
// Unique per component instance
const bucket = new aws.s3.Bucket(`${name}-bucket`, {}, { parent: this });
Designing the Args Interface
The args interface is the most impactful design decision. It defines what consumers can configure and how composable the component is.
Wrap Properties in Input
Why: Input<T> accepts both plain values and Output<T> from other resources. Without it, consumers must unwrap outputs manually with .apply().
Wrong:
interface WebServiceArgs {
port: number; // Forces consumers to unwrap Outputs
vpcId: string; // Cannot accept vpc.id directly
}
Right:
interface WebServiceArgs {
port: pulumi.Input<number>; // Accepts 8080 or someOutput
vpcId: pulumi.Input<string>; // Accepts "vpc-123" or vpc.id
}
Keep Structures Flat
Avoid deeply nested arg objects. Flat interfaces are easier to use and evolve.
// Prefer flat
interface DatabaseArgs {
instanceClass: pulumi.Input<string>;
storageGb: pulumi.Input<number>;
enableBackups?: pulumi.Input<boolean>;
backupRetentionDays?: pulumi.Input<number>;
}
// Avoid deep nesting
interface DatabaseArgs {
instance: {
compute: { class: pulumi.Input<string> };
storage: { sizeGb: pulumi.Input<number> };
};
backup: {
config: { enabled: pulumi.Input<boolean>; retention: pulumi.Input<number> };
};
}
No Union Types
Union types break multi-language SDK generation. Python, Go, and C# cannot represent string | number.
Wrong:
interface MyArgs {
port: pulumi.Input<string | number>; // Fails in Python, Go, C#
}
Right:
interface MyArgs {
port: pulumi.Input<number>; // Single type, works everywhere
}
If you need to accept multiple forms, use separate optional properties:
interface StorageArgs {
sizeGb?: pulumi.Input<number>; // Specify size in GB
sizeMb?: pulumi.Input<number>; // Or specify size in MB
}
No Functions or Callbacks
Functions cannot be serialized across language boundaries.
Wrong:
interface MyArgs {
nameTransform: (name: string) => string; // Cannot serialize
}
Right:
interface MyArgs {
namePrefix?: pulumi.Input<string>; // Configuration instead of callback
nameSuffix?: pulumi.Input<string>;
}
Use Defaults for Optional Properties
Set sensible defaults inside the constructor so consumers only configure what they need:
interface SecureBucketArgs {
enableVersioning?: pulumi.Input<boolean>; // Defaults to true
enableEncryption?: pulumi.Input<boolean>; // Defaults to true
blockPublicAccess?: pulumi.Input<boolean>; // Defaults to true
}
class SecureBucket extends pulumi.ComponentResource {
constructor(name: string, args: SecureBucketArgs, opts?: pulumi.ComponentResourceOptions) {
super("myorg:index:SecureBucket", name, {}, opts);
const enableVersioning = args.enableVersioning ?? true;
const enableEncryption = args.enableEncryption ?? true;
const blockPublicAccess = args.blockPublicAccess ?? true;
// Apply defaults...
}
}
// Consumer only overrides what they need
const bucket = new SecureBucket("data", { enableVersioning: false });
Exposing Outputs
Expose Only What Consumers Need
Components often create many internal resources. Expose only the values consumers need, not every internal resource.
Wrong:
class Database extends pulumi.ComponentResource {
// Exposes everything -- consumers see implementation details
public readonly cluster: aws.rds.Cluster;
public readonly primaryInstance: aws.rds.ClusterInstance;
public readonly replicaInstance: aws.rds.ClusterInstance;
public readonly subnetGroup: aws.rds.SubnetGroup;
public readonly securityGroup: aws.ec2.SecurityGroup;
public readonly parameterGroup: aws.rds.ClusterParameterGroup;
// ...
}
Right:
class Database extends pulumi.ComponentResource {
// Exposes only what consumers need
public readonly endpoint: pulumi.Output<string>;
public readonly port: pulumi.Output<number>;
public readonly securityGroupId: pulumi.Output<string>;
constructor(name: string, args: DatabaseArgs, opts?: pulumi.ComponentResourceOptions) {
super("myorg:index:Database", name, {}, opts);
const sg = new aws.ec2.SecurityGroup(`${name}-sg`, { /* ... */ }, { parent: this });
const cluster = new aws.rds.Cluster(`${name}-cluster`, { /* ... */ }, { parent: this });
this.endpoint = cluster.endpoint;
this.port = cluster.port;
this.securityGroupId = sg.id;
this.registerOutputs({
endpoint: this.endpoint,
port: this.port,
securityGroupId: this.securityGroupId,
});
}
}
Derive Composite Outputs
Use pulumi.interpolate or pulumi.concat to build derived values:
this.connectionString = pulumi.interpolate`postgresql://${args.username}:${args.password}@${cluster.endpoint}:${cluster.port}/${args.databaseName}`;
this.registerOutputs({ connectionString: this.connectionString });
Component Design Patterns
Sensible Defaults with Override
Encode best practices as defaults. Allow consumers to override when they have specific requirements.
interface SecureBucketArgs {
enableVersioning?: pulumi.Input<boolean>;
enableEncryption?: pulumi.Input<boolean>;
blockPublicAccess?: pulumi.Input<boolean>;
tags?: pulumi.Input<Record<string, pulumi.Input<string>>>;
}
class SecureBucket extends pulumi.ComponentResource {
public readonly bucketId: pulumi.Output<string>;
public readonly arn: pulumi.Output<string>;
constructor(name: string, args: SecureBucketArgs = {}, opts?: pulumi.ComponentResourceOptions) {
super("myorg:index:SecureBucket", name, {}, opts);
const bucket = new aws.s3.Bucket(`${name}-bucket`, {
tags: args.tags,
}, { parent: this });
// Versioning on by default
if (args.enableVersioning !== false) {
new aws.s3.BucketVersioningV2(`${name}-versioning`, {
bucket: bucket.id,
versioningConfiguration: { status: "Enabled" },
}, { parent: this });
}
// Encryption on by default
if (args.enableEncryption !== false) {
new aws.s3.BucketServerSideEncryptionConfigurationV2(`${name}-encryption`, {
bucket: bucket.id,
rules: [{ applyServerSideEncryptionByDefault: { sseAlgorithm: "AES256" } }],
}, { parent: this });
}
// Public access blocked by default
if (args.blockPublicAccess !== false) {
new aws.s3.BucketPublicAccessBlock(`${name}-public-access`, {
bucket: bucket.id,
blockPublicAcls: true,
blockPublicPolicy: true,
ignorePublicAcls: true,
restrictPublicBuckets: true,
}, { parent: this });
}
this.bucketId = bucket.id;
this.arn = bucket.arn;
this.registerOutputs({ bucketId: this.bucketId, arn: this.arn });
}
}
Conditional Resource Creation
Use optional args to gate creation of sub-resources:
interface WebServiceArgs {
image: pulumi.Input<string>;
port: pulumi.Input<number>;
enableMonitoring?: pulumi.Input<boolean>;
alarmEmail?: pulumi.Input<string>;
}
class WebService extends pulumi.ComponentResource {
constructor(name: string, args: WebServiceArgs, opts?: pulumi.ComponentResourceOptions) {
super("myorg:index:WebService", name, {}, opts);
const service = new aws.ecs.Service(`${name}-service`, {
// ...service config...
}, { parent: this });
// Only create alarm infrastructure when monitoring is enabled
if (args.enableMonitoring) {
const topic = new aws.sns.Topic(`${name}-alerts`, {}, { parent: this });
if (args.alarmEmail) {
new aws.sns.TopicSubscription(`${name}-alert-email`, {
topic: topic.arn,
protocol: "email",
endpoint: args.alarmEmail,
}, { parent: this });
}
new aws.cloudwatch.MetricAlarm(`${name}-cpu-alarm`, {
// ...alarm config referencing service...
alarmActions: [topic.arn],
}, { parent: this });
}
this.registerOutputs({});
}
}
Composition
Build higher-level components from lower-level ones. Each level manages a single concern.
// Lower-level component
class VpcNetwork extends pulumi.ComponentResource {
public readonly vpcId: pulumi.Output<string>;
public readonly publicSubnetIds: pulumi.Output<string>[];
public readonly privateSubnetIds: pulumi.Output<string>[];
constructor(name: string, args: VpcNetworkArgs, opts?: pulumi.ComponentResourceOptions) {
super("myorg:index:VpcNetwork", name, {}, opts);
// ...create VPC, subnets, route tables...
this.registerOutputs({ vpcId: this.vpcId });
}
}
// Higher-level component that uses VpcNetwork
class Platform extends pulumi.ComponentResource {
public readonly kubeconfig: pulumi.Output<string>;
constructor(name: string, args: PlatformArgs, opts?: pulumi.ComponentResourceOptions) {
super("myorg:index:Platform", name, {}, opts);
// Compose lower-level components
const network = new VpcNetwork(`${name}-network`, {
cidrBlock: args.cidrBlock,
}, { parent: this });
const cluster = new aws.eks.Cluster(`${name}-cluster`, {
vpcConfig: {
subnetIds: network.privateSubnetIds,
},
}, { parent: this });
this.kubeconfig = cluster.kubeconfig;
this.registerOutputs({ kubeconfig: this.kubeconfig });
}
}
Provider Passthrough
Accept explicit providers for multi-region or multi-account deployments. ComponentResourceOptions carries provider configuration to children automatically:
// Consumer passes a provider for a different region
const usWest = new aws.Provider("us-west", { region: "us-west-2" });
const site = new StaticSite("west-site", { indexDocument: "index.html" }, {
providers: [usWest],
});
Children with { parent: this } automatically inherit the provider. No extra code is needed inside the component.
Multi-Language Components
If your component will be consumed from multiple Pulumi languages (TypeScript, Python, Go, C#, Java, YAML), package it as a multi-language component.
Do You Need Multi-Language?
Ask: "Will anyone consume this component from a different language than it was authored in?"
Single-language component (no packaging needed):
- Your team uses one language and the component stays within that codebase
- The component is internal to a single project or monorepo
- No
PulumiPlugin.yamlneeded -- just import the class directly
Multi-language component (packaging required):
- Other teams consume your component in different languages
- Platform teams building abstractions for developers who choose their own language
- YAML consumers need access -- even if you author in TypeScript, YAML programs require multi-language packaging to use your component
- Building a shared component library for your organization
- Publishing to the Pulumi private registry or public registry is a common reason, but not required for multi-language support
Common mistake: A TypeScript platform team builds components only their TypeScript users can consume. If application developers use Python or YAML, those components are invisible to them without multi-language packaging.
Setup
Create a PulumiPlugin.yaml in the component directory to declare the runtime:
runtime: nodejs
Or for Python:
runtime: python
Serialization Constraints
For multi-language compatibility, args must be serializable. These constraints apply regardless of the authoring language:
| Allowed | Not Allowed |
|---|---|
string, number, boolean | Union types (string | number) |
Input<T> wrappers | Functions and callbacks |
| Arrays and maps of primitives | Complex nested generics |
| Enums | Platform-specific types |
Consuming Multi-Language Components
Consumers install the component with pulumi package add, which automatically downloads the provider plugin, generates a local SDK in the consumer's language, and updates Pulumi.yaml:
# From a Git repository
pulumi package add <git-repo-url>
# From a specific version tag
pulumi package add <git-repo-url>@v1.0.0
For fresh checkouts or CI environments, run pulumi install to ensure all package dependencies are available. The consumer does not need to manually generate SDKs.
Authors who publish SDKs to package managers (npm, PyPI, etc.) can optionally use pulumi package gen-sdk to generate language-specific SDKs for publishing. Most component authors do not need this -- pulumi package add handles SDK generation on the consumer side.
Entry Points
Published multi-language components require an entry point that hosts the component provider process. The entry point pattern differs by language.
TypeScript (runtime: nodejs):
Export component classes from index.ts. No separate entry point file is needed. Pulumi introspects exported classes automatically.
// index.ts -- exports are the entry point
export { StaticSite, StaticSiteArgs } from "./staticSite";
export { SecureBucket, SecureBucketArgs } from "./secureBucket";
Python (runtime: python):
Create a __main__.py that calls component_provider_host with all component classes:
from pulumi.provider.experimental import component_provider_host
from static_site import StaticSite
from secure_bucket import SecureBucket
if __name__ == "__main__":
component_provider_host(
name="my-components",
components=[StaticSite, SecureBucket],
)
Go (runtime: go):
Create a main.go that builds and runs the provider:
package main
import (
"context"
"fmt"
"os"
"github.com/pulumi/pulumi-go-provider/infer"
)
func main() {
p, err := infer.NewProviderBuilder().
WithComponents(
infer.ComponentF(NewStaticSite),
infer.ComponentF(NewSecureBucket),
).
Build()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := p.Run(context.Background(), "my-components", "0.1.0"); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
C# (runtime: dotnet):
Create a Program.cs that serves the component provider host:
using System.Threading.Tasks;
class Program
{
public static Task Main(string[] args) =>
Pulumi.Experimental.Provider.ComponentProviderHost.Serve(args);
}
For a complete working example across all languages, see https://github.com/mikhailshilkov/comp-as-comp.
Reference: https://www.pulumi.com/docs/iac/using-pulumi/pulumi-packages/
Distribution
Choose a distribution method based on your audience:
| Audience | Method | How |
|---|---|---|
| Same project | Direct import | Standard language import |
| Same organization | Private registry | pulumi package publish to Pulumi Cloud |
| Same organization | Git repository | pulumi package add <repo> with version tags |
| Language ecosystem | Package manager | Publish to npm, PyPI, NuGet, or Maven |
| Public community | Pulumi Registry | Submit via pulumi/registry GitHub repo |
Pulumi Private Registry
The private registry is the centralized catalog for your organization's components. It provides automatic API documentation, version management, and discoverability for all teams.
Publish a component to the private registry:
pulumi package publish https://github.com/myorg/my-component --publisher myorg
Version components using git tags with a v prefix:
git tag v1.0.0
git push origin v1.0.0
A README file is required when publishing. Pulumi uses it as the component's documentation page in the registry.
Automate publishing from GitHub Actions using OIDC authentication:
name: Publish Component
on:
push:
tags:
- "v*"
permissions:
id-token: write
contents: read
jobs:
publish:
runs-on: ubuntu-latest
env:
PULUMI_ORG: myorg
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: pulumi/auth-actions@v1
with:
organization: ${{ env.PULUMI_ORG }}
requested-token-type: urn:pulumi:token-type:access_token:organization
- run: pulumi package publish https://github.com/${{ github.repository }} --publisher ${{ env.PULUMI_ORG }}
Prerequisites: Configure GitHub OIDC integration with Pulumi Cloud before using this workflow.
The registry supports private GitHub and GitLab repositories. For non-OIDC setups, authenticate with GITHUB_TOKEN or GITLAB_TOKEN environment variables.
The private registry automatically generates SDK documentation for each published component. Enrich the generated docs by adding type annotations to your component's inputs and outputs (JSDoc in TypeScript, docstrings in Python, Annotate() methods in Go).
Reference: https://www.pulumi.com/docs/idp/get-started/private-registry/
Git Repository Distribution
Tag releases for consumers to pin versions:
git tag v1.0.0
git push origin v1.0.0
Consumers install with:
pulumi package add https://github.com/myorg/my-component@v1.0.0
Package Manager Distribution
Publish language-specific packages for native dependency management:
- npm:
npm publishfor TypeScript/JavaScript - PyPI:
twine uploadfor Python - NuGet:
dotnet nuget pushfor .NET - Maven Central: Standard Maven publishing for Java
Reference: https://www.pulumi.com/docs/iac/using-pulumi/pulumi-packages/
Anti-Patterns
| Anti-Pattern | Problem | Fix |
|---|---|---|
Resources inside apply() | Not visible in pulumi preview | Move resource creation outside apply (see pulumi-best-practices practice 1) |
Missing registerOutputs() | Component stuck "creating" | Always call as last line of constructor |
Missing parent: this | Children appear at root level | Pass { parent: this } to all child resources |
| Union types in args | Breaks Python, Go, C# SDKs | Use single types; separate properties for variants |
| Functions in args | Cannot serialize across languages | Use configuration properties instead |
| Hardcoded child names | Collisions with multiple instances | Derive names from ${name}-suffix |
| Over-exposed outputs | Leaks implementation details | Export only what consumers need |
| Single-use component | Unnecessary abstraction overhead | Use inline resources until a pattern repeats |
| Deeply nested args | Hard to use and evolve | Keep interfaces flat with optional properties |
Quick Reference
| Topic | Key Point |
|---|---|
| Type URN | <package>:<module>:<type>, module usually index |
| Constructor | super(type, name, {}, opts) then children then registerOutputs() |
| Child resources | Always { parent: this }, derive name from ${name}-suffix |
| Args interface | Wrap in Input<T>, no unions, no functions, flat structure |
| Outputs | Public readonly Output<T> properties, expose only essentials |
| Defaults | Use ?? operator to apply sensible defaults in constructor |
| Composition | Lower-level components composed into higher-level ones |
| Multi-language | PulumiPlugin.yaml + entry point; consumers use pulumi package add |
| Distribution | Private registry, git tags, package managers, or public Pulumi Registry |
Related Skills
- pulumi-best-practices: General Pulumi patterns including Output handling, secrets, and aliases
- pulumi-automation-api: Programmatic orchestration for integration testing and multi-stack workflows
- pulumi-esc: Centralized secrets and configuration for component deployments
References
- https://www.pulumi.com/docs/iac/concepts/resources/components/
- https://www.pulumi.com/docs/iac/using-pulumi/pulumi-packages/
- https://www.pulumi.com/docs/idp/get-started/private-registry/
- https://www.pulumi.com/docs/iac/concepts/inputs-outputs/
- https://www.pulumi.com/docs/iac/concepts/resources/options/aliases/
Query the Pulumi Context API
The Context API answers questions about an organization's cloud infrastructure as a graph: what exists, what depends on what, what a change would affect. It covers resources found through Pulumi Discovery, not just Pulumi-managed ones.
Prefer it over Resource Search whenever the question involves relationships. Resource Search finds individual resources but cannot follow edges, so answering "what depends on X" with repeated searches is slow and usually incomplete.
Public preview, for organizations on the Enterprise and Business Critical
editions, and a role granting resources:search (the default Member and Admin
roles do).
First: is a graph tool already in the session?
If one is — graph_query and get_graph_schema, under whatever prefix the
server registers them — call it and skip Steps 1 and 2. Compose the selector
from the graph_query tool's own description, which carries the grammar; the
tool resolves the organization and credentials itself and drains pagination for
you. When that description is not enough, get_graph_schema returns the live
field vocabulary and limits, and will serve the full Step 1 primer when asked
for it. Step 3 still governs what you do with the result.
Steps 1 and 2 are the path for an agent that has a shell and no such tool.
Step 1: fetch the primer, always
Needs Pulumi CLI v3.243.0 or newer and an active pulumi login.
pulumi api GetGraphQuerySchema --output=markdown
This returns a self-contained guide to composing selectors — vocabulary, edge types, engine caps, worked examples, pagination, completeness rules, the gates that deny a query, and the traps that produce a confident wrong answer instead of an error. It is served by the deployment that answers your queries, so it is the contract, and it moves between schema versions. This skill bootstraps you to it and stops there; everything below defers to it. Fetch it fresh in every session — a primer remembered from earlier may describe a schema this deployment no longer serves.
The operation takes no organization; one schema covers every org the login can
reach. --output=json on it returns the same contract as a machine-readable
payload, useful for reading limits or fieldValues programmatically, but
compose from the markdown.
Read it in full — never truncate it with head, tail, or a byte cap. A
clipped primer means malformed selectors and rejected queries.
If this call fails
You have no primer yet, so handle it here rather than looking it up there:
| Response | Meaning |
|---|---|
401 Unauthorized | no active pulumi login, or an expired token |
404 Not Found, detail-free | a wrong path, or a deployment without the endpoint |
503 Service Unavailable | transient — retry |
Entitlement gates are per-organization, so they cannot appear on this call —
they surface in Step 2, by which point the primer's "When it denies you" table
is in hand. If pulumi api doesn't know GetGraphQuerySchema at all, that is
not a gate: run pulumi api list --refresh-spec to refresh the cached spec,
then retry the fetch.
Step 2: query
pulumi api GraphQuery -F orgName=<org> --input selector.json
The body is a JSON selector, not query text. Compose it from the primer you just read, not from memory or from a grammar you recall from another session.
Name the org explicitly. Left off, -F orgName resolves from the selected
stack or the default org, which is often an individual account with no
entitlement; pulumi whoami -v lists every organization the login can reach.
A denial here names its gate — the primer's "When it denies you" table says
which are worth retrying and which to report to the user.
Step 3: apply the primer's completeness rules before answering
Every response carries fidelity signals — currently meta.resultMode,
meta.visibility, and pageInfo.continuationToken; the primer names the
authoritative set. Read the primer's rules for them and follow them; the
remedies differ per signal and a stale paraphrase here would be worse than
none.
What matters most: a completeness claim needs all of them clean. Impact analysis, "nothing depends on this", an exhaustive cleanup list, a total across groups — none of these survive a truncated result, a trimmed traversal, or an undrained page. When you can't get there, say what the answer does cover.
Scope of the graph
Resources, stacks, and the relationships between them, trimmed to the stacks and accounts the caller can see. The primer's "What it cannot answer yet" section is the live boundary — check it before concluding a question is unanswerable, and reach for a different API rather than approximating one of those gaps with a graph query.
One boundary worth knowing up front, because it decides which API to use: the graph returns a schema-declared subset of fields per node type, not full resource property bags. The primer lists which fields each node type can match on and which it can return; when the question needs the property values themselves, they come back from Resource Search.
Human-readable reference: Context API overview and query guide.
Create a Pulumi Agent
Create a saved agent definition. Starting a task or configuring automation is a separate action.
Discover and resolve
Confirm the target organization and current login with pulumi whoami -v. Do not infer the organization from the current stack or repository. Read CLI contract for operation discovery, request fields, and integration selection.
Check existing agents before choosing a name. If the name is taken, show the existing agent and ask how to proceed.
Resolve these settings from the user's request and project context:
- Name, display name, responsibility, resource scope, and expected output.
- Saved instructions, including relevant team requirements. These replace organization AI preferences, so include requirements the agent must retain.
- An organization role the caller may assign. Check its grants and exclude built-in Admin and Billing Manager roles. Instructions and deprecated
permissionModedo not restrict authority. - Connected MCP integrations. Set the selection explicitly, including
[]for none; omission inherits all organization integrations. - Approval mode. If unresolved, propose manual approval and explain that unattended runs may wait for a person.
Local files and uncommitted changes are not automatically available to the remote agent. Check that it can reach the repositories and connections needed for its responsibility. MCP selection does not control separate CLI credentials.
Ask only for missing choices. If a required API is unavailable or access cannot be verified, save a local draft with the known settings, complete instructions, and remaining questions. Explain the blocker without changing the requested access.
Tell the user, then create
Show the complete configuration and literal instructions that will be saved:
Organization:
Name and display name:
Responsibility and resource scope:
Role:
MCP integrations:
Approval mode:
Saved instructions:
[complete text]
Keep the instructions within the requested responsibility and resource boundary. For work outside that boundary, tell the agent to report the dependency and request a revised responsibility.
Submit exactly the displayed values using the request-file workflow in CLI contract. If creation is already authorized and all choices are resolved, proceed without asking again.
Verify the result
Read the returned agent ID and check active roster membership. Compare the saved name, display name, purpose, instructions, role, integrations, and approval mode with the proposal.
If values differ, report the saved result and the mismatch before making another change. Do not recreate or delete the agent as a rollback.
If the create response is lost, check the agent list and retrieve candidates before retrying. Follow all pages. A matching name alone does not prove the agent came from this request; use returned resource or request identifiers where available. If the outcome remains uncertain, report it rather than creating another agent. Do not treat a failed or incomplete listing as proof that creation failed.
Return the verified agent ID, organization, and saved configuration. Creation confirms the settings, not that the agent has successfully completed a task.
Address automation
After creation, ask unless the user already supplied a preference:
“Would you like to set up automation for this agent: a schedule, an event trigger, or no automation for now?”
An unanswered automation choice does not block agent creation. Leave that choice pending if no answer is available.
If the user requested a schedule or trigger, continue with Configure automation. If they declined, acknowledge manual invocation without asking again. Keep the created agent if automation setup fails.
For an explicitly requested first task, read Requested immediate task. A one-time task does not answer the recurring-automation question.
Load automation details only when needed: API contract for commands, webhook secrets before webhook creation, and recovery after an uncertain or mismatched result.
Debug a failed Pulumi operation
A Pulumi operation has failed. Find what caused it and fix it. The user usually points you at it, so start by working out which operation to debug, and confirm it with the user before doing anything else. Pulumi recorded the error when the operation failed, so once you know which operation it is you can read the error from that record without running anything again.
The commands below reach Pulumi Cloud with pulumi api, a subcommand of the Pulumi
CLI that you run in your shell. Each one targets a stack by the explicit
{orgName}/{projectName}/{stackName} path you pass it, so you do not need that
stack selected locally to read its record. Selecting the stack matters later, when
you go to apply a fix.
Start from the operation the user gave you
The user usually supplies the operation as a set of fields: the org, project, stack,
and update version (or preview id) — most often stated in prose, for example "debug
update 161 of vvm-dev". You need these to address the API: {orgName},
{projectName}, {stackName}, and the version or preview id.
Fill any missing field from context. Take the org, project, or stack from the
currently selected stack (pulumi stack --show-name, pulumi stack ls) or
Pulumi.yaml. A missing version means the most recent update on that stack.
Briefly confirm which operation you landed on, its version or preview id and the stack, before reading further. Keep it lightweight; they already told you.
Read what failed
A failed update and a failed preview both record engine events, and the error is in the diagnostic messages inside those events. Using the fields you settled on above, fetch the events and pull the messages out.
For a failed update, use the update path with the version number:
pulumi api /api/stacks/{orgName}/{projectName}/{stackName}/update/<version>/events \
| jq -r '.events[].diagnosticEvent | select(. != null) | "[\(.severity)] \(.message)"' \
| sed 's/<{%reset%}>//g'
For a failed preview, use the preview path with the preview id:
pulumi api /api/stacks/{orgName}/{projectName}/{stackName}/preview/<preview-id>/events \
| jq -r '.events[].diagnosticEvent | select(. != null) | "[\(.severity)] \(.message)"' \
| sed 's/<{%reset%}>//g'
Read every message, not only the ones tagged severity == "error". A provider
error carries that error tag, but a program error, which is the common case when
a preview fails, arrives as a stderr diagnostic tagged info#err. The trailing
sed strips terminal color codes that Pulumi embeds in the text, which otherwise
show up as <{%reset%}>.
Find the cause and where the fix belongs
An operation can fail with errors from more than one resource, so read all of the diagnostics first, then work through each error. Trace every error back to the resource that raised it (its URN and type), to where that resource is declared in the program, and to the inputs that feed it.
The error text tells you what kind of problem it is, and that points to where the fix belongs. A Pulumi fix lands in one of three places, and naming the right one keeps you from editing code that was never the problem.
- The program. The code is wrong: a bad reference, a wrong type, an input the provider rejected, or a value used before it had resolved. This is what a failed preview usually reports, because the plan could not be built. Fix it by editing the code.
- The state. The code is correct, but the stored state and the real cloud
resources disagree. Reconcile drift with
pulumi refresh, and bring a resource that already exists outside the state under management withpulumi importrather than recreating it. Note that an operation which failed partway through applying may have already changed some resources, so check the current state before you decide. - The environment. The problem is outside Pulumi: credentials, permissions, OIDC, or a quota. Fix the role, the ESC environment, or the capacity that the provider rejected, rather than the resource code.
When a diagnostic is empty or too thin to act on, the real error usually isn't in the record — it's in the log of whatever the resource shelled out to. Read it there. If reaching it needs access you don't have (a token, a run, a not-found), stop and tell the user what you're blocked on and the one thing you need from them.
Fix the cause
Make the smallest change that addresses the root cause. How you confirm the fix, and how you deliver it, whether as a local edit or as a pull request, follow your mode's workflow, not this skill.
If the user didn't say which operation
When the user gives you nothing to go on, debug their most recent operation on the stack. The update list does not record who ran each update, so find it through the API:
- Run
pulumi whoamito get the current user's login. - Read the latest update and who requested it with
pulumi api /api/stacks/{orgName}/{projectName}/{stackName}/updates/latest, and compare itsrequestedBy.githubLoginto the login from step 1. - If they match, that update is the one to debug. If they do not, walk back one
version at a time with
pulumi api /api/stacks/{orgName}/{projectName}/{stackName}/updates/<n>untilrequestedBy.githubLoginmatches the user.
Tell the user which operation you landed on, its version, kind, and result, and confirm it is the one they mean before going further.
Pulumi ESC (Environments, Secrets, and Configuration)
Pulumi ESC is a centralized service for managing environments, secrets, and configuration across cloud infrastructure and applications.
What is ESC?
ESC enables teams to:
- Centralize secrets and configuration in one secure location
- Compose environments by importing and layering configuration
- Generate dynamic credentials via OIDC for AWS, Azure, GCP
- Integrate external secret stores (AWS Secrets Manager, Azure Key Vault, Vault, 1Password)
- Version and audit all configuration changes
- Control access with fine-grained RBAC
Essential CLI Commands
# Create a new environment
pulumi env init <org>/<project-name>/<environment-name>
# Edit environment (opens in editor)
pulumi env edit <org>/<project-name>/<environment-name>
# Set values
pulumi env set <org>/<project-name>/<environment-name> <key> <value>
pulumi env set <org>/<project-name>/<environment-name> <key> <value> --secret
# View definition (secrets hidden)
pulumi env get <org>/<project-name>/<environment-name>
# Open and resolve (reveals secrets)
pulumi env open <org>/<project-name>/<environment-name>
# Run command with environment
pulumi env run <org>/<project-name>/<environment-name> -- <command>
# Link to Pulumi stack
pulumi config env add <project-name>/<environment-name>
Key Concepts
Command Distinctions
pulumi env get: Shows static definition, secrets appear as[secret]pulumi env open: Resolves and reveals all values including secrets and dynamic credentialspulumi env run: Executes commands with environment variables loadedpulumi config env add: Only takes the / portion
Environment Structure
Environments are YAML documents with reserved top-level keys:
imports: Import and compose other environmentsvalues: Define configuration and secrets
Reserved sub-keys under values:
environmentVariables: Map values to shell environment variablespulumiConfig: Configure Pulumi stack settingsfiles: Generate files with environment data
Basic Example
imports:
- common/base-config
values:
environment: production
region: us-west-2
dbPassword:
fn::secret: super-secure-password
environmentVariables:
AWS_REGION: ${region}
DB_PASSWORD: ${dbPassword}
pulumiConfig:
aws:region: ${region}
app:dbPassword: ${dbPassword}
Reading Another Stack's Outputs
Use the fn::open::pulumi-stacks provider to consume another stack's outputs. The
stacks and network keys below are arbitrary names you choose. Once the function
resolves, it replaces stacks.network with the named stack's outputs — so the
output names (vpcId, subnetIds) do not appear in the static YAML; they come from
whatever the producer stack exports. Two things are easy to get wrong:
- The stack is named by a single project-qualified
stack: <project>/<stackName>field — not separateprojectName/stackNamefields. - Outputs resolve directly under the stack name — there is no
.outputs.level (use${stacks.network.vpcId}, not${stacks.network.outputs.vpcId}).
Example — replace the stack name and output names with your own:
values:
stacks:
fn::open::pulumi-stacks:
stacks:
network: # arbitrary local name for the referenced stack
stack: my-project/dev # producer stack to read outputs from
pulumiConfig:
# vpcId / subnetIds are whatever the producer stack exports; after the function
# resolves they are available directly under `stacks.network` (no `.outputs.`).
vpcId: ${stacks.network.vpcId}
subnetIds: ${stacks.network.subnetIds}
Full schema: https://www.pulumi.com/docs/esc/providers/pulumi-stacks/
Viewing an Environment in the Pulumi Cloud Console
The console URL for an environment is
https://app.pulumi.com/<org>/esc/<project>/<environment>. The route segment is
esc, not environments.
Working with the User
For Simple Questions
If the user asks basic questions like "How do I create an environment?" or "What's the difference between get and open?", answer directly using the information above.
For Detailed Documentation
When users need more information, use the web-fetch tool to get content from the official Pulumi ESC documentation:
- Complete YAML syntax and functions → https://www.pulumi.com/docs/esc/environments/syntax/
- Provider integrations (AWS, Azure, GCP, Vault, 1Password):
- AWS: https://www.pulumi.com/docs/esc/integrations/dynamic-login-credentials/aws-login/
- Azure: https://www.pulumi.com/docs/esc/integrations/dynamic-login-credentials/azure-login/
- GCP: https://www.pulumi.com/docs/esc/integrations/dynamic-login-credentials/gcp-login/
- Short-term credential (OIDC) providers: https://www.pulumi.com/docs/esc/integrations/dynamic-login-credentials/
- Dynamic secret providers: https://www.pulumi.com/docs/esc/integrations/dynamic-secrets/
- Pulumi stack outputs (
fn::open::pulumi-stacks): https://www.pulumi.com/docs/esc/providers/pulumi-stacks/ - All providers (index): https://www.pulumi.com/docs/esc/providers/
- Getting started guide → https://www.pulumi.com/docs/esc/get-started/
- CLI reference → https://www.pulumi.com/docs/esc/cli/commands/
- Prefer using the
pulumi envsubcommands overescCLI.
- Prefer using the
Use the web-fetch tool with specific prompts to extract relevant information from these docs.
For Complex Tasks
When helping users:
- Understand the goal: Are they setting up new environments, migrating from stack config, or debugging?
- Check existing setup: Use
pulumi envcommands to list environments or read definitions - Fetch relevant documentation: Use the web-fetch to get specific examples or syntax from the official docs
- Provide step-by-step guidance: Walk through the process with specific commands
- Validate: Help them test with
pulumi env getorpulumi previewa. Only usepulumi env openwhen the full resolved values are needed, but use cautiously as it reveals secrets.
Example: Helping with AWS OIDC Setup
User: "How do I set up AWS OIDC credentials in ESC?"
1. Use the web-fetch tool to get AWS OIDC documentation from "https://www.pulumi.com/docs/esc/integrations/dynamic-login-credentials/aws-login/"
2. Provide the user with the configuration
3. Ask the user if they have a pre-defined role or need one created for them
4. Set up as much of the environment as possible, then guide them through any steps that you can't do for them
5. Help them test with `pulumi env get` or `pulumi env open` if necessary
Common Workflows
Creating an Environment
pulumi env init my-org/my-project/dev-config
# Edit environment (accepts new definition from a file, better for agents, more difficult for users)
pulumi env edit --file /tmp/example.yml my-org/my-project/dev-config
Linking to Stack
pulumi config env add my-project/dev-config
pulumi config # Verify environment values are accessible
API Access (Rare)
Always prefer CLI commands. Only use the API when absolutely necessary (e.g., bulk operations, automation).
Available API endpoints include:
GET /api/esc/environments/{orgName}- List environmentsGET /api/esc/environments/{orgName}/{projectName}/{envName}- Read environment definitionGET /api/esc/providers?orgName={orgName}- List available providers
Use the pulumi api CLI subcommand to make requests when needed, e.g. pulumi api /api/esc/providers -F orgName={orgName}.
Best Practices
- Always use
fn::secretfor sensitive values - Prefer OIDC over static keys
- Use descriptive names like
<org>/my-app/production-awsnot<org>/app/prod - Layer environments: base → cloud-provider → stack-specific
- Verify that
pulumi configshows expected values after linking an environment to a stack - Prefer using
pulumi env runfor commands needing environment variables - Only use
pulumi env openwhen absolutely necessary, as it reveals secrets - Before using an existing environment, verify its account and role and get the user's confirmation; never select one by name alone. Never link an environment to a stack (
pulumi config env add) without explicit user confirmation, and never pass--yes.
Handling Credential Errors and Existing Environments
Credential errors
Start with the remediation in the error message. An expired or missing login usually just needs the user to re-authenticate, and most providers name the fix or the command:
- AWS SSO:
Failed to refresh cached SSO credentials. Please refresh SSO login.→aws sso login - AWS temporary credentials:
ExpiredToken: The security token included in the request is expired→ refresh the session or keys - Azure: re-run
az login - GCP: re-run
gcloud auth application-default login - Pulumi Cloud (401 / unauthorized):
pulumi login
Relay the fix and have the user retry. If the error does not name a remediation
(for example a bare Unable to locate credentials, or an access-denied that may
mean the wrong account or profile rather than an expired login), don't guess —
identify how the project authenticates (provider config, the active profile, any
linked ESC environment) and address that.
Changing where the project gets its credentials (adding or switching an ESC environment, editing provider config) is a deliberate change, not a reflexive fix for an expired session. Do it only if the user wants it, and follow the rules below.
Never select an existing environment by name
Do not pick an environment because its name looks relevant (*-aws-oidc,
*-creds, *-workshop, etc.). A matching name does not mean it is the right
one or that it belongs to this user's work.
Before proposing any existing environment:
- Inspect it with
pulumi env get <org>/<project>/<env>. - Confirm the target it authenticates to matches where the user's resources
actually live. An OIDC
roleArnnames a specific AWS account — if it points at a different account (a shared workshop, an instructor role, another team), it is the wrong environment and will run operations against the wrong account or fail. - Show the candidate to the user and confirm it is theirs and correct before using it.
Linking an environment changes which credentials operations use — confirm first
pulumi config env add edits the stack config (Pulumi.<stack>.yaml) and
changes the credentials Pulumi operations run under. Never run it without
explicit user confirmation, and never pass --yes to skip that confirmation.
Tell the user what will change and let them decide.
Verify before claiming it worked
After linking, resolved credential values often show as [unknown] until the
environment is opened or run. Do not claim the error is fixed or that the next
operation will succeed until you have verified it — check pulumi config, and
confirm the credentials resolve to the expected account before declaring success.
Quick troubleshooting
- "Environment not found": Check permissions with
pulumi env ls -o <org> - "Secret decryption failed": Use
pulumi env opennotpulumi env get - "Stack can't read values": Verify
pulumi config env lsto ensure the stack is listed.- Ensure the environment is referenced only by the project-name/environment-name format.
- Get the specific environment definition with
pulumi env get <org>/<project-name>/<environment-name>. - Verify the
pulumiConfigkey exists and is nested under thevalueskey.
Pulumi
Pulumi is a tool for creating and managing cloud infrastructure: virtual machines, storage, Kubernetes clusters, databases, anything from any provider. You write code or run CLI commands, Pulumi previews what would change, then applies it. This skill walks three levels of working with Pulumi, from a single CLI command up to a project with policies and scheduled drift. Start at the smallest level that fits the task.
The three levels
Level 1 is pulumi do, a CLI for direct CRUD against any provider, with no project files or programming language. Level 2 is a Pulumi project in Python, TypeScript, Go, C#, or Java, used once the work involves multiple related resources, loops or conditionals, reusable abstractions, or environment-specific variants. Level 3 layers Pulumi Cloud onto a project for ESC credentials and configuration, policy, hosted execution, drift detection, schedules, and audit.
| Level | Surface | When to use |
|---|---|---|
| 1 | pulumi do | Single resource or multi-vendor bootstrapping |
| 2 | Pulumi project (Python, TS, Go, C#, Java) | Multiple resources, abstractions, environments |
| 3 | ESC, policy, deployments, drift, schedules | Governance, secrets, scheduled and hosted runs |
When the directory has no existing Pulumi project, a user asking to create a single bucket is a Level 1 task; do not scaffold a new project for it. A request to provision a VPC with subnets and a Kubernetes cluster is Level 2 from the start. A request for nightly drift detection on an existing stack is Level 3.
Converting existing infrastructure code from another tool (Terraform, CloudFormation, CDK, ARM, or Bicep) is a separate path: route straight to the migration skills listed in the table at the end, independent of the level model.
Picking the right level requires knowing what is already in the directory. If you can inspect the filesystem, do so. If you cannot (restricted agent contexts), ask the user before any Pulumi command runs whether there is an existing Pulumi project in the directory. Don't run a Pulumi command to find out: commands that would otherwise require a login silently provision a new agent account, parallel to one the user may already own.
Level 1: pulumi do for direct resource operations
Use pulumi do for one-shot resource operations against any provider. Examples: create a Cloudflare DNS record, create an S3 bucket for backups, create a GCP storage bucket for image uploads, stand up an Azure virtual machine, configure a Datadog monitor, register a Vercel deployment's domain in Cloudflare DNS. There is no project file, directory layout, or programming language involved.
pulumi do is stateless. Each command runs once and operates directly against the cloud provider: create provisions a resource and prints its cloud-side identifier, while read, patch, and delete act on a resource addressed by that identifier. Nothing is written to a Pulumi state file, so there is no resource graph and no ${...} wiring between commands. To connect two resources, capture an output from one command and pass it as a literal value to the next.
When a Pulumi project (Pulumi.yaml) already exists in the directory, do not use pulumi do to mutate resources the project manages. Changes go through the program instead.
First invocation and signup
The canonical invocation is npx pulumi <command>. It works on any machine with Node.js installed and requires no prior Pulumi setup. If pulumi is on PATH, the npx shim defers to it; otherwise the command runs from the npm registry. To confirm the CLI is available before any command that would trigger signup, run npx pulumi version; it does not touch Pulumi Cloud. The resource verbs (create, read, patch, delete, list) require CLI v3.243.0 or newer, where pulumi do gained resource support. npx pulumi fetches a current release, but a pulumi already on PATH may be older, so confirm the version is recent.
pulumi do writes no Pulumi state, but it resolves provider packages through the Pulumi registry, which can reach Pulumi Cloud. In an agent context without saved credentials, that means a first pulumi do may silently provision an ephemeral agent account and print a claim banner.
The CLI prints one line to stderr noting the new account and a claim URL. Surface that claim URL to the user immediately and again in the final response, since it is the only way the user takes ownership of the account; a session that ends without it leaves resources stranded in the cloud. The access token expires in 3 days and the claim URL stays valid for 30 days; Pulumi Cloud sets both, so surface whatever validity the banner reports.
If the account-creation banner appears more than once in the same session, credentials may not have been cached. Agent credentials are written to /tmp/.pulumi/credentials.json and the claim metadata to /tmp/.pulumi/agent-claim.json, but the claim URL itself is printed in the banner, not stored in those files. Capture it from each banner and surface the most recent one before doing more work.
If authentication fails, ask the user to run pulumi login. Never fall back to pulumi login --local or set PULUMI_CONFIG_PASSPHRASE; both silently change the user's setup.
Provider credentials are separate from Pulumi Cloud credentials. pulumi do reads them from the same environment variables the provider's native CLI uses (AWS_PROFILE, CLOUDFLARE_API_TOKEN, GOOGLE_APPLICATION_CREDENTIALS). If they aren't set, ask the user before invoking commands that call out to the cloud. If a command fails with a provider authorization error, look up that provider's required credentials or configuration and have the user supply them rather than guessing at the cause. ESC (Level 3) is the durable place to keep them once a project exists.
Command shape
Here are two invocations: create an S3 bucket, then read it back by the cloud id the create printed.
npx pulumi do aws:s3:Bucket create --yes --bucket my-data
npx pulumi do aws:s3:Bucket read my-data
The shape is:
pulumi do <pkg:mod:type> create [flags]
pulumi do <pkg:mod:type> read|patch|delete <id> [flags]
pulumi do <pkg:mod:type> list [flags]
<pkg>is the provider package (aws,azure-native,gcp,cloudflare,kubernetes, etc.).<mod>is the module within the package (compute,storage,dns); optional when the module isindex. For example,cloudflare:index/record:Recordinvokes ascloudflare:Record.<type>is the resource type (VirtualMachine,Bucket,Record).<id>is the cloud provider's identifier for an existing resource, the valuecreateprints asid.createandlisttake no positional argument;read,patch, anddeleteeach take exactly one<id>.[flags]set resource properties, or you pass a body file via--input-file <file>. See Property input below for how flags and files combine, and which values must come from a file.
There is no Pulumi logical name to choose. The CLI derives an internal name from the resource type, and you address existing resources by their cloud id.
Verbs
createprovisions the resource and prints its properties, including the cloudid, as JSON. Capture thatidto read, patch, or delete the resource later. Pass--yesin non-interactive contexts;readandlistnever need it.read <id>fetches the resource's current state from the provider and prints it as JSON. It writes nothing.patch <id>reads the resource's current inputs, overlays the top-level properties you pass as flags or in--input-file, and updates the resource in place. The overlay is shallow: properties you do not mention are left as they are.patchonly updates; it cannot replace a resource, so a change that would require replacement fails rather than recreating it. The command makes you confirm by typing the resource id; pass--yesto skip that prompt in non-interactive contexts.delete <id>removes the resource from the cloud. This is irreversible. Get explicit user confirmation for the specific resource before invoking; use--yesonly after that confirmation, not as a default for non-interactive runs.
pulumi do also supports two non-CRUD operations. pulumi do <pkg:mod:type> list [flags] enumerates existing instances of a resource type, but only for types that implement listing. Native providers support it broadly. The Terraform-bridged providers (aws, azure, gcp) support it too, but coverage varies by resource type, so a type that lacks it rejects the verb. pulumi do <pkg:mod:function> [flags] invokes a stateless function the provider exposes alongside its resources.
Property input
Properties come from per-property flags, a body file, or both; flags overlay the body. Flags set top-level scalar properties only, so nested or structured values (tags, nested blocks) must come from the body file. The body defaults to PCL, written as flat name = value attributes; pass --input yaml (which needs the YAML converter plugin) to use YAML instead.
cat > bucket.pcl <<'EOF'
bucket = "my-data"
tags = {
Environment = "dev"
}
EOF
npx pulumi do aws:s3:Bucket create --yes --input-file bucket.pcl
Before authoring properties for a resource new to this session, run npx pulumi package info <pkg> --module <mod> --resource <Type> to list its inputs and outputs with descriptions, scoped to that one resource. Reach for npx pulumi package get-schema <pkg> only when you need the full machine-readable schema with the nested type definitions info does not expand; for a large provider it runs to tens of MB, so do not read it whole. Property names are camelCase (flags are the kebab-case form). To discover names, run npx pulumi package info <pkg> with no module to list its modules and resources, or browse the catalog at https://www.pulumi.com/registry/.
Connecting resources
pulumi do keeps no state and has no resource graph, so there is no ${...} reference syntax between commands. To feed one resource's output into another, read a field from the first command's JSON output and pass it as a literal flag to the next.
# create prints JSON containing "id": "vpc-0abc123"
npx pulumi do aws:ec2:Vpc create --yes --cidr-block 10.0.0.0/16
# pass that id to the subnet
npx pulumi do aws:ec2:Subnet create --yes --vpc-id vpc-0abc123 --cidr-block 10.0.1.0/24
The same pattern connects resources across providers. Here a value from the random provider feeds an AWS resource name, a common way to get globally-unique names.
# RandomPet prints JSON containing "id": "artistic-bull"
npx pulumi do random:RandomPet create --yes
# use it in the bucket name
npx pulumi do aws:s3:Bucket create --yes --bucket assets-artistic-bull
When a command needs a value the chain does not produce, like an existing resource id or an API zone id, get it from a provider function, a list where the provider supports it, or the user. Do not invent it.
Output
By default, create, read, and patch each write one JSON object to stdout for the affected resource. Check the exit code on every invocation.
{
"id": "my-data",
"bucket": "my-data",
"arn": "arn:aws:s3:::my-data"
}
The resource's properties are top-level, alongside an id field holding the cloud identifier. There is no nested outputs object, no urn, and the type token you passed in is not echoed back. list instead writes a JSON array of {id, name} entries, and a function writes its declared result shape.
Graduating to Level 2
Eject to Level 2 when one-shot commands stop fitting. Because pulumi do leaves no Pulumi state behind, the resources it created are ordinary cloud resources, so you adopt them into a project with pulumi import. From inside a Pulumi project, run pulumi import with each resource's full type token, a logical name, and the cloud id that create returned. Import records the resource in the stack's state and, by default, generates its program code.
# the import type token is the full pkg:mod/type:Type form, not pulumi do's short aws:s3:Bucket
npx pulumi import aws:s3/bucket:Bucket assets my-data
Move the generated code into your program, then manage the resource there instead of with pulumi do. To adopt several at once, pass them in a bulk --file.
Level 2: full infrastructure as code
Level 2 is a Pulumi project: code in Python, TypeScript, Go, C#, or Java that describes a set of related resources and their dependencies. Start here when the task involves multiple related resources, loops or conditionals, reusable abstractions, or environment-specific variants. It is also the right level when ad-hoc work at Level 1 has grown past what a few CLI invocations should carry. Match the user's existing codebase language when one is present; default to TypeScript otherwise.
Before writing any non-trivial program, use skill pulumi-best-practices, which covers Output<T> and apply() usage, passing outputs directly as inputs, component structure and parenting, secrets hygiene, and safe refactoring with aliases.
Bootstrapping
The quickest way to start a project is with a template, though you can scaffold one by hand if you prefer:
npx pulumi new aws-typescript
npx pulumi new gcp-go
Templates set up the working directory, Pulumi.yaml, an initial stack, the language's package manifest, and a starter program. Browse the full catalog with npx pulumi template list, or filter by name with npx pulumi template list --name <filter>.
Core lifecycle
The lifecycle commands work the same across languages:
npx pulumi preview # show what would change
npx pulumi up # apply
npx pulumi refresh # reconcile state with cloud reality
Always run preview before up; it shows what will change and costs nothing.
pulumi destroy tears down every resource in the stack. The Pulumi docs call it "generally irreversible"; never invoke without explicit user confirmation of the stack name.
Stacks and config
A stack is an isolated instance of a project. A common pattern is one stack per environment, named dev, staging, and prod.
npx pulumi stack init dev
npx pulumi stack select prod
npx pulumi config set aws:region us-west-2
npx pulumi config set --secret dbPassword "..."
Read configuration values from inside the program with the SDK's Config object; the exact operation names vary by language, so refer to the per-language examples at https://www.pulumi.com/docs/iac/concepts/config/#code. Use skill pulumi-best-practices for Output<T> / apply() usage and broader secrets hygiene.
A stack only touches resources tracked in its state, so removing a resource from your program causes pulumi up to delete it from the cloud. Set protect: true on anything you cannot afford to lose.
For the full IaC reference, see https://www.pulumi.com/docs/iac/.
Level 3: governance and operations
Level 3 uses Pulumi Cloud for more than state. ESC holds the credentials for every provider a project touches and brokers them into runs and shells. Policy enforcement, hosted execution, drift detection, scheduled operations, and audit round out the surface.
ESC: environments, secrets, configuration
An ESC environment composes secrets and configuration from cloud secret managers, OIDC-vended credentials, and other ESC environments into a single resolved bundle that programs and stacks consume.
npx pulumi env init my_org/aws/prod
npx pulumi env set my_org/aws/prod aws.region us-west-2
npx pulumi env open my_org/aws/prod
npx pulumi env run my_org/aws/prod -- aws s3 ls
Where the provider supports it, vend cloud credentials through OIDC rather than static keys in environment YAML. OIDC trust policies, IdP registration, and rotation patterns live in pulumi-esc; use skill pulumi-esc rather than invent ESC YAML by hand.
env open resolves and prints live credentials, so avoid capturing its output into logs or transcripts. Prefer env run -- <command>, which injects the credentials into the child process rather than printing them.
Policy
Pulumi Policies runs policy packs against the resource graph at preview and update time. A policy can reject the deployment, require approval, or annotate resources with findings; enforcement happens before any cloud API call.
npx pulumi policy new aws-typescript # scaffold a pack from a policy template
npx pulumi policy publish my_org # the pack name comes from PulumiPolicy.yaml
npx pulumi policy enable my_org/<pack-name> latest --policy-group production
Policies are written in TypeScript or Python, the same languages you use for programs.
Deployments
Pulumi Deployments runs pulumi up, preview, and destroy in Pulumi-managed infrastructure rather than on the local machine. Use it for CI without maintaining your own runners and for any operation that needs to run server-side.
npx pulumi deployment run update --stack my_org/proj/prod
The target stack must already exist; a wrong --stack value can prompt to create a new stack rather than fail.
Drift detection and scheduled operations
Drift detection compares stack state against the cloud and reports anything that has diverged. For an ad-hoc local check, run a refresh in preview-only mode. Pulumi Cloud schedules operations on a cron (times are UTC), including a purpose-built drift kind.
# Ad-hoc local drift check
npx pulumi refresh --preview-only
# Scheduled drift detection (detection only)
npx pulumi stack schedule new --kind drift --cron "0 0 * * *"
# Scheduled secret rotation for an ESC environment
npx pulumi env schedule new my_org/aws/prod --cron "0 0 1 * *"
A schedule is standing automation that keeps running after the session ends, so confirm the operation, cadence, and stack with the user before creating one. Two kinds act without a human in the loop: --kind drift --auto-remediate runs pulumi up on detected drift, and --kind ttl destroys the stack at a set time. Default to detection-only unless the user asks for remediation.
Further reading
- ESC: https://www.pulumi.com/docs/esc/
- Pulumi Policies: https://www.pulumi.com/docs/insights/policy/
- Deployments: https://www.pulumi.com/docs/pulumi-cloud/deployments/
- Drift detection: https://www.pulumi.com/docs/pulumi-cloud/deployments/drift/
Reference
When you are uncertain about a CLI flag, command shape, or resource property, look it up rather than guess. npx pulumi <command> --help documents every flag and subcommand from the CLI itself. The full reference, provider catalog, and conceptual documentation live at https://www.pulumi.com/docs.
Routing to specialized skills
When the work moves into territory another skill covers in depth, hand off to that skill rather than reinvent its content.
| Skill | Load when |
|---|---|
pulumi-best-practices | Writing any non-trivial Level 2 program |
pulumi-component | Packaging or consuming ComponentResource abstractions |
pulumi-esc | Defining ESC environments, OIDC trust policies, or rotation |
pulumi-automation-api | Embedding Pulumi inside another program (IDP, custom CI) |
provider-upgrade | Upgrading a provider package version in a stack without unintended changes |
package-usage | Auditing which stacks across the org use a package and at what versions |
pulumi-context-api | Relationship and impact-analysis questions across the org's infrastructure graph |
pulumi-terraform-to-pulumi, pulumi-cdk-to-pulumi, cloudformation-to-pulumi, pulumi-arm-to-pulumi | Migrating from those tools |
An agent only sees the skills the user installed, so a referenced skill may not be present. pulumi-best-practices, pulumi-component, pulumi-esc, pulumi-automation-api, provider-upgrade, package-usage, and pulumi-context-api ship in the same pulumi plugin as this skill, so they are available whenever this one is. The migration skills install separately through the pulumi-migration plugin and may be absent. When a referenced skill is available, load it. When it is not, do not stall or treat the gap as an error: continue with the guidance in this skill and the docs at https://www.pulumi.com/docs, and tell the user which skill or plugin covers the work in depth.
Set up agent automation
An automation runs a saved Pulumi Agent on a schedule or in response to events. Creating an automation does not create a new agent or start a one-time task.
Create a schedule or event trigger
Read Configure automation.
Confirm the organization, saved agent, per-run instructions, schedule or event, and CLI connections. Reuse choices the user already supplied and ask about anything needed to complete the request. If the user declined automation, leave the agent available for manual invocation.
Check the agent's pausedAt field. A paused agent starts no new runs even when its automation is active. Setting up or resuming an automation must not resume the agent.
Use the API contract for operations and request fields. For webhooks, read Webhook secrets before creating the automation.
Pause or resume an existing automation
- Discover and describe the read and pause operations in the API contract. Read the automation by organization and ID.
- For resume, verify the bound agent, its pause state, and the caller's invocation access. A missing or unreadable agent does not prevent an authorized automation pause.
- If the automation already has the requested state, report it. Otherwise call
UpdateAgentAutomationV2Pausedwith only the requestedpausedvalue. - Read back the automation to verify its state and unchanged rule. After resume, also report whether the agent is paused.
Pausing stops future recurrence; it does not cancel tasks already created. Resuming an automation does not resume its agent.
Verify and report
Return the automation ID, bound agent, saved schedule or trigger, and automation state. If the agent is paused, say that it cannot start new runs.
Saving configuration does not prove that a webhook was delivered or a task completed. Do not trigger a test run unless requested.
For an uncertain create response or mismatched saved configuration, follow Recovery. If a required API or decision is unavailable, preserve the draft and explain what is needed to continue.
Sponsors
Details
- Marketplace
- pulumi/agent-skills
- Category
- Development