7.3 Infrastructure as Code with AWS CDK

Key Takeaways

  • AWS CDK allows developers and CloudOps engineers to define infrastructure using general-purpose programming languages (TypeScript, Python, Java, C#, Go) while synthesizing standard CloudFormation templates.
  • The CDK construct tree organizes architecture hierarchically from the root App to Stacks (CloudFormation deployment units) and Constructs.
  • Constructs span three abstraction levels: L1 (raw Cfn primitives with 1:1 CloudFormation mappings), L2 (AWS curated constructs with security defaults and grant methods), and L3 (architectural solutions patterns).
  • Core CDK CLI commands include cdk init (scaffolding), cdk synth (compiling templates to cdk.out), cdk diff (evaluating deltas against active stacks), cdk deploy (orchestrating CloudFormation updates), and cdk destroy (teardown).
  • The cdk bootstrap command establishes dedicated S3 buckets, ECR repositories, and IAM roles in target AWS environments to manage CloudFormation template assets and container images.
Last updated: September 2026

7.3 Infrastructure as Code with AWS CDK

CloudOps Blueprint Focus: As cloud operations modernize, defining infrastructure using general-purpose programming languages has become standard enterprise practice. On the AWS Certified CloudOps Engineer – Associate (SOA-C03) exam, you must understand the relationship between the AWS Cloud Development Kit (CDK) and CloudFormation, navigate the construct hierarchy (L1, L2, L3), execute core CDK CLI commands, and manage the bootstrapping architecture required for deployment assets.

The AWS CDK Architecture & CloudFormation Relationship

The AWS Cloud Development Kit (CDK) is an open-source software development framework that allows engineers to model and provision cloud application infrastructure using familiar, object-oriented programming languages including TypeScript, JavaScript, Python, Java, C#, and Go.

Using general-purpose programming languages provides significant operational advantages over static JSON/YAML templates:

  • Code Reuse & Abstraction: Create reusable classes, loops, conditionals, and object-oriented inheritance models.
  • Modern Tooling: Leverage native package managers (npm, pip, Maven, NuGet), integrated linters, type checkers, and unit testing frameworks (Jest, pytest).
  • Integrated Logic: Construct dynamic resource configurations without awkward JSON/YAML macros.

The Operational Reality: CDK Synthesizes CloudFormation

A critical concept for CloudOps engineers is that AWS CDK does not make direct AWS API calls to provision or manage infrastructure resources. Instead, CDK is a compiler and synthesis engine:

  1. The engineer executes the CDK CLI (cdk synth or cdk deploy).
  2. The CDK application executes and compiles the construct code tree into standard CloudFormation templates and asset bundles in the local cdk.out directory.
  3. The CDK CLI submits these synthesized templates to AWS CloudFormation.
  4. AWS CloudFormation executes the deployment, managing resource provisioning, state tracking, dependency graphs, and automated rollbacks.

CloudFormation remains the ultimate deployment engine and system of record for all CDK applications.


The Core CDK Hierarchy: App, Stack & Environment

A CDK application is structured as an inverted construct tree with three fundamental structural tiers:

  • App: The root construct container of any CDK application. The App manages one or more Stack constructs and defines the overall application boundary.
  • Stack: The unit of deployment in AWS CDK. Every CDK Stack maps 1:1 to an underlying AWS CloudFormation stack. All resources declared inside a CDK Stack are synthesized into a single CloudFormation template. Stacks can reference resources from other stacks; CDK automatically establishes cross-stack references using CloudFormation exports (Export: Name) and imports (Fn::ImportValue).
  • Environment: Configured on each Stack to designate the target AWS Account ID and AWS Region (env: { account: '123456789012', region: 'us-east-1' }). Stacks without an explicit environment are environment-agnostic (synthesizing templates that utilize pseudo parameters like AWS::AccountId and AWS::Region), while environment-specific stacks can query live VPCs, AMIs, and hosted zones at synthesis time via context providers.

The Three-Tier Construct Levels Hierarchy

In AWS CDK, everything is a Construct. Constructs represent cloud components and are categorized into three levels of abstraction:

Construct LevelClass NamingAbstraction DepthSecurity Defaults & Helper MethodsPrimary Use Case
Level 1 (L1)Prefixed with Cfn (e.g., CfnBucket, CfnVPC, CfnInstance)Low-level (1:1 mapping) to raw CloudFormation resource types.No defaults. Requires manual specification of all required CloudFormation properties. No helper methods.When newly released CloudFormation properties are not yet supported by L2 constructs.
Level 2 (L2)AWS Curated (e.g., s3.Bucket, ec2.Vpc, iam.Role)High-level, opinionated abstractions maintained by AWS.Sensible security defaults (encryption enabled, public access blocked). Includes helper methods and IAM grant methods (bucket.grantRead(role)).Standard day-to-day infrastructure provisioning. The primary construct level for CloudOps engineers.
Level 3 (L3)Solutions / Patterns (e.g., ApplicationLoadBalancedFargateService)Architectural patterns composed of multiple L2 constructs.Pre-wired multi-service architecture. Automatically configures ALBs, ECS tasks, target groups, security groups, and DNS.Rapid deployment of common architectures with minimal boilerplate code.

L2 Constructs in Action: Granular IAM & Defaults

L2 constructs eliminate hundreds of lines of boilerplate. For example, instantiating new ec2.Vpc(this, 'AppVPC') automatically creates a multi-AZ VPC, public and private subnets, internet gateways, NAT gateways, and route tables with optimal CIDR allocations. Furthermore, calling myBucket.grantRead(myRole) automatically generates the least-privilege IAM policy statement and attaches it to the role, avoiding manual IAM JSON authoring.


CDK CLI Lifecycle & Workflow Commands

The CDK Command Line Interface (CLI) drives the development and deployment lifecycle:

  • cdk init: Initializes a new CDK project from a template in the specified language (e.g., cdk init app --language typescript).
  • cdk synth: Executes the application and synthesizes CloudFormation templates into the cdk.out directory. Validates template syntax and construct logic locally without interacting with live AWS resources.
  • cdk diff: Compares the local synthesized template against the currently deployed CloudFormation stack in AWS. It displays a color-coded delta showing resource additions, modifications, and deletions, and explicitly highlights security-sensitive changes (such as altered IAM statements or broadened security group ingress rules).
  • cdk deploy: Synthesizes the template, packages and uploads deployment assets, and initiates the CloudFormation stack deployment. By default, it prompts for interactive approval when security-sensitive changes are detected (can be bypassed in CI/CD using --require-approval never).
  • cdk destroy: Deletes the deployed CloudFormation stack and tears down managed resources.

CDK Bootstrapping Architecture: CDKToolkit & Assets

CDK applications frequently bundle external assets, such as AWS Lambda function code directories, Docker container build contexts, or CloudFormation templates exceeding the 50 KB direct upload limit.

To manage these assets, the target AWS account and Region must be initialized using the cdk bootstrap command (cdk bootstrap aws://123456789012/us-east-1).

Resources Provisioned by the CDKToolkit Bootstrap Stack

Bootstrapping provisions a dedicated CloudFormation stack named CDKToolkit in the target environment, creating:

  1. Amazon S3 Bucket: Stores synthesized CloudFormation templates and compressed Lambda function zip archives.
  2. Amazon ECR Repositories: Stores Docker container images built by the CDK CLI for ECS or Lambda container deployments.
  3. IAM Roles: Creates dedicated deployment and publishing roles (cdk-*-deploy-role, cdk-*-file-publishing-role, cdk-*-image-publishing-role, cdk-*-lookup-role) with defined trust policies, enabling secure cross-account deployments within AWS Organizations.

Bootstrapping must be executed once per target account/Region before deploying CDK applications that utilize assets or large templates.

Test Your Knowledge

A developer is writing an AWS CDK application in TypeScript to provision an S3 bucket. The developer wants the bucket to automatically enforce server-side encryption, block all public access, and leverage built-in IAM grant helper methods such as bucket.grantRead(role) rather than writing raw CloudFormation IAM JSON policies. Which level of CDK construct should the developer use?

A
B
C
D
Test Your Knowledge

A DevOps engineer is preparing to deploy an AWS CDK application containing Docker container assets and Lambda functions to a newly created AWS account and Region. When running cdk deploy, the command fails with an error stating that the bootstrap stack is missing. What does the engineer need to do to resolve this issue, and what does the resolution command accomplish?

A
B
C
D
Test Your Knowledge

Before deploying a modified AWS CDK application to a staging environment, an automated CI/CD pipeline step must compare the synthesized CloudFormation template against the live deployed stack and highlight any newly introduced IAM permission grants or security group openings. Which CDK CLI command executes this comparison?

A
B
C
D