ရိုးရိုးလေး ရှင်းပြမယ်
CDK ကို ရိုးရိုးလေး
ယခင်သင်ခန်းစာက CloudFormation template ကို ဇယားကွက် ဖြည့်ရတဲ့ form ကြီးတစ်ခုလို့ မြင်ကြည့်ပါ — box တိုင်းကို ကိုယ်တိုင် ဖြည့်ရပါတယ်။ AWS CDK ကတော့ အဲဒီ form ကို ဖြည့်ပေးတဲ့ ဉာဏ်ကောင်းတဲ့ assistant လိုပါပဲ။ 'ဒီ Lambda function ကို ဒီ table ကို ဖတ်ရေးခွင့်ပေး' လို့ ပြောလိုက်ရုံနဲ့ IAM role, policy, ARN တွေကို မှန်မှန်ကန်ကန် ဖြည့်ပေးပါတယ်။
CDK code ကို TypeScript, Python, Java, C#, Go လို language တွေနဲ့ ရေးလို့ရပြီး နောက်ဆုံးမှာ CloudFormation template ပဲ ထွက်လာပါတယ်။ ဒါကြောင့် ယခင်သင်ခန်းစာက change set, rollback, DeletionPolicy အကုန်လုံး ဒီမှာလည်း အလုပ်လုပ်ပါတယ် — CDK က အပေါ်ကနေ loop, function, class, unit test တွေကို ထပ်ပေါင်းပေးတာပါ။
Problem → Why → Solution
YAML ကြီးထွားလာတဲ့အခါ
Lambda function တစ်ခုက DynamoDB table တစ်ခုကို ရေးနိုင်အောင် လုပ်ဖို့ CloudFormation မှာ အောက်ကလို YAML လိုင်း ၅၀ နီးပါး လိုပါတယ် — role, trust policy, managed policy, inline policy, action စာရင်း၊ ARN reference တွေ အကုန် လက်နဲ့ ရေးရပါတယ်။ API Gateway ထပ်ထည့်ရင် resource, method, deployment, stage, permission တွေနဲ့ လိုင်း ၁၀၀ ထပ်တိုးပါတယ်။
Service ၁၀ ခုရှိရင် ဒီ pattern ကို ၁၀ ခါ copy-paste လုပ်ရပြီး တစ်နေရာမှာ action တစ်ခု ကျန်ခဲ့တာ၊ Resource: '*' လို့ ပျင်းပျင်းနဲ့ ရေးလိုက်တာမျိုး ဖြစ်လာပါတယ်။ YAML မှာ function မရှိလို့ ပြန်သုံးလို့ရတဲ့ အစိတ်အပိုင်း လုပ်ဖို့ ခက်ပြီး deploy မလုပ်ခင် logic ကို test လုပ်ဖို့ နည်းလမ်းလည်း မရှိပါဘူး။
AWSTemplateFormatVersion: "2010-09-09"
Description: One Lambda that may write to one table - every wire by hand
Resources:
OrdersTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: pk
AttributeType: S
KeySchema:
- AttributeName: pk
KeyType: HASH
HandlerRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: orders-table-rw
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
- dynamodb:Query
Resource: !GetAtt OrdersTable.Arn
Handler:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.12
Handler: index.handler
Role: !GetAtt HandlerRole.Arn
Timeout: 10
Environment:
Variables:
TABLE_NAME: !Ref OrdersTable
Code:
ZipFile: |
def handler(event, context):
return {"statusCode": 200}ဘာကြောင့် ဒါက ပြဿနာလဲ
Template ရဲ့ အများစုဟာ ကိုယ့် business logic မဟုတ်ဘဲ resource တွေကို တစ်ခုနဲ့တစ်ခု ချိတ်ပေးတဲ့ 'ဝါယာကြိုး' တွေပါ။ ဝါယာကြိုးကို လက်နဲ့ ဆွဲရင် အမှားဖြစ်ဖို့ လွယ်ပြီး ပြန်သုံးဖို့ ခက်ပါတယ်။ CDK က table.grantReadWriteData(handler) လို တစ်ကြောင်းတည်းနဲ့ least-privilege policy ကို ထုတ်ပေးပြီး pattern တွေကို class အဖြစ် ထုပ်ပိုး၊ npm package အဖြစ် share လုပ်ပြီး unit test လုပ်ခွင့်ပေးပါတယ်။
Construct, tree နဲ့ synth
CDK ရဲ့ အခြေခံ အုတ်ချပ်က construct ပါ။ Construct တိုင်းမှာ scope (မိဘ)၊ id (မိဘအောက်မှာ unique ဖြစ်တဲ့ နာမည်) နဲ့ props ရှိပါတယ်။ Construct တွေကို တစ်ခုထဲ တစ်ခု ထည့်လိုက်တော့ tree တစ်ခု ဖြစ်လာပါတယ် — အမြစ်မှာ App၊ အောက်မှာ Stack တွေ (stack တစ်ခု = CloudFormation stack တစ်ခု)၊ အဲဒီအောက်မှာ resource construct တွေ ရှိပါတယ်။ Tree ထဲက path (/OrdersStack-dev/Orders/Table) ကနေ CloudFormation logical ID ကို hash ပေါင်းပြီး တည်ငြိမ်အောင် ထုတ်ပေးပါတယ်။
Construct တွေဟာ ရိုးရိုး class တွေ ဖြစ်လို့ programming language တစ်ခုရဲ့ အားသာချက် အားလုံးကို ရပါတယ် — stage တစ်ခုချင်းအတွက် loop ပတ်တာ၊ props ကို type နဲ့ စစ်တာ၊ IDE ထဲမှာ autocomplete နဲ့ documentation ကြည့်တာ၊ မှားရေးထားတဲ့ property name ကို deploy မလုပ်ခင် compiler က ဖမ်းပေးတာ စတာတွေပါ။
| Level | ဘာလဲ | ဥပမာ |
|---|---|---|
| L1 (Cfn*) | CloudFormation resource တစ်ခုနဲ့ ၁:၁ တူတဲ့ class၊ default မရှိ | s3.CfnBucket, dynamodb.CfnTable |
| L2 | ရည်ရွယ်ချက်ကို ဖော်ပြတဲ့ API၊ လုံခြုံတဲ့ default နဲ့ grant* method တွေ | s3.Bucket, lambda.Function |
| L3 (pattern) | Resource အများကြီးကို architecture တစ်ခုအဖြစ် ပေါင်းထားတာ | ApplicationLoadBalancedFargateService, ကိုယ်ပိုင် OrdersApi |
cdk synth run လိုက်ရင် CDK က ကိုယ့် program ကို execute လုပ်ပြီး tree ကို ဆောက်၊ aspect တွေကို run၊ validate လုပ်ပြီး stack တစ်ခုချင်းအတွက် CloudFormation template (JSON) နဲ့ asset (Lambda code zip, Docker image) manifest တွေကို cdk.out directory ထဲ ရေးပါတယ်။ ဆိုလိုတာက CDK code ဟာ deploy-time မှာ run တာ မဟုတ်ဘဲ synth-time မှာ run ပါတယ်။ if (props.stage === 'prod') လို logic က template ကို ပုံဖော်ရုံပါ၊ AWS ပေါ်က တကယ့်တန်ဖိုး (ဥပမာ table name) တွေကတော့ synth ချိန်မှာ token လို့ခေါ်တဲ့ placeholder သာ ဖြစ်ပြီး deploy ချိန်မှပဲ resolve ဖြစ်ပါတယ်။
Deploy လုပ်တဲ့အခါ CDK CLI က asset တွေကို bootstrap လုပ်ထားတဲ့ S3 bucket/ECR repository ဆီ upload လုပ်ပြီး CloudFormation ကို change set နဲ့ deploy ခိုင်းပါတယ်။ ဒါကြောင့် CDK ဟာ CloudFormation ကို အစားထိုးတာ မဟုတ်ဘဲ အပေါ်က compiler တစ်ခုပါ။
FROM CODE TO STACKS
-------------------
app.ts (TypeScript) cdk synth cdk deploy
+----------------------+ +------------------+ +-------------------+
| App | | cdk.out/ | | CloudFormation |
| +- OrdersStack-dev | --> | *.template.json | --> | change set |
| | +- Orders (L3) | | *.assets.json | | -> stack events |
| | +- Table | | manifest.json | +-------------------+
| | +- Handler | +------------------+ ^
| | +- Api | | |
| +- OrdersStack-prod | +-- assets --> S3 / ECR -+
+----------------------+ (from cdk bootstrap)- Write constructs in code
- cdk synth -> templates in cdk.out
- cdk diff against deployed stack
- cdk deploy -> CloudFormation
ဘာပဲ ဖြစ်ဖြစ် cdk.out ထဲက template ကို ကြည့်လို့ရပါတယ် — CDK က ဘာလုပ်မလဲ မသေချာရင် synth လုပ်ပြီး JSON ကို ဖတ်ပါ။
L1, L2, L3 ကို ဘေးချင်းယှဉ်ကြည့်ခြင်း
import { Stack } from "aws-cdk-lib";
import * as ecs from "aws-cdk-lib/aws-ecs";
import * as ecsPatterns from "aws-cdk-lib/aws-ecs-patterns";
import * as s3 from "aws-cdk-lib/aws-s3";
const stack = new Stack();
// L1: a 1:1 mirror of AWS::S3::Bucket - every property is yours to set
new s3.CfnBucket(stack, "RawBucket", {
versioningConfiguration: { status: "Enabled" },
});
// L2: intent-based API with secure defaults and helper methods
new s3.Bucket(stack, "Bucket", {
versioned: true,
encryption: s3.BucketEncryption.S3_MANAGED,
enforceSSL: true,
});
// L3 pattern: VPC, cluster, ALB, Fargate service, roles and security groups
new ecsPatterns.ApplicationLoadBalancedFargateService(stack, "Web", {
taskImageOptions: {
image: ecs.ContainerImage.fromRegistry("public.ecr.aws/nginx/nginx:latest"),
},
publicLoadBalancer: true,
});Construct တိုင်းကို (scope, id, props) နဲ့ ဆောက်ပါတယ်။ L1 မှာ property အားလုံးကို ကိုယ်တိုင် သတ်မှတ်ရပြီး L2 က enforceSSL လို ရည်ရွယ်ချက်ကို ပြောရုံနဲ့ bucket policy ကို ထုတ်ပေးပါတယ်။ L3 တစ်ကြောင်းက resource ဒါဇင်နဲ့ချီ ထုတ်ပေးပါတယ်။
CDK app အပြည့်အစုံ — dev နဲ့ prod orders service
ဒီ app က ကိုယ်ပိုင် L3 construct (OrdersApi = REST API + Lambda + DynamoDB table) တစ်ခု ရေးပြီး stack နှစ်ခု (dev နဲ့ prod) မှာ ပြန်သုံးပါတယ်။ Prod မှာပဲ data ကို Retain နဲ့ point-in-time recovery နဲ့ ကာကွယ်ပြီး aspect တစ်ခုက recovery ပိတ်ထားတဲ့ table တိုင်းကို synth ချိန်မှာ warning ပြပါတယ်။ TypeScript ~၉၀ လိုင်းကနေ stack တစ်ခုချင်းမှာ CloudFormation resource ၁၆ ခု ထွက်လာပါတယ်။
import {
Annotations, App, Aspects, CfnOutput, Duration, IAspect, RemovalPolicy,
Stack, StackProps, Tags,
} from "aws-cdk-lib";
import * as apigw from "aws-cdk-lib/aws-apigateway";
import * as dynamodb from "aws-cdk-lib/aws-dynamodb";
import * as lambda from "aws-cdk-lib/aws-lambda";
import { Construct, IConstruct } from "constructs";
const HANDLER_CODE = `
import json, os
import boto3
table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])
def handler(event, context):
if event["httpMethod"] == "POST":
order = json.loads(event.get("body") or "{}")
table.put_item(Item={"pk": "ORDER#" + order["id"], "sk": "META", **order})
return {"statusCode": 201, "body": json.dumps({"id": order["id"]})}
return {"statusCode": 200, "body": json.dumps({"service": "orders"})}
`;
// L3: our own reusable pattern = REST API + Lambda + table, permissions wired
export class OrdersApi extends Construct {
public readonly table: dynamodb.Table;
public readonly url: string;
constructor(scope: Construct, id: string, props: { protectData: boolean }) {
super(scope, id);
this.table = new dynamodb.Table(this, "Table", { // L2
partitionKey: { name: "pk", type: dynamodb.AttributeType.STRING },
sortKey: { name: "sk", type: dynamodb.AttributeType.STRING },
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
pointInTimeRecoverySpecification: { pointInTimeRecoveryEnabled: props.protectData },
removalPolicy: props.protectData ? RemovalPolicy.RETAIN : RemovalPolicy.DESTROY,
});
const handler = new lambda.Function(this, "Handler", { // L2
runtime: lambda.Runtime.PYTHON_3_12,
handler: "index.handler",
code: lambda.Code.fromInline(HANDLER_CODE),
timeout: Duration.seconds(10),
environment: { TABLE_NAME: this.table.tableName },
});
this.table.grantReadWriteData(handler); // least-privilege IAM
const api = new apigw.LambdaRestApi(this, "Api", { handler });
this.url = api.url;
}
}
interface OrdersStackProps extends StackProps {
stage: "dev" | "prod";
}
export class OrdersStack extends Stack {
constructor(scope: Construct, id: string, props: OrdersStackProps) {
super(scope, id, props);
const orders = new OrdersApi(this, "Orders", { protectData: props.stage === "prod" });
new CfnOutput(this, "ApiUrl", { value: orders.url });
new CfnOutput(this, "TableName", { value: orders.table.tableName });
}
}
// Aspect: visits every construct before synthesis and flags risky settings
class TablesNeedRecovery implements IAspect {
public visit(node: IConstruct): void {
if (!(node instanceof dynamodb.CfnTable)) return;
const pitr = node.pointInTimeRecoverySpecification as
| dynamodb.CfnTable.PointInTimeRecoverySpecificationProperty
| undefined;
if (!pitr || pitr.pointInTimeRecoveryEnabled !== true) {
Annotations.of(node).addWarningV2("orders:pitr", "Point-in-time recovery is off");
}
}
}
const app = new App();
new OrdersStack(app, "OrdersStack-dev", {
stage: "dev",
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION,
},
});
new OrdersStack(app, "OrdersStack-prod", {
stage: "prod",
env: { account: "222233334444", region: "ap-southeast-1" },
});
Tags.of(app).add("service", "orders");
Aspects.of(app).add(new TablesNeedRecovery());
app.synth();Browser ထဲမှာ run လို့ မရပါ
ဒီ code ဟာ AWS account အစစ်ပေါ်မှာ run ရမယ့် code ဖြစ်လို့ browser playground ထဲမှာ run လို့ မရပါ။ ကိုယ့် terminal (သို့) AWS CloudShell ထဲမှာ စမ်းပါ။
Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- OrdersApi (L3)
export class OrdersApi extends ConstructConstruct ကို extend လုပ်ရုံနဲ့ ကိုယ်ပိုင် L3 pattern ရပါပြီ။ Constructor ထဲမှာ this ကို scope အဖြစ် ပေးလို့ table, handler, API တွေဟာ /…/Orders/Table စသဖြင့် tree ထဲမှာ OrdersApi အောက်ကို ရောက်ပါတယ်။ ဒီ class ကို npm package အဖြစ် team တိုင်းကို share လုပ်လို့ ရပါတယ်။
- removalPolicy
removalPolicy: props.protectData ? RemovalPolicy.RETAIN : RemovalPolicy.DESTROYယခင်သင်ခန်းစာက DeletionPolicy နဲ့ UpdateReplacePolicy ကို CDK က ဒီ property တစ်ခုတည်းကနေ နှစ်ခုလုံး ထုတ်ပေးပါတယ်။ Prod template မှာ Retain/Retain၊ dev မှာ Delete/Delete ဖြစ်ပါတယ်။
- grantReadWriteData
this.table.grantReadWriteData(handler);Lambda ရဲ့ execution role ပေါ်မှာ ဒီ table ARN (နဲ့ index ARN) တစ်ခုတည်းအတွက်ပဲ DynamoDB read/write action တွေ ပါတဲ့ IAM policy ကို ထုတ်ပေးပါတယ်။ Problem section က YAML ၂၅ လိုင်းလောက်ကို တစ်ကြောင်းတည်းနဲ့ အစားထိုးတာပါ။
- env
env: { account: "222233334444", region: "ap-southeast-1" }Stack ကို account/region တစ်ခုနဲ့ ချည်ထားပါတယ်။ Dev က CLI profile ကနေ ရတဲ့ CDK_DEFAULT_ACCOUNT/REGION ကို သုံးပြီး prod ကတော့ တိကျတဲ့ account နဲ့ region ပါ — တစ်ယောက်ယောက် profile မှားပြီး deploy လုပ်ရင် CDK က ငြင်းပါမယ်။
- IAspect
Aspects.of(app).add(new TablesNeedRecovery());Synth မတိုင်ခင် tree ထဲက construct တိုင်းကို visit() နဲ့ လည်ပတ်စစ်ပါတယ်။ ဒီမှာ L1 CfnTable ကို ကြည့်ပြီး point-in-time recovery ပိတ်ထားရင် warning ထည့်ပါတယ် — dev stack မှာ warning ထွက်ပြီး prod မှာ မထွက်ပါဘူး။ Tags.of(app).add() ကိုယ်တိုင်လည်း aspect တစ်ခုပါပဲ။
Sample output (hash, ID, URL တွေ ကွဲပြားပါမယ်):
$ npx cdk ls
OrdersStack-dev
OrdersStack-prod
$ npx cdk synth OrdersStack-dev --quiet
[Warning at /OrdersStack-dev/Orders/Table/Resource] Point-in-time recovery is off [ack: orders:pitr]
$ npx cdk deploy OrdersStack-dev
...
Outputs:
OrdersStack-dev.ApiUrl = https://a1b2c3d4e5.execute-api.us-east-1.amazonaws.com/prod/
OrdersStack-dev.TableName = OrdersStack-dev-OrdersTable1F8332C7-1AB2CD3EF4GHBootstrap, synth, diff, deploy
cdk bootstrap (account/region တစ်ခုကို တစ်ကြိမ်)
CDKToolkit stack ကို ဆောက်ပါတယ် — file asset အတွက် S3 bucket၊ Docker image asset အတွက် ECR repository နဲ့ deploy, file-publishing, image-publishing, lookup, CloudFormation execution role တွေ ပါပါတယ်။ Default အနေနဲ့ CloudFormation execution role မှာ AdministratorAccess ပါလို့ production မှာ --cloudformation-execution-policies နဲ့ ကျဉ်းအောင် လုပ်ပါ။
cdk synth
Program ကို run ပြီး cdk.out ထဲ template ထုတ်ပါတယ်။ AWS ကို ဘာမှ မခေါ်ပါဘူး (context lookup မပါရင်)။ CI ထဲမှာ synth ကို တစ်ကြိမ်ပဲ လုပ်ပြီး cdk.out ကို artifact အဖြစ် နောက်အဆင့်တွေကို ပေးလေ့ ရှိပါတယ်။
cdk diff
Deploy ထားပြီးသား stack နဲ့ နှိုင်းယှဉ်ပြီး resource ပြောင်းလဲမှုနဲ့ IAM/security group ပြောင်းလဲမှုတွေကို သီးသန့် ဇယားနဲ့ ပြပါတယ်။ Pull request တိုင်းမှာ diff ကို comment အဖြစ် တင်တာ အလေ့အထကောင်းပါ။
cdk deploy
Asset upload ပြီး change set နဲ့ deploy လုပ်ပါတယ်။ --require-approval broadening (default) က IAM ဒါမှမဟုတ် network access ကို ချဲ့တဲ့ ပြောင်းလဲမှုရှိရင် အတည်ပြုခိုင်းပါတယ်။ --hotswap က dev မှာ Lambda code ကို CloudFormation ကျော်ပြီး မြန်မြန်ပြောင်းပေးပေမယ့် production မှာ ဘယ်တော့မှ မသုံးပါနဲ့ (drift ဖြစ်စေပါတယ်)။
npx cdk bootstrap aws://111122223333/us-east-1
npx cdk synth # writes cdk.out/*.template.json
npx cdk diff OrdersStack-dev # what would change?
npx cdk deploy OrdersStack-dev --require-approval broadening
# The bootstrap stack is plain CloudFormation - inspect it like any other
aws cloudformation describe-stacks --stack-name CDKToolkit \
--query "Stacks[0].Outputs[].[OutputKey,OutputValue]" --output tableEnvironment မသတ်မှတ်ထားတဲ့ stack ကို 'environment-agnostic' လို့ ခေါ်ပြီး ဘယ် account မှာမဆို deploy လို့ရပေမယ့် Vpc.fromLookup လို context lookup တွေ၊ AZ အရေအတွက်ကို သိဖို့ လိုတဲ့ construct တွေက အလုပ်မလုပ်ပါဘူး။ Lookup ရလဒ်တွေကို cdk.context.json ထဲ cache လုပ်ထားလို့ အဲဒီ file ကို Git ထဲ commit လုပ်ပါ — မဟုတ်ရင် synth တစ်ခါနဲ့ တစ်ခါ ရလဒ် မတူတာ ဖြစ်နိုင်ပါတယ်။
aws-cdk-lib/assertions နဲ့ unit test
CDK code ဟာ program ဖြစ်လို့ deploy မလုပ်ခင် test လုပ်လို့ ရပါတယ်။ Template.fromStack(stack) က stack ကို synth လုပ်ပြီး template ကို စစ်ဖို့ method တွေ ပေးပါတယ် — hasResourceProperties (property အချို့ ကိုက်ရင် ရ)၊ resourceCountIs၊ hasOutput စသဖြင့်။ Match.objectLike, Match.arrayWith, Match.anyValue တို့နဲ့ အရေးကြီးတဲ့ အပိုင်းကိုပဲ စစ်ပါ။
Test လုပ်ဖို့ အကောင်းဆုံးက ကိုယ်ပိုင် L3 construct တွေပါ — 'DLQ အမြဲ ပါရမယ်'၊ 'TLS မဟုတ်တဲ့ request ကို ငြင်းရမယ်' လို စည်းကမ်းတွေကို test က ကာကွယ်ပေးပါတယ်။ cdk init က Jest နဲ့ project ဆောက်ပေးပေမယ့် ဒီဥပမာမှာ extra package မလိုအောင် Node ရဲ့ built-in test runner ကို သုံးထားပါတယ် — assertions API က အတူတူပါပဲ။
// Run with: npx tsx --test test/work-queue.test.ts
import { test } from "node:test";
import * as cdk from "aws-cdk-lib";
import { Duration, Stack } from "aws-cdk-lib";
import { Match, Template } from "aws-cdk-lib/assertions";
import * as sqs from "aws-cdk-lib/aws-sqs";
import { Construct } from "constructs";
// The construct under test (in a real project: import from "../lib/work-queue")
export class WorkQueue extends Construct {
public readonly queue: sqs.Queue;
constructor(scope: Construct, id: string, props: { maxReceiveCount?: number } = {}) {
super(scope, id);
const dlq = new sqs.Queue(this, "Dlq", {
retentionPeriod: Duration.days(14),
enforceSSL: true,
});
this.queue = new sqs.Queue(this, "Queue", {
visibilityTimeout: Duration.seconds(60),
enforceSSL: true,
deadLetterQueue: { queue: dlq, maxReceiveCount: props.maxReceiveCount ?? 5 },
});
}
}
function synth(props?: { maxReceiveCount?: number }): Template {
const stack = new Stack(new cdk.App(), "TestStack");
new WorkQueue(stack, "Orders", props);
return Template.fromStack(stack);
}
test("creates a work queue and a dead-letter queue", () => {
synth().resourceCountIs("AWS::SQS::Queue", 2);
});
test("redrives to the DLQ after the requested receive count", () => {
synth({ maxReceiveCount: 3 }).hasResourceProperties("AWS::SQS::Queue", {
VisibilityTimeout: 60,
RedrivePolicy: { maxReceiveCount: 3, deadLetterTargetArn: Match.anyValue() },
});
});
test("both queues deny requests that do not use TLS", () => {
const template = synth();
template.resourceCountIs("AWS::SQS::QueuePolicy", 2);
template.hasResourceProperties("AWS::SQS::QueuePolicy", {
PolicyDocument: {
Statement: Match.arrayWith([
Match.objectLike({
Effect: "Deny",
Condition: { Bool: { "aws:SecureTransport": "false" } },
}),
]),
},
});
});| Test အမျိုးအစား | သုံးသင့်တဲ့နေရာ |
|---|---|
| Fine-grained (hasResourceProperties) | အရေးကြီးတဲ့ စည်းကမ်း (encryption, DLQ, removal policy) ကို ကာကွယ်ဖို့ — အဓိက နည်းလမ်း |
| Snapshot (template တစ်ခုလုံး) | Refactor လုပ်တဲ့အခါ မထင်မှတ်တဲ့ ပြောင်းလဲမှုကို ဖမ်းဖို့၊ CDK upgrade တိုင်း ပြန် update လုပ်ရ |
| Validation (Annotations) | Aspect က ထည့်တဲ့ warning/error ရှိမရှိ စစ်ဖို့ |
Aspect, cdk-nag နဲ့ escape hatch
Aspect က visitor pattern ပါ — tree တစ်ခုလုံးကို လည်ပတ်ပြီး construct တိုင်းကို စစ်တာ၊ ပြင်တာ လုပ်နိုင်ပါတယ်။ Organization တစ်ခုလုံးရဲ့ စည်းကမ်း (bucket တိုင်း encrypt၊ tag တိုင်း ပါ၊ IAM role တိုင်းမှာ permission boundary ပါ) ကို code review မှာ လူက မှတ်မိဖို့ မလိုတော့ပါဘူး။
ကိုယ်တိုင် မရေးချင်ရင် open-source cdk-nag package ကို သုံးလို့ရပါတယ်။ Aspects.of(app).add(new AwsSolutionsChecks()) လို့ ထည့်လိုက်ရင် AWS Solutions, HIPAA, NIST စတဲ့ rule pack တွေနဲ့ synth ချိန်မှာ စစ်ပြီး ချိုးဖောက်တာ ရှိရင် error ထုတ်ပါတယ်။ တမင် ခွင့်ပြုတာဆိုရင် NagSuppressions နဲ့ အကြောင်းပြချက် ရေးပြီး suppress လုပ်ပါ။
L2 က property တစ်ခုကို မထုတ်ပေးသေးရင် escape hatch သုံးပါ — bucket.node.defaultChild ကို s3.CfnBucket အဖြစ် cast လုပ်ပြီး L1 property ကို တိုက်ရိုက် သတ်မှတ်တာ ဒါမှမဟုတ် addPropertyOverride('Path.To.Property', value) နဲ့ template ကို override လုပ်တာပါ။
Production မှာ
Production မှာ CDK
Platform team တွေက ကုမ္ပဏီ standard (encryption, logging, alarm, tag) တွေ ထည့်ပြီးသား L3 construct library တစ်ခုကို internal npm package အဖြစ် ထုတ်ပြီး product team တွေက အဲဒါကို သုံးပါတယ်။ ဒါမှ standard တစ်ခု ပြောင်းရင် library version တင်ရုံနဲ့ team အားလုံးဆီ ရောက်ပါတယ်။ Stage တစ်ခု (dev, staging, prod) ကို cdk.Stage subclass အဖြစ် ဖွဲ့ပြီး account အလိုက် instance ဆောက်ပါတယ်။
aws-cdk-lib နဲ့ CDK CLI version ကို package.json နဲ့ lockfile မှာ pin လုပ်ပြီး Dependabot/Renovate နဲ့ ပုံမှန် upgrade လုပ်ပါတယ်။ cdk.json ထဲက feature flag တွေက CDK version အသစ်ရဲ့ default အပြုအမူကို ထိန်းထားလို့ အလွယ်တကူ မပြောင်းပါနဲ့ — ပြောင်းရင် cdk diff နဲ့ အရင် စစ်ပါ။ CI ထဲမှာ synth → unit test → cdk-nag → diff → (prod အတွက် approval) → deploy အစဉ်နဲ့ run ပြီး developer laptop ကနေ prod ကို deploy လုပ်ခွင့် မပေးပါဘူး (နောက်သင်ခန်းစာမှာ OIDC နဲ့ လုပ်ပုံ ကြည့်ပါမယ်)။ Reviewer တွေက code ပြောင်းလဲမှုနဲ့ infrastructure ပြောင်းလဲမှုကို ဘေးချင်းယှဉ် မြင်ရအောင် pull request တိုင်းမှာ cdk diff output ကို တွဲတင်ပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားများ
- Construct id ကို refactor လုပ်ရင်း ပြောင်းခြင်း — logical ID ဟာ tree path ကနေ လာလို့ id ပြောင်းတာ၊ construct ကို တခြား parent အောက် ရွှေ့တာက CloudFormation အမြင်မှာ 'အဟောင်း ဖျက်၊ အသစ် ဆောက်' ဖြစ်ပါတယ်။ Table တစ်ခုဆိုရင် data ပျောက်နိုင်ပါတယ်။ cdk diff မှာ [-] နဲ့ [+] တွဲပေါ်ရင် ရပ်ပါ။
- Synth-time နဲ့ deploy-time ကို ရောထွေးခြင်း — table.tableName ကို console.log လုပ်ရင် ${Token[...]} လို string ပဲ ထွက်ပါတယ်၊ တကယ့်နာမည် မဟုတ်ပါဘူး။ if (table.tableName.startsWith('prod')) လို logic က ဘယ်တော့မှ မှန်မှာ မဟုတ်ပါဘူး။
- Stateful resource ကို RemovalPolicy.DESTROY နဲ့ ထားခဲ့ခြင်း — dev အတွက် အဆင်ပြေပေမယ့် prod stack ကိုလည်း props တစ်ခုတည်းနဲ့ ဆောက်ရင် cdk destroy တစ်ခါနဲ့ data အကုန် ပျောက်ပါတယ်။
- cdk.context.json ကို commit မလုပ်ခြင်း — lookup ရလဒ်တွေ (AMI ID, VPC ID) ပြောင်းသွားရင် ကိုယ်ဘာမှ မပြောင်းဘဲ diff ပေါ်လာပြီး EC2 instance တွေ replace ဖြစ်တတ်ပါတယ်။
- Production မှာ --hotswap သုံးခြင်း — CloudFormation ကို ကျော်လို့ stack နဲ့ တကယ့် resource မကိုက်တော့ပါဘူး။
💰 Cost & Cleanup
CDK ကိုယ်တိုင် အခမဲ့ပါ။ ငွေကျတာက deploy လုပ်တဲ့ resource တွေ (ဒီ lab မှာ API Gateway request, Lambda invocation, on-demand DynamoDB — အသုံးနည်းရင် free tier ထဲ ပါတတ်ပါတယ်) နဲ့ bootstrap stack ပါ။ CDKToolkit stack ရဲ့ S3 bucket ထဲ asset file တွေ စုလာပြီး storage ကြေး နည်းနည်း တက်ပါတယ်၊ bucket မှာ versioning ဖွင့်ထားလို့ ဖျက်ချင်ရင် version အကုန် ဖျက်ရပါတယ်။ Lab ပြီးရင် stack တွေကို destroy လုပ်ပါ။ Prod stack မှာ Retain ထားတဲ့ table ကို လက်နဲ့ ဖျက်ဖို့ မမေ့ပါနဲ့။
စမ်းပြီးရင် ဖျက်ဖို့ command
npx cdk destroy OrdersStack-dev --force
# Only if you deployed the prod stack too: its table is retained on purpose
aws dynamodb list-tables --region ap-southeast-1 \
--query "TableNames[?starts_with(@, 'OrdersStack-prod')]"
# Keep the CDKToolkit stack if you will use CDK again in this account/regionMini challenge
Encrypt လုပ်ထားတဲ့ bucket construct နဲ့ test
Team တိုင်း သုံးမယ့် SecureBucket L3 construct တစ်ခု ရေးပြီး aws-cdk-lib/assertions နဲ့ စည်းကမ်းတွေကို test လုပ်ပါ။
- Block Public Access အကုန်ဖွင့်၊ S3-managed encryption၊ versioning နဲ့ enforceSSL ပါရမယ်
- noncurrent version တွေကို ရက် ၃၀ ကြာရင် ဖျက်တဲ့ lifecycle rule ပါရမယ်
- hasResourceProperties နဲ့ versioning နဲ့ lifecycle rule ကို test လုပ်ရမယ်
- Bucket policy မှာ aws:SecureTransport Deny statement ရှိကြောင်း test လုပ်ရမယ်
ရလဒ်: npx tsx --test က test သုံးခုလုံး pass ဖြစ်ပြီး enforceSSL ကို ဖယ်လိုက်ရင် TLS test fail ဖြစ်ပါမယ် — test က စည်းကမ်းကို တကယ် ကာကွယ်နေတာကို ပြပါတယ်။
အရိပ်အမြွက် ကြည့်ရန်
s3.Bucket ရဲ့ lifecycleRules prop မှာ noncurrentVersionExpiration: Duration.days(30) ကို သုံးပါ။ Template ထဲမှာ NoncurrentVersionExpiration.NoncurrentDays အဖြစ် ထွက်ပါတယ်။
အဖြေ ကြည့်ရန်
import { test } from "node:test";
import * as cdk from "aws-cdk-lib";
import { Duration, Stack } from "aws-cdk-lib";
import { Match, Template } from "aws-cdk-lib/assertions";
import * as s3 from "aws-cdk-lib/aws-s3";
import { Construct } from "constructs";
export class SecureBucket extends Construct {
public readonly bucket: s3.Bucket;
constructor(scope: Construct, id: string) {
super(scope, id);
this.bucket = new s3.Bucket(this, "Bucket", {
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
encryption: s3.BucketEncryption.S3_MANAGED,
versioned: true,
enforceSSL: true,
lifecycleRules: [{ noncurrentVersionExpiration: Duration.days(30) }],
});
}
}
const template = (() => {
const stack = new Stack(new cdk.App(), "TestStack");
new SecureBucket(stack, "Reports");
return Template.fromStack(stack);
})();
test("versioning is enabled", () => {
template.hasResourceProperties("AWS::S3::Bucket", {
VersioningConfiguration: { Status: "Enabled" },
});
});
test("noncurrent versions expire after 30 days", () => {
template.hasResourceProperties("AWS::S3::Bucket", {
LifecycleConfiguration: {
Rules: Match.arrayWith([
Match.objectLike({ NoncurrentVersionExpiration: { NoncurrentDays: 30 } }),
]),
},
});
});
test("requests without TLS are denied", () => {
template.hasResourceProperties("AWS::S3::BucketPolicy", {
PolicyDocument: {
Statement: Match.arrayWith([
Match.objectLike({
Effect: "Deny",
Condition: { Bool: { "aws:SecureTransport": "false" } },
}),
]),
},
});
});Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- L1 = CloudFormation နဲ့ ၁:၁၊ L2 = ရည်ရွယ်ချက် + လုံခြုံတဲ့ default + grant*၊ L3 = architecture pattern တစ်ခုလုံး။
- App → Stack → Construct tree ကနေ cdk synth က cdk.out ထဲ CloudFormation template ထုတ်ပါတယ်၊ CDK code က synth-time မှာ run ပါတယ်။
- Account/region တစ်ခုချင်းကို bootstrap တစ်ကြိမ်လုပ်ပြီး diff ကို ဖတ်ပြီးမှ deploy လုပ်ပါ။
- Aspect (နဲ့ cdk-nag) က tree တစ်ခုလုံးကို policy အလိုက် စစ်ပေးပါတယ်။
- ကိုယ်ပိုင် construct တွေကို Template.fromStack + hasResourceProperties နဲ့ unit test လုပ်ပါ။
AWS CDK v2 Developer Guide — AWS Documentation
AWS CDK bootstrapping — AWS Documentation
Testing AWS CDK applications — AWS Documentation