Quick AWS CDK
Posted on October 2, 2021
Tags: aws
1 Theory
- In a way CDK is like typescript for Cloudformation
- use
cdk synth
like typescript’stsc
to generate the Cloudformation template - run Cloudformation template to spin up resources
- use
- Constructs : Basic reusable building blocks
- L1 Constructs : one-to-one mapping to cloudformation resources, starts with
Cfn
like `CfnResolver - L2 Constructs : Pre-configured popular default settings on L1 constructs
- L3 Constructs : Composed out of L2 and L1 constructs
- Stacks - made out of Constructs
- L1 Constructs : one-to-one mapping to cloudformation resources, starts with
2 Practical
to use cdk install it with
npm install -g aws-cdk
cdk ls # list stacks
cdk destroy
3 Example
3.1 Spinning up S3 bucket
cdk init app --language typescript
cdk bootstrap
#bootstrap creates a s3 bucket called cdk-hnb659fds-assets-729330484136-us-east-1,
#SO DONT JUST willy nilly delete s3 buckets
cdk synth
#this will compile the cloudformation templates in dir cdk.out
import * as cdk from 'aws-cdk-lib';
import {aws_s3} from 'aws-cdk-lib';
import { Construct } from 'constructs';
// import * as sqs from 'aws-cdk-lib/aws-sqs';
export class CloudFormationStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// The code that defines your stack goes here
// example resource
// const queue = new sqs.Queue(this, 'CloudFormationQueue', {
// visibilityTimeout: cdk.Duration.seconds(300)
// });
const mybucket = new aws_s3.Bucket(this,'MyFirstBucket',{
versioned: true,
removalPolicy: cdk.RemovalPolicy.DESTROY,
autoDeleteObjects: true,
;
})
} }
3.2 ec2 instance
4 troubleshooting
- Scenario: You start deleting all s3 buckets to clean your account
- problem: you keep getting error asking
did you bootstrap
from cdk - solution: delete your CDK toolkit stack via vscode aws plugin
- why: You deleted a CDK toolkit s3 bucket dependency thus corrupting the env, so now you need to clean slate it.
- problem: you keep getting error asking