Fix TechDebt: ClickOps to CDK made easy with Kiro
Fix your technical debt by importing console-created resources into AWS CDK managed stacks. What was a daunting task in the past today is easy - thanks to Kiro.
Every AWS account has them. The Lambda function someone created during an incident. The DynamoDB table that started as a proof of concept and quietly became load-bearing. The IAM role with a name like
my-function-role-a1b2c3 that nobody remembers creating.They work. That's the problem — they work well enough that nobody touches them, and the knowledge of how they were configured leaves with the person who clicked them into existence.
Three conversations you may recognize:
The colleague who built this has left. Nobody knows why the timeout is 47 seconds — and nobody dares touch it.
We need the identical setup in eu-central-1 by Friday. Two days of clicking later, it still isn't identical.
It broke after someone "just changed one setting." No idea which one.
The fix is Infrastructure as Code. The obstacle is that most IaC guidance assumes you're starting from nothing, and you aren't — you're starting from something that already exists and is already serving traffic.
This article walks the path from a console-created resource to one managed by AWS CDK, without deleting and recreating it.
A quick word on what ClickOps actually costs you
"ClickOps" is building resources by clicking through the AWS Console. It's the fastest way to get started and there's nothing shameful about it.
What it costs you is not auditability — CloudTrail records who called what, so console actions are traceable after the fact. What you lose is different, and more subtle:
- No review before the change lands. There's no pull request, no second pair of eyes, no automated check. The change is simply live.
- No versioned record of intended state. CloudTrail tells you a setting changed. It doesn't give you something you can diff, roll back, or reason about as a whole.
- No repeatability. Another Region, another account, a rebuild after an incident — all of it is manual again.
Those three gaps are what infrastructure as code (IaC) with AWS CDK closes.
The problem: your resource already exists
Here's where the standard tutorials stop being useful.
CDK is built to create resources. If you write a construct describing your existing function and run
cdk deploy , CloudFormation tries to create it and fails: "already exists."So you have two options.
Option A: delete it and recreate it
Tempting, because it's less work. Genuinely fine for a scratch resource. On anything real, it bites in three ways:
- The ARN changes. An ARN is the globally unique identifier other things reference. A new one silently breaks IAM policies, event source mappings, and anything with the old value baked into configuration.
- Data is gone. Tables, buckets, and volumes hold state you can't rebuild from a template.
- There's downtime while the resource is torn down and replaced.
Option B: import it
cdk import tells CloudFormation to start managing a resource that already exists. The resource never moves. Same ARN, same data, no downtime. CloudFormation adopts it under a Retain deletion policy, so nothing is created or destroyed in the process.The rest of this article is Option B.
Step 1: Describe the resource in code
This is the part that surprises people: you write the CDK code yourself, by hand, describing the resource as it already is. Nothing is exported from AWS for you.
- Start from a project. A new one (
cdk init app --language typescript) or the CDK project you already have. If you already have one, just add the construct to an existing stack — there's no requirement for a greenfield project. A separate stack for imports keeps the blast radius small, but it's a preference, not a rule.
- Discover the live settings. Names, size, configuration, permissions.
aws lambda get-function,aws iam get-role, and friends.
- Write code that matches exactly. Same physical names. Same memory, timeout, runtime, role path.
- Run
cdk synth.
That last step deserves a note, because it confuses everyone the first time:
cdk synth reads your code, not AWS. It exists here so you can see the logical IDs CDK generated for the constructs you wrote. You need those next.Two rules matter at this stage:
- Match physical names exactly. Without an explicit
functionName,roleName, orlogGroupName, CDK generates its own unique names and the import won't match anything.
- Avoid
grant*()helpers for now. Convenient methods liketable.grantWriteData(fn)generate an extra IAM policy resource that doesn't exist in AWS yet, and the import fails with an unresolved-dependency error. Spell permissions out as inline policies to get through the import, then refactor afterwards.
Step 2: Build the resource mapping
The mapping file connects two names for the same thing:
- Logical ID — CDK's internal handle, invented during synthesis (
MyFnABC123)
- Physical name — what the resource is actually called in AWS (
my-fn)
Find the logical IDs in the synthesized template. The keys under
Resources: are what you want:Resources: MyResourceABC123: # <- the logical ID Type: AWS::Lambda::FunctionThen pair them by hand. CDK does not generate this file for you:
{ "LambdaFunctionABC123": { "FunctionName": "my-fn" }, "LambdaRoleDEF456": { "RoleName": "my-fn-role" }, "LogGroupGHI789": { "LogGroupName": "/aws/lambda/my-fn" }}Each resource type has its own identifier key — Function uses
FunctionName , Role uses RoleName , LogGroup uses LogGroupName , S3 uses BucketName , SQS uses the full QueueUrl . Get one wrong and the import either fails outright or tries to replace the resource.Step 3: Import, then read the diff carefully
$ cdk import --resource-mapping resource-mapping.jsonMyFn (AWS::Lambda::Function): successMyRole (AWS::IAM::Role): success
$ cdk diffStack MyStackResources[~] AWS::Lambda::Function MyFn MyFnABC123 └─ [-] DeletionPolicy: Retain[~] AWS::IAM::Role MyRole MyRoleDEF456 └─ [-] DeletionPolicy: RetainThat diff is the whole verification story, so read it properly:
- Only
[-] DeletionPolicymeans the import is faithful. That line is CloudFormation's import safety net being handed over to normal stack management. A stack description and aBootstrapVersionparameter appearing are also normal.
- A property change, or worse a replacement, means your code doesn't match reality — usually a physical name. Fix the mapping or the construct before you deploy.
Then
cdk deploy once to normalise ownership, and invoke the resource to confirm it still behaves.Step 4: You only do this once
Worth being explicit, because people assume otherwise: import is scaffolding, not a new way of working. It runs once per resource and then gets out of the way. Every future change goes through ordinary
cdk deploy . Once the diff is clean, resource-mapping.json has served its purpose and can be deleted — deployments never read it. Some teams keep it committed as a record of what was adopted and when, which is a reasonable habit.What changes from this point:
- The code is the source of truth. If someone edits the resource in the console afterwards, the next
cdk diffshows it as drift, and a deploy pulls it back to whatever the code says. That discipline is the thing you were buying.
- Now you can improve it safely. Set log retention instead of infinite. Add tags and alarms. Upgrade an end-of-life runtime. Swap those inline policies for
grant*()helpers. Delete the console's orphaned managed policy. Each change is a reviewedcdk diffaway.
Do the improving after the import is verified stable, not during. Import should be a no-op adoption; modernization is a separate, deliberate step.
When this doesn't apply
Not every resource type is importable. CloudFormation supports import for many types but not all. Lambda event source mappings, resource-based permissions, API Gateway definitions, CloudWatch alarms, and EventBridge rules are generally easier to define fresh in CDK and let it replace the manually-created equivalents.
Making it repeatable
Everything above is a defined sequence with defined checks, which makes it a good candidate for automation. I wrote a Kiro skill for this workflow — written-down expertise (a
SKILL.md with steps, commands, and guardrails) that an AI agent picks up on demand. Point the agent at a resource and it discovers the configuration, asks the judgment calls, writes the stack, builds the mapping, runs the import, and checks the diff.Try it on one resource
Pick a single non-production resource this week. A Lambda function is a good first target: small, self-contained, and it drags its execution role and log group along so you get practice importing a set rather than one thing.
Walk it through by hand the first time. You'll understand the diff output far better for having done it, and you'll know what "faithful import" actually looks like before you automate it.
Once you've done one by hand, try the
clickops-to-iac skill I built for this demo — it targets Lambda functions and their attached role and log group. Point it at one of your own functions and watch it discover the config, write the stack, and run the import. (Reminder: it's a demo skill). Feel free to modify it. Just ask Kiro to assist you with that task.The console isn't the enemy. Leaving things there permanently is.
Here my sample skill file:
#SKILL.md
---name: clickops-to-iacdescription: Import existing ClickOps-created AWS resources into a CDK project. Discovers all resource configuration, creates a matching CDK stack, runs cdk import, and verifies management works. Covers Lambda functions with all settings (env vars, VPC, layers, triggers, etc.), IAM roles, log groups, and associated resources. After migration, optionally modernizes the CDK and Lambda code — either inline with Kiro (runtime upgrades, dependency updates, best practices) or via AWS Transform continuous modernization (rapid-techdebt-analysis or tech-debt-comprehensive scans with autonomous remediation PRs). Use when the user wants to migrate manually-created AWS resources to Infrastructure as Code.---
# ClickOps to IaC
A guided workflow to import existing manually-created AWS resources into a new or existing CDK project using `cdk import`.
## When to use
Activate when the user asks any of:
- "import this Lambda/resource into CDK"- "migrate from ClickOps to IaC"- "manage this resource with CDK"- "I created this in the console, now I want it in code"- "take over management of [resource] with CDK"- "import existing infrastructure"
Do NOT activate for:- Referencing an existing resource without managing it (use `fromXxx()` methods instead)- Creating new resources from scratch (just write CDK normally)- CloudFormation stack imports that don't involve CDK
## Questions to ask before starting
Gather these from the user before beginning work:
### Required
1. **What resource(s)?** — Function name, ARN, or description of what to import.2. **What region?** — Where the resources live.3. **AWS credentials** — Which profile or default credentials to use.4. **CDK language** — TypeScript or Python? (Follow project conventions if adding to an existing project.)5. **New or existing project?** — Create a new CDK project or add to an existing stack?6. **Project location** — Where on the filesystem?
### Ask based on discovery
7. **Log retention** — "The log group has no retention set (infinite). What retention do you want?" (suggest 30, 60, 90 days or keep infinite)8. **Removal policy** — "Should resources be destroyed when the stack is deleted, or retained?" (default: DESTROY)9. **Naming prefix** — "What prefix for the stack name?" (for multi-environment support)10. **Tagging** — "Do you want to add project/team tags?"
## High-level flow
0. Check accesc to the aws account1. **Discover** all resources and their configuration.2. **Ask** clarifying questions based on what was found.3. **Create** or update the CDK project.4. **Define** the stack matching existing resources exactly.5. **Build** the resource mapping file.6. **Bootstrap** CDK in the target region (if needed).7. **Import** using `cdk import --force --resource-mapping`.8. **Verify** with `cdk diff` (expect only DeletionPolicy changes).9. **Deploy** to normalize CDK ownership.10. **Validate** the resource still works.11. **Clean up** orphaned resources (old managed policies, etc.).
## Step 1: Discover Resources
### Lambda Function
```bash# Full function configurationaws lambda get-function --function-name <NAME> --region <REGION>
# Event source mappings (SQS, DynamoDB, Kinesis triggers)aws lambda list-event-source-mappings --function-name <NAME> --region <REGION>
# Resource-based policy (API GW, S3, SNS, CloudWatch Events triggers)aws lambda get-policy --function-name <NAME> --region <REGION>
# Aliases and versionsaws lambda list-aliases --function-name <NAME> --region <REGION>
# Provisioned concurrencyaws lambda list-provisioned-concurrency-configs --function-name <NAME> --region <REGION>```
### Lambda Properties to Capture
Record ALL of these from the discovery:
| Property | CDK Parameter | Notes ||----------|---------------|-------|| FunctionName | `functionName` | **Must match exactly** for import || Runtime | `runtime` | e.g., `lambda.Runtime.NODEJS_LATEST` || Handler | `handler` | e.g., `index.handler` || Architectures | `architecture` | ARM_64 or X86_64 || MemorySize | `memorySize` | 128-10240 MB || Timeout | `timeout` | `cdk.Duration.seconds(N)` || EphemeralStorage | `ephemeralStorageSize` | Only if > 512 MB || Environment.Variables | `environment` | Key-value map || VpcConfig | `vpc`, `vpcSubnets`, `securityGroups` | If VPC-attached || Layers | `layers` | Reference via `LayerVersion.fromLayerVersionArn()` || DeadLetterConfig | `deadLetterQueue` or `deadLetterTopic` | If configured || TracingConfig | `tracing` | `ACTIVE` or `PASS_THROUGH` || ReservedConcurrentExecutions | `reservedConcurrentExecutions` | If set || LoggingConfig.LogFormat | `loggingFormat` | `TEXT` or `JSON` || LoggingConfig.LogGroup | `logGroup` | Custom log group || Description | `description` | Often empty for console-created || KMSKeyArn | `environmentEncryption` | If using CMK |
### IAM Role
```bash# Role details (trust policy, path)aws iam get-role --role-name <ROLE_NAME>
# Attached managed policiesaws iam list-attached-role-policies --role-name <ROLE_NAME>
# Inline policiesaws iam list-role-policies --role-name <ROLE_NAME>
# Get each inline policy documentaws iam get-role-policy --role-name <ROLE_NAME> --policy-name <POLICY_NAME>
# Get each managed policy documentaws iam get-policy-version --policy-arn <ARN> --version-id <VERSION>```
### IAM Role Properties to Capture
| Property | CDK Parameter | Notes ||----------|---------------|-------|| RoleName | `roleName` | **Must match exactly** || Path | `path` | Often `/service-role/` for console-created || AssumeRolePolicyDocument | `assumedBy` | Usually `lambda.amazonaws.com` || Permissions | `inlinePolicies` | Recreate as inline policies for import |
### Log Group
```bashaws logs describe-log-groups --log-group-name-prefix /aws/lambda/<FUNCTION_NAME> --region <REGION>```
### Other Resources to Check
- **VPC** (if Lambda is VPC-attached): subnets, security groups- **Layers**: version ARNs, compatibility runtimes- **DLQ**: SQS queue or SNS topic configuration- **Aliases**: weighted aliases for traffic shifting- **Event sources**: SQS queues, DynamoDB streams, Kinesis streams- **Triggers**: API Gateway, S3, CloudWatch Events/EventBridge rules, SNS subscriptions
### Download the Code
```bash# Get pre-signed URL and downloadaws lambda get-function --function-name <NAME> --region <REGION> \ --query 'Code.Location' --output text | xargs curl -s -o lambda-code.zip
# Extractunzip lambda-code.zip -d src/lambda/```
## Step 2: Ask Clarifying Questions
After discovery, ask about anything not captured:
- **Environment variables with sensitive values**: "I see env vars X, Y, Z. Should these be parameterized or stored in SSM/Secrets Manager?"- **VPC configuration**: "The Lambda is in VPC X with subnets A, B, C. Should I import the VPC or reference it with `fromLookup()`?" (Usually reference — VPCs are shared infrastructure.)- **Layers**: "The function uses layer ARN X. Should I import the layer or reference it?" (Usually reference via `fromLayerVersionArn()`.)- **Triggers**: "There's an API Gateway trigger. Should that be imported too or is it managed elsewhere?"- **Log retention**: Always ask if not set.- **Architecture**: If x86_64, ask if they want to switch to ARM (cost savings).
## Step 3: Write the CDK Stack
### Critical Rules for Import
1. **Every imported resource MUST have its physical name explicitly set.** Without `functionName`, `roleName`, `logGroupName`, CDK generates unique names that won't match.
2. **Do NOT use `grant*()` methods before the first deploy.** Methods like `grantWrite()`, `grantRead()`, `grantInvoke()` create a separate `DefaultPolicy` resource (AWS::IAM::Policy) that doesn't exist in AWS. This causes: ``` Template format error: Unresolved resource dependencies [XxxDefaultPolicyYYYYYYYY] ``` **Solution:** Use `inlinePolicies` on the Role constructor instead.
3. **Match the IAM role path.** Console-created roles use `/service-role/`. Omitting this causes a mismatch.
4. **Match architecture exactly.** Don't change x86_64 to ARM during import — do that after.
5. **Match runtime exactly.** Use the same runtime version, not an upgrade.
6. **For VPC-attached Lambdas**, reference the VPC via `fromLookup()` — don't try to import the VPC itself: ```typescript const vpc = ec2.Vpc.fromLookup(this, 'Vpc', { vpcId: 'vpc-12345' }); ```
7. **For Layers**, reference via ARN: ```typescript const layer = lambda.LayerVersion.fromLayerVersionArn( this, 'MyLayer', 'arn:aws:lambda:region:account:layer:name:version' ); ```
### Template
```typescriptimport * as cdk from 'aws-cdk-lib/core';import * as lambda from 'aws-cdk-lib/aws-lambda';import * as iam from 'aws-cdk-lib/aws-iam';import * as logs from 'aws-cdk-lib/aws-logs';import { Construct } from 'constructs';import * as path from 'path';
export class ImportedLambdaStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props);
// --- Log Group (explicit, with desired retention) --- const logGroup = new logs.LogGroup(this, 'LambdaLogGroup', { logGroupName: '/aws/lambda/<FUNCTION_NAME>', retention: logs.RetentionDays.<CHOSEN_RETENTION>, removalPolicy: cdk.RemovalPolicy.DESTROY, });
// --- IAM Role (with inlinePolicies, NOT grant methods) --- const executionRole = new iam.Role(this, 'LambdaExecutionRole', { roleName: '<EXACT_ROLE_NAME>', path: '/service-role/', // or whatever path was discovered assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'), inlinePolicies: { // Recreate the discovered policy statements here ExecutionPolicy: new iam.PolicyDocument({ statements: [ // ... match discovered permissions exactly ], }), }, });
// --- Lambda Function --- const fn = new lambda.Function(this, 'LambdaFunction', { functionName: '<EXACT_FUNCTION_NAME>', runtime: lambda.Runtime.<DISCOVERED_RUNTIME>, handler: '<DISCOVERED_HANDLER>', code: lambda.Code.fromAsset(path.join(__dirname, '..', 'src', 'lambda')), memorySize: <DISCOVERED_MEMORY>, timeout: cdk.Duration.seconds(<DISCOVERED_TIMEOUT>), architecture: lambda.Architecture.<DISCOVERED_ARCH>, role: executionRole, logGroup: logGroup, // Include if discovered: // environment: { KEY: 'value' }, // vpc: vpc, // vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS }, // securityGroups: [sg], // layers: [layer], // deadLetterQueue: dlq, // tracing: lambda.Tracing.ACTIVE, // reservedConcurrentExecutions: N, }); }}```
## Step 4: Build Resource Mapping
Find the logical IDs CDK generates:
```bashnpx cdk synth | grep -E "^ [A-Z].*:$"```
Create `resource-mapping.json`:
```json{ "<LogicalId_LogGroup>": { "LogGroupName": "/aws/lambda/<function-name>" }, "<LogicalId_Role>": { "RoleName": "<role-name>" }, "<LogicalId_Function>": { "FunctionName": "<function-name>" }}```
### Identifier Keys by Resource Type
| Resource Type | Key | Value ||---------------|-----|-------|| AWS::Lambda::Function | `FunctionName` | Function name || AWS::IAM::Role | `RoleName` | Role name || AWS::Logs::LogGroup | `LogGroupName` | Log group name || AWS::DynamoDB::Table | `TableName` | Table name || AWS::S3::Bucket | `BucketName` | Bucket name || AWS::SQS::Queue | `QueueUrl` | Full queue URL || AWS::SNS::Topic | `TopicArn` | Full topic ARN || AWS::Events::Rule | `Name` | Rule name || AWS::Lambda::LayerVersion | `LayerVersionArn` | Full layer version ARN |
## Step 5: Bootstrap and Import
```bash# Bootstrap if not already donenpx cdk bootstrap aws://<ACCOUNT>/<REGION>
# Importnpx cdk import --force --resource-mapping resource-mapping.json```
### Common Import Errors
| Error | Cause | Fix ||-------|-------|-----|| `Unresolved resource dependencies [XxxDefaultPolicy...]` | `grant*()` method created a DefaultPolicy | Use `inlinePolicies` on the Role instead || `Resource of type X is not importable` | CloudFormation doesn't support import for this type | Use `fromXxx()` to reference it, manage separately || `No resource with [identifier] exists` | Physical name mismatch | Double-check the name in resource-mapping.json || `Resource already managed by another stack` | Resource belongs to a different CloudFormation stack | Remove it from the other stack first || `--resource-mapping is required when input is not a terminal` | Running in non-interactive context | Use `--resource-mapping` with a JSON file |
## Step 6: Verify and Deploy
```bash# Check for drift — expect only DeletionPolicy removalnpx cdk diff
# Deploy to normalize CDK ownershipnpx cdk deploy
# Verify the resource still worksaws lambda invoke --function-name <NAME> --region <REGION> --payload '{}' /tmp/response.jsoncat /tmp/response.json```
### Expected diff after import
These are normal and safe:- `[-] DeletionPolicy: Retain` — CloudFormation's import safety net being removed- `[+] Description` — Stack description being added- `[+] Parameter BootstrapVersion` — CDK scaffolding
These are NOT expected (investigate):- Property changes on the Lambda, role, or log group- Resources being replaced (check physical names match)
## Step 7: Clean Up Orphaned Resources
After CDK takes over, the old console-created managed policies are orphaned. List and delete them once users confirms:
```bash# Find orphaned policies (no longer attached)aws iam list-policies --scope Local --query "Policies[?AttachmentCount==\`0\`]" --output table
# Delete if confirmed orphanedaws iam delete-policy --policy-arn <ARN>```
## Step 8: Optional Runtime Upgrade
After import is stable and verified, offer the user a runtime upgrade if the function is on an older version. This is a safe, reversible change when done correctly.
### When to offer
- Runtime is more than one major version behind (e.g., nodejs18.x when nodejs22.x is available)- Runtime is approaching or past end-of-life- User asks for it
### Safe upgrade process
**1. Investigate potential breaking changes**
Before touching anything, analyze the function code for incompatibilities with the target runtime:
```bash# Read the function codecat src/lambda/index.mjs # or index.py, index.js, etc.```
Check for:
**Node.js upgrades:**- `require('aws-sdk')` — v2 SDK removed from nodejs18.x+; needs `@aws-sdk/*` v3 or a layer- `require('http2')` — API changes between versions- Deprecated APIs: `url.parse()` (use `new URL()`), `querystring` (use `URLSearchParams`)- CommonJS vs ESM: `.mjs` extensions and `import` syntax behave differently across versions- Native addons / compiled dependencies in layers — must be rebuilt for the new runtime
**Python upgrades:**- `import distutils` — removed in Python 3.12+- `import imp` — removed in Python 3.12+, use `importlib`- `import cgi`, `import cgitb` — removed in Python 3.13+- `datetime.utcnow()` — deprecated in Python 3.12+, use `datetime.now(timezone.utc)`- f-string grammar changes in 3.12 (more permissive, shouldn't break)- Typing syntax: `list[str]` works natively in 3.9+, `X | Y` union syntax in 3.10+- Layer dependencies compiled with older Python (C extensions need recompile)
**Both:**- Check `package.json` or `requirements.txt` for pinned dependencies that may not support the new runtime- Check layers — they may bundle native libraries compiled for a specific runtime version- Check if the function uses Lambda runtime APIs that changed between versions
```bash# For Node.js — scan for aws-sdk v2 usagegrep -r "require('aws-sdk')\|from 'aws-sdk'" src/lambda/
# For Node.js — scan for deprecated APIsgrep -r "url\.parse\|querystring\.\|new Buffer(" src/lambda/
# For Python — scan for removed modulesgrep -r "import distutils\|import imp\|import cgi\|from cgi " src/lambda/
# For Python — scan for deprecated patternsgrep -r "utcnow()\|utcfromtimestamp(" src/lambda/
# Check if layers exist (they may need updating too)aws lambda get-function --function-name <NAME> --region <REGION> \ --query 'Configuration.Layers[].Arn' --output text```
If breaking changes are found, inform the user:
> "I found potential incompatibilities:> - Your code uses `require('aws-sdk')` which is not bundled in nodejs20.x+. You'll need to either add the AWS SDK v3 (`@aws-sdk/client-*`) or include a layer with SDK v2.> - Layer `arn:aws:lambda:...:layer:my-layer:3` may contain native binaries compiled for the old runtime.>> Want me to fix these before upgrading, or skip the runtime upgrade for now?"
Only proceed with the upgrade after issues are resolved or confirmed as non-issues.
**2. Record the current working state**
```bash# Invoke and capture the response as a baselineaws lambda invoke --function-name <NAME> --region <REGION> \ --payload '<REPRESENTATIVE_PAYLOAD>' /tmp/baseline-response.jsoncat /tmp/baseline-response.json```
**3. Publish a version of the current working code**
This creates an immutable snapshot to roll back to if the upgrade breaks anything:
```bashaws lambda publish-version --function-name <NAME> --region <REGION> \ --description "Pre-upgrade snapshot on <CURRENT_RUNTIME>"```
Note the returned version number.
**4. Change the runtime in CDK**
```typescript// Beforeruntime: lambda.Runtime.NODEJS_18_X,
// Afterruntime: lambda.Runtime.NODEJS_22_X,```
**5. Preview and deploy**
```bashnpx cdk diff # Should show only Runtime changenpx cdk deploy```
**6. Validate after upgrade**
```bash# Invoke with the same payloadaws lambda invoke --function-name <NAME> --region <REGION> \ --payload '<REPRESENTATIVE_PAYLOAD>' /tmp/upgraded-response.json
# Compare responsesdiff /tmp/baseline-response.json /tmp/upgraded-response.json```
**7. Check for errors in logs**
```bashaws logs filter-log-events \ --log-group-name /aws/lambda/<NAME> \ --region <REGION> \ --start-time $(date -v-5M +%s000) \ --filter-pattern "ERROR" \ --query 'events[].message' --output text```
### Rollback plan
If the upgrade breaks something:
**Option A — Revert in CDK (preferred):**```typescript// Change back to the old runtimeruntime: lambda.Runtime.NODEJS_18_X,``````bashnpx cdk deploy```
**Option B — Instant rollback via CLI (faster, for emergencies):**```bash# Point $LATEST back to old runtimeaws lambda update-function-configuration \ --function-name <NAME> \ --region <REGION> \ --runtime nodejs18.x```Then fix CDK code to match and redeploy.
### Runtime-specific breaking changes to watch for
| Upgrade path | Common issues ||---|---|| nodejs18.x → nodejs20.x+ | `aws-sdk` v2 no longer bundled; must use `@aws-sdk/*` v3 or add a layer || nodejs20.x → nodejs22.x | Minor: `fetch` is globally available (good), some deprecated Node APIs removed || python3.9 → python3.11+ | `importlib` changes, some deprecated stdlib modules removed (`cgi`, `cgitb`) || python3.11 → python3.12+ | Removed `distutils`, `imp`; use `importlib` instead || Any → latest | Check Lambda runtime release notes for the specific version |
### Key question to ask
> "Your Lambda is on `<CURRENT_RUNTIME>`. The latest supported is `<LATEST>`. Would you like to upgrade? I'll create a rollback snapshot first so we can revert instantly if anything breaks."
## Step 9: Post-Import Improvements
After the import is stable, suggest these improvements to the user:
- **Switch to ARM** — Cost/performance improvement if the runtime supports it- **Upgrade runtime** — See Step 8 above- **Add monitoring** — Error alarms, throttle alarms on the Lambda- **Add tags** — Project, team, cost-center tags- **Refactor to grant methods** — Now that import is done, `logGroup.grantWrite(role)` is cleaner than inline policies- **Parameterize** — Move hardcoded values (memory, timeout, env vars) to config- **Add a DLQ** — If async invocation is used and no DLQ exists
## Resources NOT supported by cdk import
These must be referenced via `fromXxx()` methods instead:
- Lambda Event Source Mappings (manage separately or recreate)- Lambda Permissions (resource-based policies) — CDK recreates these- API Gateway resources (complex; often better to recreate)- CloudWatch Alarms (recreate in CDK)- EventBridge Rules (recreate in CDK)
For these, define them in CDK and let CDK create them fresh on deploy. They'll replace the manually-created equivalents.
## Edge Cases
- **Lambda with container image**: Use `lambda.Code.fromEcrImage()` instead of `fromAsset()`. The ECR repo should be referenced via `fromRepositoryName()`.- **Lambda@Edge**: Must be deployed in us-east-1 regardless of where other resources are.- **Lambda with SnapStart**: Set `snapStart` property in CDK.- **Function URL configured**: Import doesn't cover function URLs. Recreate in CDK if needed.- **Multiple aliases/versions**: Only `$LATEST` is imported. Aliases need to be recreated.- **Provisioned concurrency**: Not part of the function resource. Add after import.
## Step 10: Optional Code Modernization
After the import is stable and verified, offer the customer a choice to modernize both the CDK infrastructure code and the Lambda application code. The goal is to bring everything to a current, maintainable state — not just wrap legacy code in IaC.
### When to offer
Always offer this step after a successful import. Present it as optional:
> "Your resources are now managed by CDK. Would you also like to modernize the code? I can either:>> I'll review and update the CDK stack and Lambda code right now (runtime upgrades, dependency updates, best practice fixes).>> Or skip this step entirely if you're happy with the current state."
---
### Kiro-Driven Modernization
Kiro performs the modernization inline in this session. This is best for single-repo, immediate improvements.
**What Kiro does:**
1. **Lambda runtime upgrade** — Follow Step 8 (investigate breaking changes, snapshot, upgrade, verify)2. **Dependency updates** — Update `package.json` / `requirements.txt` to latest compatible versions, pin versions exactly3. **CDK best practices** — Apply cdk best practices4. **Code quality** — Fix deprecated API usage, apply secure coding patterns, improve error handling and logging5. **Security hardening** — Remove overly broad IAM permissions, add encryption, fix insecure patterns found in the Lambda code
After each change, Kiro builds, tests (if tests exist), and verifies with `cdk diff` + `cdk deploy`.
## Output
After completing the workflow, the user should have:- A working CDK project managing their previously-ClickOps resource- `cdk diff` showing no drift- Confirmation the resource still works- A clear path to making changes via code going forward- **(If modernization chosen):** Modernized Lambda code and CDK stack with latest runtimes, patched dependencies, and best practices applied
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article