pulumi avatar

pulumi-migration

Convert and import infrastructure from Terraform, CDK, ARM, and CloudFormation to Pulumi

GitHub stars
80

Install

/plugin install pulumi-migration@pulumi-agent-skills

Run it inside Claude Code after adding the marketplace with /plugin marketplace add pulumi/agent-skills.

Contents

Discovered from source

Skills 5

IMPORTANT: PLAN ADJUSTMENT REQUIRED

If you have already generated a migration plan before loading this skill, you MUST:

  1. Review your existing plan against the workflows and requirements in this skill
  2. Identify any gaps, missing steps, or incorrect assumptions
  3. Update and revise your plan to align with this skill's guidance
  4. Communicate the adjusted plan to the user before proceeding

CRITICAL SUCCESS REQUIREMENTS

The migration output MUST meet all of the following:

  1. Complete Resource Coverage

    • Every CloudFormation resource MUST be represented in the Pulumi program OR explicitly justified in the final report.
  2. CloudFormation Logical ID as Resource Name

    • CRITICAL: Every Pulumi resource MUST use the CloudFormation Logical ID as its resource name.
    • This enables the cdk-importer tool to automatically find import IDs.
    • DO NOT rename resources. Automated import will FAIL if you change the logical IDs.
  3. Successful Deployment

    • The produced Pulumi program must be structurally valid and capable of a successful pulumi preview (assuming proper config).
  4. Zero-Diff Import Validation (if importing existing resources)

    • After import, pulumi preview must show NO updates, replaces, creates, or deletes.
  5. 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 name
  • PhysicalResourceId - The actual AWS resource ID
  • ResourceType - 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-native for all resources unless there's a specific reason to use aws.
  • 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:

CloudFormationPulumi Equivalent
!Ref (resource)Resource output (e.g., bucket.id)
!Ref (parameter)Pulumi config
!GetAtt Resource.AttrResource 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::ImportValueStack 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:

  1. Identify the purpose: Read the Lambda function code to understand what it does
  2. Find native replacement: Check if Pulumi has a native resource that provides the same functionality
  3. 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:

  1. Check Provider Usage: Scan your code to ensure all resources use aws-native
  2. Document Exceptions: Any use of aws (classic) provider must be justified
  3. 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:

  1. Follow cloudformation-id-lookup.md to find the import ID format
  2. 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:

  1. Overview (high-level description)
  2. Migration Plan Summary
  3. Pulumi Code Outputs (TypeScript; organized by file)
  4. Resource Mapping Table:
CloudFormation Logical IDCFN TypePulumi TypeProvider
MyAppBucketABC123AWS::S3::Bucketaws-native.s3.Bucketaws-native
MyLambdaFunction456AWS::Lambda::Functionaws-native.lambda.Functionaws-native
  1. Custom Resources Summary (if any)
  2. Final Migration Report (PR-ready)
  3. 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:

  1. Review your existing plan against the workflows and requirements in this skill
  2. Identify any gaps, missing steps, or incorrect assumptions
  3. Update and revise your plan to align with this skill's guidance
  4. Communicate the adjusted plan to the user before proceeding

CRITICAL SUCCESS REQUIREMENTS

The migration output MUST meet all of the following:

  1. Complete Resource Coverage

    • Every ARM template resource MUST:
      • Be represented in the Pulumi program OR
      • Be explicitly justified in the final report.
  2. Successful Deployment

    • The produced Pulumi program must be structurally valid and capable of a successful pulumi preview (assuming proper config).
  3. Zero-Diff Import Validation (if importing existing resources)

    • After import, pulumi preview must show:
      • NO updates
      • NO replaces
      • NO creates
      • NO deletes
    • Any diffs must be resolved using the Preview Resolution Workflow. See arm-import.md.
  4. 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
  1. Provider Strategy:

    • Default: Use @pulumi/azure-native for 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:

  2. 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
  3. 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
  1. Inline Import Approach:

    • Use import resource option with Azure Resource IDs
    • No separate import tool (unlike pulumi-cdk-importer)
  2. Azure Resource IDs:

    • Follow predictable pattern: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
    • Can be generated by convention or queried via Azure CLI
  3. Zero-Diff Validation:

    • Run pulumi preview after import
    • Resolve all diffs using Preview Resolution Workflow
    • Goal: NO updates, replaces, creates, or deletes

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:

  1. Review all exports:

    pulumi stack output
    
  2. Verify resource relationships:

    pulumi stack graph
    
  3. Test application functionality (if applicable)

  4. 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:

Microsoft Azure Documentation:

OUTPUT FORMAT (REQUIRED)

When performing a migration, always produce:

  1. Overview (high-level description)
  2. Migration Plan Summary
    • ARM template resources identified
    • Conversion strategy (language, providers)
    • Import approach (if applicable)
  3. Pulumi Code Outputs (organized by file)
    • Main program file
    • Component resources (if any)
    • Configuration instructions
  4. Resource Mapping Table (ARM → Pulumi)
    • ARM resource type → Pulumi resource type
    • ARM resource name → Pulumi logical name
    • Import ID (if importing)
  5. Preview Resolution Notes (if importing)
    • Diffs encountered
    • Resolution strategy applied
    • Properties ignored vs. added
  6. Final Migration Report (PR-ready)
    • Summary of changes
    • Testing instructions
    • Known limitations
    • Next steps
  7. Configuration Setup
    • Required config values
    • Example pulumi config set commands

Keep code syntactically valid and clearly separated by files.

CRITICAL SUCCESS REQUIREMENTS

The migration output MUST meet all of the following:

  1. Complete Resource Coverage

    • Every CloudFormation resource synthesized by CDK MUST:
      • Be represented in the Pulumi program OR
      • Be explicitly justified in the final report.
  2. Successful Deployment

    • The produced Pulumi program must be structurally valid and capable of a successful pulumi up (assuming proper config).
  3. 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 synth with --quiet to 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 cdk2pulumi tool. 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::CustomResource or Custom::<name>
  • Metadata contains aws:cdk:path with 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:

HandlerStrategy
aws-certificatemanager/dns-validated-certificate-handlerReplace with aws.acm.Certificate, aws.route53.Record, and aws.acm.CertificateValidation
aws-ec2/restrict-default-security-group-handlerReplace with aws.ec2.DefaultSecurityGroup resource with empty ingress/egress rules
aws-ecr/auto-delete-images-handlerReplace aws-native:ecr:Repository with aws.ecr.Repository with forceDelete: true
aws-s3/auto-delete-objects-handlerReplace aws-native:s3:Bucket with aws.s3.Bucket with forceDestroy: true
aws-s3/notifications-resource-handlerReplace with aws.s3.BucketNotification
aws-logs/log-retention-handlerReplace with aws.cloudwatch.LogGroup with explicit retentionInDays
aws-iam/oidc-handlerReplace with aws.iam.OpenIdConnectProvider
aws-route53/delete-existing-record-set-handlerReplace with aws.route53.Record with allowOverwrite: true
aws-dynamodb/replica-handlerReplace with aws.dynamodb.TableReplica

Cross-account/region handlers:

  • aws-cloudfront/edge-function → Use aws.lambda.Function with region: "us-east-1"
  • aws-route53/cross-account-zone-delegation-handler → Use separate aws provider with cross-account role assumption

Graceful degradation for unknown handlers:

  1. Keep the CustomResourceEmulator (default behavior)
  2. 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-native whenever the resource type is available.
  • Fallback: Use aws when 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 TypeDetectionPulumi Migration
Docker ImagedockerImages in assets.jsonUse docker-build.Image to build and push. Replace hard-coded ECR URI with image output.
File with build commandfiles with executable fieldFlag to user - build command needs setup in Pulumi
Static filefiles without executable, no bundling in CDK sourceUse pulumi.FileArchive or pulumi.FileAsset
Bundled filefiles without executable, but CDK source uses bundlingFlag 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:

  1. CI/CD Pipeline (Recommended): Move the build step to your CI pipeline and reference the pre-built artifact in Pulumi
  2. Pulumi Command Provider: Use command.local.Command to run the build command during pulumi up
  3. Pre-build Script: Create a build script that runs before pulumi up and outputs to a known location

Each 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-importer tool. 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:

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:

  1. Overview (high-level description)
  2. Migration Plan Summary
  3. Pulumi Code Outputs (TypeScript; structured by file)
  4. Resource Mapping Table (CDK → Pulumi)
  5. Custom Resources Summary (if any):
    • Handlers migrated to native Pulumi resources
    • Handlers kept as CustomResourceEmulator with rationale
    • Any handlers requiring user attention
  6. 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
  7. Final Migration Report (PR-ready)
  8. 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-pulumi or pulumi-arm-to-pulumi alongside this skill. Those two skills prescribe a template-first workflow (mechanical translation → import) and mandate aws-native for AWS. This skill is cloud-state-first (import from discovered state → optional refactor against the template later) and defaults to aws classic / azure-native. The useful reference material from those two skills has been curated into cloudformation.md and arm.md in 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:

  1. Complete resource coverage — every discovered resource is imported OR has an annotation explaining why not.
  2. Zero-diff — pulumi preview shows no changes. This proves the code matches the cloud state exactly.
  3. Progress tracked via the API — use compareTo and migration annotations so progress is visible in Pulumi Cloud, not just in agent memory.
  4. 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). null if unmapped.
  • resource.inputs.providerId — physical cloud ID for pulumi import.
  • resource.urn — the URN to use as resourceUrn in 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 ID
  • resourceType — the CF type (e.g. AWS::IAM::Role)
  • resourceStatus — e.g. CREATE_COMPLETE, DELETE_COMPLETE
  • driftStatus — 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.deploymentName non-empty) — arm is a deployment-operation object: properties.targetResource.id / .resourceType / .resourceName, properties.provisioningState (e.g. Succeeded).
  • Placeholder (resource.inputs.deploymentName empty) — arm is the raw Azure generic-resource object instead: top-level id, name, type, location, tags. No properties.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:

  1. Migrated — the resource was found in the compareTo Pulumi stack. Already under Pulumi management; skip.
  2. Ready — providerType and providerId are set and the scanner confirmed the resource exists. Import with pulumi import <providerType> <name> <providerId> --generate-code --out <file>.ts (NEVER without --generate-code --out — see Phase 4).
  3. NotFound — providerType and providerId are 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.
  4. NotApplicable — container or wrapper types (AWS::CloudFormation::Stack, Microsoft.Resources/deployments, Microsoft.Resources/resourceGroups, pulumi:providers:*) are not individually migratable. Skip silently.
  5. NoMatch — providerType is null. No mapping found. Common examples:
    • CF Custom Resources (e.g. Custom::VpcRestrictDefaultSG) — no direct Pulumi equivalent.
    • Inline policies — AWS::IAM::Policy modeled as an inline property of aws:iam/role:Role. Once the parent Role is migrated, annotate the policy as migrated.
  6. PulumiOnly — exists in the compareTo stack 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 Migrated with a note explaining they no longer exist
  • Flag inline/child resources covered by a parent's migration as Migrated with a note naming the parent — do not use linkedResourceUrn here (it's a 1:many relationship and the UI only merges 1:1 pairs)
  • Bridge a NotFound or NoMatch origin to its PulumiOnly counterpart after a corrected mapping (statusOverride=Migrated + linkedResourceUrn → the PulumiOnly URN). This is the only valid use of linkedResourceUrn.
  • 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:

  1. 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 code
    

    Read these before calling the API.

  2. API response — the annotation.note field on each DiscoveredResourceInfo when you call GET .../resources. The annotation object 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 compareTo in 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:

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.

  1. 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.
  2. Save the response to disk — ./.migration/resources-baseline.json.
  3. 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.
  4. 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

  1. 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.
  2. 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.
  3. Set provider config: pulumi config set aws:region <r> (or azure-native:location).
  4. Link the ESC environment if provided.

No empty pulumi up needed.

Concrete commands for project + stack setup, region config, and provider install: cloudformation.md §2 or arm.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.

  1. Import the batch.
  2. pulumi preview — zero diff required. Fix any diffs before moving on.
  3. Commit the program changes to a branch.
  4. Annotate each imported resource — PUT .../migration with note and no statusOverride. 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 (with linkedResourceUrn) — resource covered by another (inline IAM policy → parent Role, IGW attachment → IGW, etc.).
  • statusOverride=Migrated (with a note, no linkedResourceUrn) — 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:

  1. Resource is deleted. pulumi import returns Preview failed: resource '<id>' does not exist. Annotate statusOverride=Migrated with 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.

  2. Wrong providerType mapping. 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 the originType in cloudformation.md §7, override providerType in the import file, retry. Then handle the fingerprint side-effect (next bullet).

  3. Wrong-mapping side-effect: PulumiOnly appears. When the agent imports with a corrected providerType, fingerprint matching against the discovered resource fails. The discovered resource stays NotFound (or NoMatch) and a new PulumiOnly entry appears. Annotate the original origin row as statusOverride=Migrated with linkedResourceUrn pointing to the PulumiOnly URN. This bridges them in the UI and keeps the bookkeeping clean.

  4. Resource is alive and mapping is correct. Import succeeds. Status flips to Migrated automatically.

NoMatch (providerType is null):

Common patterns:

  1. Inline IAM policies. AWS::IAM::Policy whose name matches a migrated Role's prefix is an inline policy already captured as inlinePolicies on the Role's import. Annotate statusOverride=Migrated with note: "inline policy of <RoleName>".

  2. 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=Migrated with a note explaining the implicit link.

  3. CDK Custom Resources (Custom::*). Typically a Lambda handler doing the actual work. Check cloudformation.md §5 for known handler → Pulumi replacement mappings. Don't annotate Migrated without confirming with the user — surface what the handler does and let them decide.

  4. Other NoMatch types. Look up the originType in 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 (aws classic vs aws-native, azure-native vs azure), the Preview Resolution Workflow, and known import quirks, see cloudformation.md §3–§6 or arm.md §3–§6.

Phase 6 — Reconciliation & PR

  1. 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't ignoreChanges.
    • 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 with ignoreChanges.

    Expect 2–5 preview rounds for complex resources. Never run pulumi up to resolve diffs — that modifies the cloud, not the code. See cloudformation.md §6 or arm.md §6 for cloud-specific diff patterns.

  2. Do one final GET resources?compareTo=... and verify the expected distribution (this reflects the current backend state — migrationStatus is already up-to-date since every pulumi import writes state):

    • Migrated — all imported resources
    • PulumiOnly — Pulumi-only resources, including any corrected-mapping imports linked via annotation
    • NoMatch remaining — every one should have an annotation
    • NotApplicable (containers) — silently skipped
  3. 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:

  1. 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.
  2. Replace literal ARN/ID references with cross-resource output references.
  3. Extract config parameters (region, account ID, environment tag).
  4. Consolidate into ComponentResource classes where the source repo or CDK paths suggest a natural grouping.
  5. 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:

  1. Show a summary of what changed: files created/renamed, components introduced, literals replaced, config keys added.
  2. Walk through the top-level index.ts (or equivalent) line by line if it's under ~80 lines; otherwise describe the module breakdown.
  3. Highlight any judgment calls (e.g. "I grouped the IAM resources into iam.ts to match the lib/iam/ directory in your source repo — let me know if you'd prefer a different name").
  4. 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:

  1. Overview — source discovered stack → target Pulumi stack, region, language.
  2. Triage summary — counts by status at start and end.
  3. Resource mapping table — name, origin type, provider type, status, notes.
  4. Gaps — unmapped resources and why, with annotations.
  5. Progress URL — link to the discovered-stacks comparison endpoint for ongoing tracking.
  6. 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.

Sponsors

Details

Marketplace
pulumi/agent-skills
Source
migration
Category
Integration

More from pulumi/agent-skills

All 4