AWS CDK v2: A Safe TypeScript Walkthrough

Build a small AWS CDK v2 stack in TypeScript, inspect its CloudFormation diff, bootstrap carefully, deploy with review, and clean it up safely.

published: reading time: 6 min read author: Geek Workbench updated: November 5, 2026
Quick Summary

Build a scratch SQS queue with AWS CDK v2 and TypeScript. Follow the path from synthesis through a reviewed CloudFormation change set, least-privilege bootstrap, deployment, and cleanup, with notes on approval prompts and data deletion.

AWS CDK v2: A Safe TypeScript Walkthrough

The AWS Cloud Development Kit (CDK) lets you describe AWS resources in a programming language and synthesize them into CloudFormation templates. This walkthrough sticks to TypeScript and CDK v2. It creates one SQS queue in a scratch account, inspects the proposed change, and removes the stack when you are done.

Use an isolated account or sandbox. The commands below are examples, not something to paste into a production terminal. You need Node.js, npm, the CDK v2 CLI, and an AWS profile authorized to bootstrap and deploy to the target account. Do not put access keys in the source files.

Create the project

Make a new directory and initialize a TypeScript app:

mkdir scratch-queue
cd scratch-queue
cdk init app --language typescript

The initializer creates the app entry point and a stack under lib/. Replace its generated stack class with the one below. In the generated bin/ file, instantiate this class and replace both environment placeholders before running CDK commands:

import * as cdk from "aws-cdk-lib";
import { Queue } from "aws-cdk-lib/aws-sqs";
import { Construct } from "constructs";

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

    const queue = new Queue(this, "Jobs", {
      visibilityTimeout: cdk.Duration.seconds(30),
      removalPolicy: cdk.RemovalPolicy.DESTROY,
    });

    new cdk.CfnOutput(this, "QueueUrl", {
      value: queue.queueUrl,
    });
  }
}

The generated app entry point should create the stack with the target environment:

const app = new cdk.App();

new ScratchQueueStack(app, "ScratchQueueStack", {
  env: { account: "<ACCOUNT_ID>", region: "<REGION>" },
});

Replace <ACCOUNT_ID> with the 12-digit account ID and <REGION> with the target region. They are placeholders, not valid deployment settings. The account and region should match the profile and environment you intend to change.

Synthesize and inspect the diff

First synthesize locally:

cdk synth ScratchQueueStack

Synthesis writes a CloudFormation template to cdk.out/. Review the resource types, properties, and IAM changes in that template. Synthesis catches some app errors; it does not prove a deployment will succeed or that the stack is safe.

Bootstrap the target account and region before deploying. CDK creates a CDKToolkit CloudFormation stack with resources used to publish templates and assets. The default CloudFormation execution policy is AdministratorAccess, so the default is not least privilege.

Set these placeholders to the AWS CLI profile, target account, region, and a managed execution-policy ARN reviewed for this workload:

export AWS_PROFILE="<PROFILE_NAME>"
export CDK_ACCOUNT_ID="<ACCOUNT_ID>"
export CDK_REGION="<REGION>"
export EXECUTION_POLICY_ARN="<REVIEWED_LEAST_PRIVILEGE_POLICY_ARN>"

aws sts get-caller-identity
cdk bootstrap "aws://$CDK_ACCOUNT_ID/$CDK_REGION" \
  --cloudformation-execution-policies "$EXECUTION_POLICY_ARN"

Replace every placeholder before running the commands. Check the identity output and confirm its account matches CDK_ACCOUNT_ID and the selected profile is the intended one. The policy must allow the CloudFormation actions and resource changes this app needs, including any required rollback or deletion actions. A policy that is too narrow can leave a failed deployment requiring manual recovery. Review bootstrap trust as well: an account listed as trusted can use the permissions granted by the execution policy. Do not add cross-account trust unless those accounts and permissions are approved.

Now compare the local stack with its deployed state:

cdk diff ScratchQueueStack --method=change-set

A change-set diff gives more accurate resource replacement information than a template-only comparison. The command needs enough permissions to create the change set; if it cannot, fix the permissions before approving a deployment. Read every [+], [-], and [~] entry. Check whether a change replaces a resource, deletes one, broadens access, or affects data you need to keep. A property update can replace a resource even when the logical resource still appears in the template.

Deploy with a human review

The CLI’s default --require-approval mode is broadening. It prompts for changes that broaden permissions or security-group rules; it does not ask for approval for every change. That prompt is not a general protection against replacement or data loss.

For this scratch example, require a prompt for any change:

cdk deploy ScratchQueueStack --require-approval any-change

CDK presents a change set and waits for confirmation. Review it against the diff and cancel if the account, resources, replacement behavior, or access changes are unexpected. The any-change option makes the CLI prompt for all changes, but the operator still has to understand what the change set will do. Do not use --require-approval never as a shortcut around review.

CloudFormation can replace a resource during an update when a property requires replacement. A stack update may then remove the old physical resource. A DeletionPolicy: Retain controls deletion when a resource is removed from a stack, but does not protect a physical resource that is replaced during an update. Check the CDK diff command reference, deploy approval options, and CloudFormation’s DeletionPolicy documentation before approving changes to stateful resources.

Clean up the scratch stack

Before destroying a stack, confirm the AWS profile and stack name. CDK asks for confirmation unless you pass --force. CloudFormation deletes stack resources unless a retention policy says otherwise. For this example, destroying the stack deletes the SQS queue and any messages still in it.

For a stack with data you need, decide how each resource should be handled before cleanup. Retain leaves the resource in the account outside the stack, where it may continue to incur charges; a snapshot policy is available only for supported resource types. Retention is a lifecycle choice, not a backup plan. Make and verify any required backup before deleting the stack.

If the scratch queue has no messages you need and the diff confirms the intended target, remove only this stack:

cdk destroy ScratchQueueStack

Do not add --force to skip the prompt. The shared CDKToolkit bootstrap stack is separate from the app stack and is not removed by this command.

CDK, Terraform, or Pulumi?

Choose When it fits
AWS CDK v2 Your infrastructure targets AWS, and you want to define it in TypeScript while deploying through CloudFormation.
Terraform You want one provider-based workflow across cloud platforms or prefer HCL.
Pulumi You want general-purpose programming languages and a provider-based infrastructure workflow.

All three can describe infrastructure as code. The choice depends on the providers you need, the language your team wants to maintain, and the deployment/state model you prefer.

Recap

  1. Initialize a TypeScript CDK v2 app and create a small stack.
  2. Run cdk synth, then bootstrap the target environment with a reviewed execution policy and limited trust.
  3. Run a change-set diff and inspect replacements, deletions, data retention, and permission changes.
  4. Deploy with an interactive review, then destroy only the scratch stack after checking for data you need to keep.

For the full command details, see the official CDK v2 tutorial, bootstrap reference, CDK security best practices, and the SQS Queue API reference.

Category

Related Posts

AWS Compute Choices for DevOps Workloads

Choose compute for a small web and order workload with a practical guide to EC2, ECS, Fargate, EKS, Lambda, and S3's supporting role.

#aws #cloud #devops

IaC Module Design: Reusable and Composable Infrastructure

Design Terraform modules that are reusable, composable, and maintainable—versioning, documentation, and publish patterns for infrastructure building blocks.

#terraform #iac #modules

IaC State Management: Remote Backends and Team Collaboration

Manage Terraform/OpenTofu state securely with remote backends, state locking, and strategies for team collaboration without state conflicts.

#terraform #iac #state-management