(圖說:當年積體電路 (IC) 將一些常用、重複使用的電路整理起來,進而縮小尺寸,站在前人的肩膀上,帶動了時代進步。現在的 AWS CDK 也做了類似的整理。圖片來源:Image by Gerd Altmann from Pixabay。)
概覽摘要 Briefing
AWS Cloud Development Kit (AWS CDK) 可以讓我們用自己熟悉的程式語言(目前已支援有 5 種),以程式碼方式定義自己的雲端基礎架構 (IaC)。
AWS CDK 由各種大大小小的 constructs 所組成,用以打造 stacks 和 apps。
AWS CDK 樓下 (底層) 住的是 AWS CloudFormation,藉由 cdk synth
指令工具轉換成 AWS CloudFormation Template,接著即可使用 cdk deploy
指令輕鬆部署各種 AWS 產品/資源,或使用 cdk destroy
指令一鍵復原。
初次接觸,建議可以看 Pahud Dev 的 AWS CDK 系列影片、或 CDK Workshop 體驗整個流程的簡單(與舒服)。
- 實戰派可以參考 AWS CDK 官方文件的範例(Serverless, ECS, CodePipeline)、或官方範例大全集(目前 TypeScript 和 Python 範例比較齊全,也有涵蓋 Java, JavaScript, .NET 的範例),找適合自己應用場景的範例先入手玩看看。(找一個乾淨的 AWS Region 或用 AWS Organizations 建立一個乾淨的 AWS Root Account 來玩)。
- 學院派可以參閱這份筆記(本文)或 AWS CDK 官方文件 Concepts 等段落。
- 創作派可以從 AWS Construct library 和源頭 GitHub repo: aws/aws-cdk 下手,或參考這篇 How to Create CDK Constructs (by AWS Hero Matthew Bonig)。
- 社交派請加快手速前往 Taiwan CDK Meetup #TaiwanCDKMeetup。
剛開始動手玩 AWS CDK 的時候,大多時候都是使用到預設值/預設環境,進一步使用到量產環境時會陸續用到比較細膩的設定,有時太細膩的環節還沒打通,可以動手幫忙貢獻一下 (L2/L3 constructs)。本文參考資料段落有一些關於貢獻的參考資源。
歷史考古 History
古往今來,縱橫脈絡。
- 2017-10-05: First git repo initial commit.
- 2018-06-13: First GitHub Release: v0.7.0-beta
- 2018-08-27: AWS CDK Developer Preview
- 2019-07-11: The AWS Cloud Development Kit (AWS CDK) is Now Generally Available; GA Release: v1.0.0 🎉🎉🥂🥂🍾🍾
- 2020-07-16: CDK for Terraform (experimental project from HashiCorp)
- 2021-01-27: eks: 畢業轉成 stable
名詞定義 Terms
這裡整理有出場的名詞清單,並註記原文全名、名詞定義與來源。
- AWS Cloud Development Kit (AWS CDK) is a software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation.
- Constructs
- Constructs are the basic building blocks of AWS CDK apps. A construct represents a “cloud component” and encapsulates everything AWS CloudFormation needs to create the component.
- 基本單元。
- 可大可小。
- 小至對應到一種雲端產品(例如一個 Amazon S3 bucket)。
- 大至可以橫跨多個 AWS 帳戶、多個 regions。
- 在 AWS CDK 的世界,所有東西都是 Construct。
- 類似 Flutter 的世界,所有東西都是 Widget。
- AWS Construct library
- The Matrix: The Construct Explained
- Apps
- App 也是一種 Construct。
- The App construct doesn’t require any initialization arguments, because it’s the only construct that can be used as a root for the construct tree.
- Stacks
- The unit of deployment in the AWS CDK is called a stack.
- All AWS resources defined within the scope of a stack, either directly or indirectly, are provisioned as a single unit.
- Environments
- Each Stack instance in your AWS CDK app is explicitly or implicitly associated with an environment (env).
- An environment is the target AWS account and AWS Region into which the stack is intended to be deployed.
使用情境 Use Cases
- 希望 使用 IaC (Infrastructure as Code)。
- 希望 基礎設施/架構也納入版本控制。
- 適合 前端人員,例如:可以自由部署 S3 / API Gateway。(參閱 Pahud 的 Youtube 影片「【Pahud Dev】EP17 - 立即開箱 Amazon API Gateway HTTP API with AWS CDK (4K 2160p)」)
- 不想學/不想使用 CloudFormation 慢慢刻。
- 不想學/不想使用 AWS CLI / CLI v2 慢慢刻。
- 建議搭配 AWS Organizations 一起服用。
限制條件 Limits
- 使用 AWS CDK 的同時要考量 AWS CloudFormation 的限制條件。例如:
- 每個 AWS CloudFormation template
- 限制 500 個 resources (可藉由 nested stacks / multiple stacks 來繞過)。(2020/10 之前: 200 個)
- 限制 200 個 parameters。(2020/10 之前: 60 個)
- 限制 200 個 mappings。(2020/10 之前: 100 個)
- 限制 200 個 outputs。(2020/10 之前: 60 個)
- AWS CloudFormation resource name 命名要小於 255 個字元。
- AWS CloudFormation (預設)最多可以建立 200 個 stacks。
- 每個 AWS CloudFormation template
- 備註:2020/10 CloudFormation 提高限制條件數量。
收費結構 Pricing
- 免!免費!
- AWS CDK 本身為開發工具。
- 請參考最新官方文件。這裡僅為速記。
- 藉由 AWS CDK 叫用/使用對應各種 AWS Products 則依照各個產品收費規則收費。
常用資訊
先決條件 Prerequisites
- Node.js
- 10.3.0 or later.
- even those working in languages other than TypeScript or JavaScript.
- The AWS CDK Toolkit (cdk command-line tool) and the AWS Construct Library are developed in TypeScript and run on Node.js.
- AWS suggests the latest LTS version.
- 13.0.0 through 13.6.0 are not compatible with the AWS CDK.
- AWS credentials
- AWS CLI
常用指令: 安裝/更新 AWS CDK Toolkit
安裝 AWS CDK Toolkit
npm install -g aws-cdk
yarn global add aws-cdk
指定安裝特定版本(鎖版本) AWS CDK Toolkit
npm install -g aws-cdk@1.50.0
更新 AWS CDK Toolkit
npm update -g aws-cdk
檢查版本
cdk --version
常用指令: 使用 projen
mkdir hello-cdk
cd hello-cdk
git init
npx projen new awscdk-app-ts
- 編輯檔案
.projenrc.js
npx projen
- 會自動生成檔案
package.json
- 會自動生成檔案
常用指令: 傳統方式
mkdir hello-cdk
cd hello-cdk
cdk init --language typescript
npm run build
(compile typescript to js)npm install @aws-cdk/aws-s3
- Edit your code
npm run build
cdk bootstrap
(Bootstrap once, per account per region)cdk synth
(Synthesizing an AWS CloudFormation Template. Generate file cdk.context.json.)cdk deploy
- Do some extra editing on your code.
npm run build
cdk diff
cdk deploy
cdk destroy
細節概念 Concepts
Constructs
Constructs are the basic building blocks of AWS CDK apps. A construct represents a “cloud component” and encapsulates everything AWS CloudFormation needs to create the component.
基本單元。
- 積木。
可大可小。
- 小至對應到一種雲端產品(例如一個 Amazon S3 bucket)。
- 大至可以橫跨多個 AWS 帳戶、多個 regions。
- 在 AWS CDK 的世界,所有東西都是 Construct。
- 類似 Flutter 的世界,所有東西都是 Widget。
AWS Construct library
- Docs
- This library includes constructs that represent all the resources available on AWS.
- For example, the
s3.Bucket
class represents an Amazon S3 bucket, and thedynamodb.Table
class represents an Amazon DynamoDB table.
- For example, the
- There are different levels of constructs in AWS Construct Library.
- Bottom level: CFN Resources. (AWS CloudFormation-only) (L1) (Level 1)
- These constructs represent all of the AWS resources that are available in AWS CloudFormation. CFN Resources are generated from the AWS CloudFormation Resource Specification on a regular basis. They are named
CfnXyz
, where Xyz represents the name of the resource. - For example,
s3.CfnBucket
represents theAWS::S3::Bucket
CFN Resource.
- These constructs represent all of the AWS resources that are available in AWS CloudFormation. CFN Resources are generated from the AWS CloudFormation Resource Specification on a regular basis. They are named
- Higher level: AWS constructs. (Curated) (L2)
- They provide the same functionality, but handle much of the details, boilerplate, and glue logic required by CFN constructs. AWS constructs offer convenient defaults and reduce the need to know all the details about the AWS resources they represent, while providing convenience methods that make it simpler to work with the resource.
- Example:
s3.Bucket
.
- Even higher-level: Patterns. (Patterns) (L3)
- These constructs are designed to help you complete common tasks in AWS, often involving multiple kinds of resources.
- For example, the
aws-ecs-patterns.ApplicationLoadBalancedFargateService
construct represents an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer (ALB).
- Bottom level: CFN Resources. (AWS CloudFormation-only) (L1) (Level 1)
Composition
The key pattern for defining higher-level abstractions through constructs is called composition.
Initialization
Constructs are implemented in classes that extend the
Construct
base class. You define a construct by instantiating the class. All constructs take three parameters when they are initialized:- scope
- 通常傳入
this
- 通常傳入
- id
- identifier
- namespace
- unique
- resource names
- AWS CloudFormation logical IDs
- props
- A set of properties or keyword arguments
Apps
App 也是一種 Construct。
The App construct doesn’t require any initialization arguments, because it’s the only construct that can be used as a root for the construct tree.
You can use the App instance as a scope for defining a single instance of your stack.
App 生命週期:
- The following diagram shows the phases that the AWS CDK goes through when you call the cdk deploy.
(圖片來源: 官方文件)
To work with the CDK CLI, you need to let it know how to execute an AWS CDK app.
cdk --app executable cdk-command
cdk.json:
1 2 3
{ "app": "node bin/my-app.js" }
Example: The following example lists the stacks defined in the cloud assembly stored under ./my-cloud-assembly.
cdk --app ./my-cloud-assembly ls
Stacks
The unit of deployment in the AWS CDK is called a stack.
All AWS resources defined within the scope of a stack, either directly or indirectly, are provisioned as a single unit.
When you run the cdk synth command for an app with multiple stacks, the cloud assembly includes a separate template for each stack instance.
Because AWS CDK stacks are implemented through AWS CloudFormation stacks, they have the same limitations as in AWS CloudFormation.
1 2 3 4 5 6
const app = new App(); new MyFirstStack(app, 'stack1'); new MySecondStack(app, 'stack2'); app.synth();
To list all the stacks in an AWS CDK app, run the
cdk ls
command, which for the previous AWS CDK app would have the following output.stack1 stack2
Nested stacks
- class NestedStack (construct)
- A CloudFormation nested stack.
- The NestedStack construct offers a way around the AWS CloudFormation 500-resource limit for stacks.
- The scope of a nested stack must be a
Stack
orNestedStack
construct. - parent stacks v.s nested stacks
- Nested stacks are bound to their parent stack and are not treated as independent deployment artifacts; they are not listed by
cdk list
nor can they be deployed bycdk deploy
.
- Nested stacks are bound to their parent stack and are not treated as independent deployment artifacts; they are not listed by
Environments
Each Stack instance in your AWS CDK app is explicitly or implicitly associated with an environment (env).
An environment is the target AWS account and AWS Region into which the stack is intended to be deployed.
For production stacks, AWS recommends that you explicitly specify the environment for each stack in your app using the env property.
Example: specifies different environments for its two different stacks.
1 2 3 4 5
const envEU = { account: '2383838383', region: 'eu-west-1' }; const envUSA = { account: '8373873873', region: 'us-west-2' }; new MyFirstStack(app, 'first-stack-us', { env: envUSA }); new MyFirstStack(app, 'first-stack-eu', { env: envEU });
To make the stack deployable to a different target, but to determine the target at synthesis time, your stack can use two environment variables provided by the AWS CDK CLI:
CDK_DEFAULT_ACCOUNT
andCDK_DEFAULT_REGION
.- These variables are set based on the AWS profile specified using the
--profile
option, or the default AWS profile if you don’t specify one.
1 2 3 4 5
new MyDevStack(app, 'dev', { env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION }});
- These variables are set based on the AWS profile specified using the
You can set env however you like, using any valid expression.
- Example: you might write your stack to support two additional environment variables to let you override the account and region at synthesis time.
1 2 3 4 5
new MyDevStack(app, 'dev', { env: { account: process.env.CDK_DEPLOY_ACCOUNT || process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEPLOY_REGION || process.env.CDK_DEFAULT_REGION }});
With your stack’s environment declared this way, you can now write a short script or batch file like the following to set the variables from command line arguments, then call
cdk deploy
:cdk-deploy-to.sh
:
1 2 3 4 5 6
#!/bin/bash export CDK_DEPLOY_ACCOUNT=$1 shift export CDK_DEPLOY_REGION=$1 shift cdk deploy "$@"
cdk-deploy-to-test.sh
:
1 2
#!/bin/bash bash cdk-deploy-to.sh 123457689 us-east-1 "$@"
cdk-deploy-to-prod.sh
:
1 2 3
#!/bin/bash bash cdk-deploy-to.sh 135792468 us-west-1 "$@" || exit bash cdk-deploy-to.sh 246813579 eu-west-1 "$@"
Resources
The AWS CDK provides a rich class library of constructs, called AWS constructs, that represent all AWS resources.
Resource attributes
Most resources in the AWS Construct Library expose attributes, which are resolved at deployment time by AWS CloudFormation.
1 2 3 4
import * as sqs from '@aws-cdk/aws-sqs'; const queue = new sqs.Queue(this, 'MyQueue'); const url = queue.queueUrl; // => A string representing a deploy-time value
Referencing resources
Many AWS CDK classes require properties that are AWS CDK resource objects (resources). To satisfy these requirements, you can refer to a resource in one of two ways:
- By passing the resource directly
- By passing the resource’s unique identifier, which is typically an ARN, but it could also be an ID or a name
If a construct property represents another AWS construct, its type is that of the interface type of that construct. Examples:
- the Amazon ECS service takes a property
cluster
of typeecs.ICluster
; - the CloudFront distribution takes a property
sourceBucket
(Python:source_bucket
) of types3.IBucket
.
- the Amazon ECS service takes a property
Example: define an Amazon ECS cluster and then uses it to define an Amazon ECS service.
1 2 3
const cluster = new ecs.Cluster(this, 'Cluster', { /*...*/ }); const service = new ecs.Ec2Service(this, 'Service', { cluster: cluster });
Physical names
The logical names of resources in AWS CloudFormation are different from the physical names of resources that are shown in the AWS Management Console after AWS CloudFormation has deployed the resources. The AWS CDK calls these final names physical names.
For example, AWS CloudFormation might create the Amazon S3 bucket with the logical ID
Stack2MyBucket4DD88B4F
from the previous example with the physical namestack2mybucket4dd88b4f-iuv1rbv9z3to
.You can specify a physical name when creating constructs that represent resources by using the property
<resourceType>Name
. The following example creates an Amazon S3 bucket with the physical namemy-bucket-name
.1 2 3
const bucket = new s3.Bucket(this, 'MyBucket', { bucketName: 'my-bucket-name', });
(缺點) Assigning physical names to resources has some disadvantages in AWS CloudFormation.
Most importantly, any changes to deployed resources that require a resource replacement, such as changes to a resource’s properties that are immutable after creation, will fail if a resource has a physical name assigned.
(只能刪掉再重新 deploy 一次) If you end up in a state like that, the only solution is to delete the AWS CloudFormation stack, then deploy the AWS CDK app again.
(有些跨環境時需要指定固定的 physical names,可讓 AWS CDK 幫忙命名) In some cases, such as when creating an AWS CDK app with cross-environment references, physical names are required for the AWS CDK to function correctly. In those cases, if you don’t want to bother with coming up with a physical name yourself, you can let the AWS CDK name it for you by using the special value
PhysicalName.GENERATE_IF_NEEDED
1 2 3
const bucket = new s3.Bucket(this, 'MyBucket', { bucketName: core.PhysicalName.GENERATE_IF_NEEDED, });
Importing existing external resources
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Construct a resource (bucket) just by its name (must be same account) s3.Bucket.fromBucketName(this, 'MyBucket', 'my-bucket-name'); // Construct a resource (bucket) by its full ARN (can be cross account) s3.Bucket.fromArn(this, 'MyBucket', 'arn:aws:s3:::my-bucket-name'); // Construct a resource by giving attribute(s) (complex resources) ec2.Vpc.fromVpcAttributes(this, 'MyVpc', { vpcId: 'vpc-1234567890abcde', }); // quert by default ec2.Vpc.fromLookup(this, 'DefaultVpc', { isDefault: true }); // query by tag ec2.Vpc.fromLookup(this, 'PublicVpc', {tags: {'aws-cdk:subnet-type': "Public"} });
Permission grants
- The grant methods return an
iam.Grant
object.
1 2 3 4 5
if (bucket.grantReadWrite(func).success) { // ... } table.grant(func, 'dynamodb:CreateBackup');
Metrics and alarms
- Docs
- AWS constructs have metric methods that allow easy access to the metrics without having to look up the correct name to use.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import * as cw from '@aws-cdk/aws-cloudwatch'; import * as sqs from '@aws-cdk/aws-sqs'; import { Duration } from '@aws-cdk/core'; const queue = new sqs.Queue(this, 'MyQueue'); const metric = queue.metricApproximateNumberOfMessagesNotVisible({ label: 'Messages Visible (Approx)', period: Duration.minutes(5), // ... }); metric.createAlarm(this, 'TooManyMessagesAlarm', { comparisonOperator: cw.ComparisonOperator.GREATER_THAN_THRESHOLD, threshold: 100, // ... });
Network traffic
- Docs
- Resources that establish or listen for connections expose methods that enable traffic flows, including setting security group rules or network ACLs.
- IConnectable resources have a
connections
property that is the gateway to network traffic rules configuration.
Event handling
Some resources can act as event sources. Use the
addEventNotification
method (Python:add_event_notification
) to register an event target to a particular event type emitted by the resource.In addition to this,
addXxxNotification
methods offer a simple way to register a handler for common event types.The following example shows how to trigger a Lambda function when an object is added to an Amazon S3 bucket:
1 2 3 4 5
import * as s3nots from '@aws-cdk/aws-s3-notifications'; const handler = new lambda.Function(this, 'Handler', { /*…*/ }); const bucket = new s3.Bucket(this, 'Bucket'); bucket.addObjectCreatedNotification(new s3nots.LambdaDestination(handler));
Removal policies
Resources that maintain persistent data, such as databases and Amazon S3 buckets, have a removal policy that indicates whether to delete persistent objects when the AWS CDK stack that contains them is destroyed.
The values specifying the removal policy are available through the
RemovalPolicy
enumeration in the AWS CDKcore
module.Example:
1 2 3 4 5 6 7 8 9 10 11 12
import * as cdk from '@aws-cdk/core'; import * as s3 from '@aws-cdk/aws-s3'; export class CdkTestStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const bucket = new s3.Bucket(this, 'Bucket', { removalPolicy: cdk.RemovalPolicy.DESTROY, }); } }
Example: You can also apply a removal policy directly to the underlying AWS CloudFormation resource via the applyRemovalPolicy() method.
1 2
const resource = bucket.node.findChild('Resource') as cdk.CfnResource; resource.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY);
Identifiers
The AWS CDK deals with many types of identifiers and names.
Identifiers must be unique within the scope in which they are created; they do not need to be globally unique in your AWS CDK application.
Construct IDs
- The most common identifier,
id
, is the identifier passed as the second argument when instantiating a construct object.
Paths
We refer to the collection of IDs from a given construct, its parent construct, its grandparent, and so on to the root of the construct tree, as a path.
The AWS CDK typically displays paths in your templates as a string, with the IDs from the levels separated by slashes, starting at the node just below the root App instance, which is usually a stack. For example, the paths of the two Amazon S3 bucket resources in the previous code example are
Stack1/MyBucket
andStack2/MyBucket
.1
const path: string = myConstruct.node.path;
Unique IDs
Since the AWS CDK already has paths that are globally unique, the AWS CDK generates these unique identifiers by concatenating the elements of the path, and adds an 8-digit hash. The hash is necessary, as otherwise two distinct paths, such as
A/B/C
andA/BC
would result in the same identifier. The AWS CDK calls this concatenated path elements and hash the unique ID of the construct.1
const uid: string = myConstruct.node.uniqueId;
Logical IDs
- Unique IDs serve as the logical identifiers, which are sometimes called logical names, of resources in the generated AWS CloudFormation templates for those constructs that represent AWS resources.
- Avoid changing the logical ID of a resource between deployments. Since AWS CloudFormation identifies resources by their logical ID, if you change the logical ID of a resource, AWS CloudFormation deletes the existing resource, and then creates a new resource with the new logical ID.
- The most common identifier,
Tokens
- Tokens represent values that can only be resolved at a later time in the lifecycle of an app (see App lifecycle). For example, the name of an Amazon S3 bucket that you define in your AWS CDK app is only allocated by AWS CloudFormation when you deploy your app. If you print the bucket.bucketName attribute, which is a string, you see it contains something like
${TOKEN[Bucket.Name.1234]}
.
Parameters
- AWS CloudFormation templates can contain parameters—custom values that are supplied at deployment time and incorporated into the template. Since the AWS CDK synthesizes AWS CloudFormation templates, it too offers support for deployment-time parameters.
- In general, we recommend against using AWS CloudFormation parameters with the AWS CDK. Parameter values are not available at synthesis time and thus cannot be easily used in other parts of your AWS CDK app, particularly for control flow. 是有支援,但不建議使用。
Tagging
The following example applies the tag key with the value value to a construct:
1
Tag.add(myConstruct, 'key', 'value');
The following example deletes the tag key from a construct:
1
Tag.remove(myConstruct, 'key');
By default, applying a tag has a priority of 100 and removing a tag has a priority of 200. To change the priority of applying a tag, pass a
priority
property toTag.add()
orTag.remove()
. 可以設定優先權。The following applies a tag with a priority of 300 to a construct:
1 2 3
Tag.add(myConstruct, 'key', 'value', { priority: 300 });
Tag.add()
1 2 3 4 5 6
Tag.add(myConstruct, 'tagname', 'value', { applyToLaunchedInstances: false, includeResourceTypes: ['AWS::Xxx::Yyy'], excludeResourceTypes: ['AWS::Xxx::Zzz'], priority: 100, });
- These properties have the following meanings.
applyToLaunchedInstances
- By default, tags are applied to instances launched in an Auto Scaling group. Set this property to false to not apply tags to instances launched in an Auto Scaling group
includeResourceTypes
/excludeResourceTypes
- Use these to apply tags only to a subset of resources, based on AWS CloudFormation resource types. By default, the tag is applied to all resources in the construct subtree, but this can be changed by including or excluding certain resource types. Exclude takes precedence over include, if both are specified.
priority
- Use this to set the priority of this operation with respect to other Tag.add() and Tag.remove() operations. Higher values take precedence over lower values. The default is 100.
- These properties have the following meanings.
Assets
Assets are local files, directories, or Docker images that can be bundled into AWS CDK libraries and apps; for example, a directory that contains the handler code for an AWS Lambda function. Assets can represent any artifact that the app needs to operate.
You typically reference assets through APIs that are exposed by specific AWS constructs. For example, when you define a lambda.Function construct, the code property lets you pass an asset (directory).
Function
uses assets to bundle the contents of the directory and use it for the function’s code.Similarly, ecs.ContainerImage.fromAsset uses a Docker image built from a local directory when defining an Amazon ECS task definition. 實用!
Docker image assets
The AWS CDK supports bundling local Docker images as assets through the aws-ecr-assets module.
The following example defines a docker image that is built locally and pushed to Amazon ECR. Images are built from a local Docker context directory (with a Dockerfile) and uploaded to Amazon ECR by the AWS CDK CLI or your app’s CI/CD pipeline, and can be naturally referenced in your AWS CDK app.
The
my-image
directory must include a Dockerfile. The AWS CDK CLI builds a Docker image from my-image, pushes it to an Amazon ECR repository, and specifies the name of the repository as an AWS CloudFormation parameter to your stack. Docker image asset types expose deploy-time attributes that can be referenced in AWS CDK libraries and apps. The AWS CDK CLI commandcdk synth
displays asset properties as AWS CloudFormation parameters.1 2 3 4 5
import { DockerImageAsset } from '@aws-cdk/aws-ecr-assets'; const asset = new DockerImageAsset(this, 'MyBuildImage', { directory: path.join(__dirname, 'my-image') });
Amazon ECS task definition example
A common use case is to create an Amazon ECS TaskDefinition to run docker containers. The following example specifies the location of a Docker image asset that the AWS CDK builds locally and pushes to Amazon ECR.
1 2 3 4 5 6 7 8 9 10 11
import * as ecs from '@aws-cdk/aws-ecs'; import * as path from 'path'; const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { memoryLimitMiB: 1024, cpu: 512 }); taskDefinition.addContainer("my-other-container", { image: ecs.ContainerImage.fromAsset(path.join(__dirname, "..", "demo-image")) });
深入討論 Deep Dive
大方向是為圭臬,但小心地上有坑。
如何依照順序部署多個 CfnResource ?
我們在 TypeScript 裡頭撰寫的 CfnResource 順序,不一定就會是 AWS CloudFormation 的部屬順序,若是想建立多個 CfnResource 之間的相依性(先後關聯性),可以使用 cfnResource.addDependsOn
方法。
#asynchronous #synchronous #await #dependsOn #resourceDependencies
|
|
如此一來部署的順序會是:
resourceA = deployment 1st (先)
resourceB = deployment 2nd (後)
參考資料:
參考資料 Reference
文件
- AWS CDK Developer Guide
- AWS CDK API Reference
- AWS Construct Library reference
- CDK Construct Catalog, by source code (an index of multi-language AWS CDK libraries.)
Awesome Lists
- eladb/awesome-cdk, by Elad Ben-Israel (the amazing #awscdk team!!)
社群
工作坊
快速上手
- AWS CDK Introduction, by Pahud (Developer Advocate, AWS) (There are at least 12+ videos in 4K high resolution, so that you can see the source code very clearly, and lead step by step. (Chinese) (Video))
- CFH partner workshop - Manage your infrastructure as code on AWS, 2020-06-22, by Darko Mesaroš (Developer Advocate, AWS), at Web Summit
範例
- AWS CDK Examples (At present, TypeScript and Python examples are relatively complete, and there are also examples covering Java, JavaScript, .NET)
- DevOps Taiwan: Kubernetes Jenkins workshop, by John Chen (陳志强) & Rico Chen (陳缺牙)
- cdk-lambda-bash (Deploy Bash Lambda Functions with AWS CDK), by Pahud (Developer Advocate, AWS)
- CDK Serverless Examples
- CDK ECS Examples
- CDK CodePipeline Examples
原始碼
文章與分享
- AWS Blog about AWS CDK
- AWS CDK on DEV.to
- CDK Weekly (Newsletter)
- AWS CDK 初探, 2019-07-30, by Azole (in Chinese)
- Infrastructure IS Code - Intro to AWS CDK, 2019-12-11, by GDG Cyprus
- Infrastructure Is Code with the AWS Cloud Development Kit (CDK), 2020-02-10, by Richard Boyd, at QCon
- What I learned using the AWS CDK in the past year, 2020-11-12, by RAFAEL ZAMANA KINEIPPE
- CDK Corner – January 2021, 2021-01-14, by Richard H Boyd, at AWS DevOps Blog
- Exploring CDK Internals, 2021-04-19, by Mauricio Klein
- Topics: CDK construct levels, CDK tree, Construct path, How logical and unique IDs are calculated, How to fine tune the resulting CloudFormation template generated by CDK.
- Accelerating development with AWS CDK plugin – CfnGuardValidator, 2023-09-15, by Xiaoxue Xu and Kanwar Bajwa
比較
- CDK vs. CloudFormation vs. Terraform vs. Pulumi, 2020-02-28, by David Krohn, at globaldatanet
- Rollback capability is the advantage of CDK/CloudFormation.
貢獻
- (English) Create Your First AWS CDK Pull Request (4K 2160p), 2020-08-11, by Pahud (Developer Advocate, AWS)
- (English) Create Your First AWS CDK Pull Request: Study Notes, 2020-08-10, by Ernest Chiang (AWS Community Hero)
- (Chinses) 創建你的第一個 AWS CDK pull request (4K 2160p), 2020-08-03, by Pahud (Developer Advocate, AWS)
- (Chinses) 創建你的第一個 AWS CDK pull request: 學習筆記, 2020-08-05, by Ernest Chiang (AWS Community Hero)
冷知識 Trivia
- Q: 請問 CDK 專案的 git repo 第一個 init commit 中包含有幾個檔案?
- Q: 請問 CDK 專案的 GitHub repo 第一個釋出的版本號碼為何?