How to debug AWS CDK Typescript app with VSCode debugger

Engineer
3 min readFeb 7, 2023

--

VSCode comes with a built-in debugger which comes in handy whenever you get an unexpected behaviour in your code and you’d like to dig in. Since CDK allows us to use a general purpose programming language (e.g. TypeScript), this VSCode feature can be useful for infrastructure code as well.

Suppose you have a stack like this

import { Duration, Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Runtime } from "aws-cdk-lib/aws-lambda";
import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs";
import { LambdaIntegration, LambdaRestApi, RestApi } from "aws-cdk-lib/aws-apigateway";

import * as path from 'path'

export class LambdaProjectStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);


const getFunction = new NodejsFunction(this, 'GetFunction', {
memorySize: 1024,
timeout: Duration.seconds(5),
runtime: Runtime.NODEJS_16_X,
entry: path.join(__dirname, '../resources/TestHandler.ts'),
handler: "getFunction",
bundling: {
minify: true,
externalModules: ['aws-sdk'],
},
});

}
}

Debugging

Okay now that we have a project configured, let’s setup debugging! To do this in VSCode, create a new folder .vscode and add a file to it called launch.json

mkdir .vscode/
touch .vscode/launch.json

In the launch.json file we need to add the following contents.

{
"version": "0.2.0",
"configurations": [

{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"runtimeArgs": [
"-r", "./node_modules/ts-node/register/transpile-only"
],
"args": [
"${workspaceFolder}/bin/aws-cdk-vscode-example.ts"
]
}
]
}

NOTE: You will need to change aws-cdk-vscode-example.ts if this is not the name of the .ts file that is within the bin/ directory.

With debugging configuration setup we’re now able to add breakpoints within the CDK code and then get all the fantastic utilities that come from that available to us.

Try this yourself by setting a breakpoint on the API gateway resource; just click on the green arrow in the debug panel:

You should see the debugger fire up and halt where ever you set the breakpoint. This allows you to explore the call stack and variables that are in memory at that point of compilation.

Summary

If you’re a heavy user of CDK you will likely run into problems occasionally that are just too difficult to resolve by analyzing CloudFormation failed stack logs. Instead it can be really handy to have this debugging technique handy to check underlying objects in memory are in fact doing what they should be doing.

What did you think of this tip? Did it help you? I’d love to hear about other awesome tricks you use in CDK development, please hit me up on Twitter @erkamaloffial

--

--

Engineer
Engineer

Written by Engineer

Blockchain & MERN Stack Developer || Web3 || AWS || Typescript || NFT

No responses yet