#AWS CDK
Infrastructure as Code using programming languages.
#Overview
CDK synthesizes CloudFormation from TypeScript, Python, Java, etc.
#Installation
bash
npm install -g aws-cdk
cdk --version#TypeScript Example
typescript
1// lib/mystack.ts
2import * as cdk from 'aws-cdk-lib';
3import * as ec2 from 'aws-cdk-lib/aws-ec2';
4import * as s3 from 'aws-cdk-lib/aws-s3';
5import { Construct } from 'constructs';
6
7export class MyStack extends cdk.Stack {
8 constructor(scope: Construct, id: string, props?: cdk.StackProps) {
9 super(scope, id, props);
10
11 // Create VPC
12 const vpc = new ec2.Vpc(this, 'MyVpc', {
13 maxAzs: 2,
14 });
15
16 // Create S3 bucket
17 const bucket = new s3.Bucket(this, 'MyBucket', {
18 versioned: true,
19 encryption: s3.BucketEncryption.S3_MANAGED,
20 });
21 }
22}#Commands
bash
1# Initialize project
2cdk init app --language typescript
3
4# Synthesize CloudFormation
5cdk synth
6
7# Deploy
8cdk deploy
9
10# Diff
11cdk diff
12
13# Destroy
14cdk destroy#CDK vs Terraform
| Feature | CDK | Terraform |
|---|---|---|
| Languages | TS, Python, Java | HCL |
| Target | CloudFormation | Multi-cloud |
| Abstraction | L2 constructs | Resources |
[!TIP] Pro Tip: CDK is excellent for complex AWS apps with shared constructs!