L1 (Level 1) constructs are direct CloudFormation resource mappings, prefixed with 'Cfn' (e.g., CfnBucket, CfnFunction). They expose every CloudFormation property with no defaults or convenience methods. Use L1 when: (1) new AWS service not yet in L2, (2) need specific CloudFormation property not exposed in L2, (3) migrating from CloudFormation (1:1 mapping), (4) debugging L2/L3 issues. L1 requires configuring everything manually.
AWS Cdk FAQ & Answers
26 expert AWS Cdk answers researched from official documentation. Every answer cites authoritative sources you can verify.
Jump to section:
constructs
4 questionsL2 (Level 2) constructs are intent-based abstractions with sensible defaults, helper methods, and best-practice security policies. Example: new s3.Bucket(this, 'MyBucket') creates a bucket with encryption, versioning options, lifecycle rules, all configurable. L2 hides boilerplate: creating a VPC with L1 requires separately defining subnets, route tables, internet gateways. L2 Vpc construct handles all of this automatically. Most daily CDK development uses L2.
L3 constructs, also called patterns, combine multiple L1/L2 constructs into complete solutions. Example: ecsPatterns.ApplicationLoadBalancedFargateService creates a Fargate service, ECS cluster, ALB, target groups, security groups, and IAM roles in one construct. Other examples: LambdaRestApi (API Gateway + Lambda), QueueProcessingFargateService (SQS + Fargate). L3 provides least flexibility but fastest deployment for common architectures.
AWS Solutions Constructs are vetted, tested L3 patterns from AWS for common architectures. Examples: aws-lambda-dynamodb (Lambda writing to DynamoDB with proper IAM), aws-apigateway-lambda (API Gateway to Lambda with best practices), aws-sqs-lambda (SQS queue triggering Lambda with DLQ). Available at construct.dev. Follow Well-Architected Framework. Separate from core CDK library - install individually.
configuration
4 questionsCDK context stores key-value pairs for your app. Sources (in precedence order): construct.node.setContext(), --context CLI flag, cdk.context.json, cdk.json, ~/.cdk.json. CDK uses context to cache AWS account lookups (AZs, AMI IDs) in cdk.context.json, ensuring deterministic synthesis. Access values with this.node.tryGetContext('keyName'). Context values from CLI are always strings - parse if needed.
When using .fromLookup() methods (e.g., Vpc.fromLookup(), HostedZone.fromLookup()), CDK queries your AWS account and caches results in cdk.context.json. This ensures future synthesis produces identical templates regardless of account state changes. To refresh cached values: cdk context --clear or delete specific keys. Values in cdk.json cannot be cleared (use for permanent config).
Use the Tags class with Aspects: Tags.of(scope).add('Environment', 'Production') adds tag to all taggable resources in scope. Apply at app level for all stacks, or stack level for specific stacks. Tags can have include/exclude filters: Tags.of(app).add('CostCenter', '123', {excludeResourceTypes: ['AWS::CloudWatch::Alarm']}). Tags propagate to child constructs.
RemovalPolicy controls what happens when resource is removed from stack or stack is deleted. Options: DESTROY (delete resource), RETAIN (keep resource, orphan from CloudFormation), SNAPSHOT (RDS/EBS only - create snapshot then delete). Set with removalPolicy: RemovalPolicy.RETAIN. Default varies by resource - stateful resources (S3, RDS) default to RETAIN for safety, others to DESTROY.
operations
3 questionscdk diff compares your CDK app against deployed CloudFormation stack, showing what will change without deploying. Output shows resources to add (+), remove (-), or modify (~). Use before deploy to catch unexpected changes. Also useful: cdk diff --security-only shows only IAM/security group changes. cdk diff --fail exits non-zero if changes exist (for CI gates).
cdk watch monitors your code and auto-deploys changes. Uses watch settings in cdk.json to determine which files trigger deployment. For Lambda: uses hotswap deployment (updates function code without full CloudFormation update) for sub-10-second deploys. Falls back to full deployment for infrastructure changes. Great for iterative development. Disable hotswap with --no-hotswap for production-like deploys.
cdk synth synthesizes your CDK app into CloudFormation templates. Output goes to cdk.out/ directory containing: template JSON for each stack, asset manifests, tree.json (construct tree). For debugging: cdk synth --verbose shows synthesis details. cdk synth StackName synthesizes specific stack. Template output can be deployed directly via CloudFormation console if needed.
advanced
2 questionsEscape hatches let you modify CloudFormation properties not exposed by L2/L3 constructs. Access the underlying L1 with bucket.node.defaultChild as s3.CfnBucket, then use: (1) addOverride('Properties.Foo', 'value') - set any property path, (2) addPropertyOverride('Foo', 'value') - shortcut for Properties.*, (3) addDeletionOverride('Properties.Foo') - remove a property. Use dot notation for nested paths: addPropertyOverride('VersioningConfiguration.Status', 'Enabled').
Aspects apply operations to all constructs in a scope during synthesis. Use cases: (1) Tagging - add mandatory tags to all taggable resources, (2) Validation - verify all S3 buckets are encrypted, (3) Modification - set specific IAM role names. Apply with Aspects.of(scope).add(new MyAspect()). Aspects run in the 'prepare' phase before CloudFormation generation. Implement by extending IAspect interface with a visit(node) method.
testing
2 questionsTwo test categories: (1) Fine-grained assertions - test specific CloudFormation properties using Template.fromStack(stack).hasResourceProperties('AWS::S3::Bucket', {VersioningConfiguration: {Status: 'Enabled'}}). Most commonly used, catches regressions. (2) Snapshot tests - compare entire synthesized template against baseline. Good for refactoring confidence. Use Jest (TypeScript), pytest with syrupy (Python), JUnit (Java). Import assertions module: aws_cdk.assertions (Python) or aws-cdk-lib/assertions (TypeScript).
Integration tests deploy actual AWS resources to validate IAM policies, service limits, and runtime behavior. Use @aws-cdk/integ-tests-alpha construct library. Define test as a CDK app with one-to-one relationship. Run with integ-runner which handles provisioning and teardown. Test deployed resources with assertions. Example: deploy Lambda, invoke it, assert response matches expected output. Complements unit tests that only validate CloudFormation templates.
deployment
2 questionsCDK Pipelines creates CI/CD pipelines that deploy to multiple accounts/regions. Enable with crossAccountKeys: true in pipeline configuration. Requires bootstrapping target accounts to trust the pipeline account: cdk bootstrap aws://STAGING_ACCOUNT/REGION --trust PIPELINE_ACCOUNT. The pipeline assumes cross-account roles created during bootstrap. Define stages for each environment: pipeline.addStage(new MyAppStage(this, 'Staging', {env: {account: 'staging-id'}}).
Bootstrap (cdk bootstrap) provisions resources CDK needs to deploy: S3 bucket for assets, ECR repo for Docker images, IAM roles for deployment. Run once per account/region combination before first deploy. For cross-account: cdk bootstrap aws://TARGET/REGION --trust SOURCE_ACCOUNT --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess. Creates CDKToolkit CloudFormation stack.
bundling
2 questionsNodejsFunction automatically bundles TypeScript/JavaScript Lambda code using esbuild. It tree-shakes unused code, produces smaller packages. If esbuild is available locally, bundling happens natively. Otherwise, CDK uses Docker with Lambda-compatible environment. Force Docker with bundling: {forceDockerBundling: true} - useful for native dependencies (sharp, bcrypt). Supports automatic dependency installation from package.json.
PythonFunction (from @aws-cdk/aws-lambda-python-alpha) automatically bundles Python Lambdas. If requirements.txt or Pipfile exists at entry path, CDK runs pip install in Lambda-compatible Docker container. Dependencies are packaged with your code. For custom bundling, use bundling option on Code.fromAsset() with commands that read from /asset-input and write to /asset-output.
patterns
2 questionsUse .from*() static methods to reference resources by ARN, ID, or name without managing them: Bucket.fromBucketName(this, 'Existing', 'bucket-name'), Vpc.fromLookup(this, 'Vpc', {vpcId: 'vpc-123'}), Function.fromFunctionArn(this, 'Fn', 'arn:...'). These create IResource interfaces for read-only access. Can grant permissions to/from referenced resources.
CDK automatically manages dependencies when you pass resources between stacks (e.g., passing a Bucket to another stack creates export/import). Explicit dependency: stackB.addDependency(stackA). For cross-stack references, CDK creates CloudFormation exports. View dependency order: cdk list --long shows deployment order. Circular dependencies cause synthesis errors - restructure using SSM parameters or explicit ARNs.
languages
1 questionAWS CDK v2 officially supports 5 languages (Tier 1): TypeScript (primary, best docs, fastest updates), Python (snake_case conventions, boto3 integration), Java (Maven/Gradle, Java 17-21), C# (.NET 6-8, Visual Studio integration), and Go (added 2022, Go 1.21+). JavaScript works but TypeScript is recommended. All Tier 1 languages have full L1/L2/L3 construct support, same-day AWS service updates, CDK Pipelines, and cross-language constructs via JSII.
architecture
1 questionJSII (JavaScript Interoperability Interface) enables CDK constructs written in TypeScript to be used from Python, Java, C#, and Go. The AWS Construct Library is written in TypeScript and JSII automatically generates idiomatic bindings for other languages. Example: TypeScript new s3.Bucket(this, 'MyBucket', {versioned: true}) becomes Python s3.Bucket(self, 'MyBucket', versioned=True) or Java Bucket.Builder.create(this, "MyBucket").versioned(true).build().
security
1 questioncdk-nag validates CDK constructs against security/compliance rules using Aspects. It includes NagPacks for: AWS Solutions, HIPAA Security, NIST 800-53 rev 4 & 5, PCI DSS 3.2.1. Usage: Aspects.of(app).add(new AwsSolutionsChecks({verbose: true})). Running cdk synth then shows warnings/errors for non-compliant resources. Rules can be errors (block deployment) or warnings. Supports suppressions for documented exceptions.
migration
1 questionThree methods: (1) cdk import - import existing resources into CDK stack with minimal disruption. Specify resource identifiers and CDK adds them to CloudFormation state. (2) CfnInclude - import existing CloudFormation template into CDK as L1 constructs. Good for gradual migration. (3) IaC Generator (Feb 2024) - generates CDK apps from deployed resources automatically. Also: cdk migrate generates CDK app from deployed CloudFormation stack.