Sub topic 1
Why Infrastructure as Code and Where CloudFormation Fits
Prerequisites
This chapter assumes basic knowledge of AWS services such as S3, Lambda, and IAM. You should also know TypeScript or Python, use a terminal, and have Node.js and configured AWS credentials available.
Infrastructure as Code
Infrastructure as code (IaC) is the practice of defining cloud resources in files instead of creating them manually in a console. The files can be reviewed, tested, versioned, and reused.
AWS CloudFormation is AWS's managed IaC service. A CloudFormation template describes resources and their settings. CloudFormation then creates and updates those resources as a stack, which is a managed group of resources.
The AWS Cloud Development Kit (CDK) sits above CloudFormation. You write TypeScript or Python code, and the CDK synthesizes that code into a CloudFormation template.
The CDK Workflow
The CDK app is evaluated locally. During synthesis, it builds a construct tree and produces a cloud assembly containing CloudFormation templates and deployment assets. The CDK CLI then uses those outputs to compare or deploy changes.
Install the CLI and create a TypeScript project:
npm install -g aws-cdk
mkdir my-app && cd my-app
cdk init app --language typescript
cdk synthUse --language python to create a Python project. cdk synth does not change AWS. It generates and validates the template locally.
Apps, Stacks, and Constructs
An App is the root of a CDK program. A Stack is a deployable CloudFormation unit. Constructs are reusable building blocks placed inside stacks. Together, they form the construct tree.
const app = new cdk.App();
const stack = new cdk.Stack(app, "WebStack");
const bucket = new s3.Bucket(stack, "Uploads");L1, L2, and L3 Constructs
- L1 constructs map directly to CloudFormation resources, such as
CfnBucket. They provide detailed control. - L2 constructs provide typed APIs and secure, useful defaults, such as
s3.Bucket. - L3 constructs combine multiple resources into a higher-level pattern, such as an application load-balanced service.
Prefer L2 constructs for ordinary resources. Use L1 when an L2 lacks a required feature, and L3 when a repeated architecture deserves a reusable abstraction.
Exercise
Which CDK command generates a CloudFormation template without deploying resources?
Show answer
cdk synth.