• https://docs.aws.amazon.com/ja_jp/cdk/v2/guide/getting_started.html
  • https://aws.amazon.com/jp/blogs/news/best-practices-for-developing-cloud-applications-with-aws-cdk/

前提

TypeScriptを使用する。

AWS CDKインストール

aws-cdkをグローバルにインストールする前提で進める。

$ npm i -g aws-cdk

$ cdk --version
2.77.0 (build 06a0b19)

ブートストラッピング

AWS アカウントで 1 回実行します。
CloudFormation に CDKToolKit スタックが作成されて、CDK で使用する S3 バケットやポリシーなどのリソースが作成されます。

ブートストラッピング AWS CDKを使用してスタックをデプロイするには、AWS CloudFormationデプロイ中に専用の Amazon S3 バケットとその他のコンテナを利用できるようにしておく必要があります。これらを作成することをブートストラップと呼びます。ブートストラップするには、以下を実行します。

cdk bootstrap aws://ACCOUNT-NUMBER/REGION

ref. https://docs.aws.amazon.com/ja_jp/cdk/v2/guide/getting_started.html

ブートストラッピング例。

$ cdk bootstrap aws://xxxxxxxxxxxxx/ap-northeast-1 --profile personal
    Bootstrapping environment aws://xxxxxxxxxxxxx/ap-northeast-1...
Trusted accounts for deployment: (none)
Trusted accounts for lookup: (none)
Using default execution policy of 'arn:aws:iam::aws:policy/AdministratorAccess'. Pass '--cloudformation-execution-policies' to customize.
CDKToolkit: creating CloudFormation changeset...
 ✅  Environment aws://xxxxxxxxxxxxx/ap-northeast-1 bootstrapped.

ワークフロー

概要

Your first AWS CDK app

The standard AWS CDK development workflow is similar to the workflow you’re already familiar with as a developer, just with a few extra steps.

  1. Create the app from a template provided by the AWS CDK
  2. Add code to the app to create resources within stacks
  3. Build the app (optional; the AWS CDK Toolkit will do it for you if you forget)
  4. Synthesize one or more stacks in the app to create an AWS CloudFormation template
  5. Deploy one or more stacks to your AWS account

詳細

  1. cdk init app --language typescript
    • cdk init の引数は app の他に libsample-app がある1
  2. コードを変更
  3. npm run build(実際は忘れてもCDKが自動で行ってくれるので省略可能)
  4. cdk synthsynthesize 統合する)
    • cdk.out ディレクトリに CloudFormation テンプレートを出力
    • cdk synth は明示的に実行しなくても deploy 時に CDK が自動で実行するので必須ではない

      It is optional (though good practice) to synthesize before deploying. The AWS CDK synthesizes your stack before each deployment.

      – https://docs.aws.amazon.com/cdk/v2/guide/hello_world.html

  5. (既にデプロイされている場合) cdk diff --profile
  6. cdk deploy --profile

注意。

  • cdk コマンドはスタックを指定する
  • スタックが一つの場合は省略できる
  • すべてのスタックを指定するには --all オプションを付与する

ワークフローで使用するコマンド

ref. AWS CDK Toolkit (cdk command)

cdk synth

$ cdk synth
  • 標準出力にCloudFormationのコードを出力
  • cdk.outディレクトリにJSONのCloudFormationテンプレートを格納

cdk deploy

  • スタック作成 or スタック更新

CDK プログラミングガイド

ライブラリの利用

プログラミングの基本

以上の2つのライブラリを使用してプログラミングしていく。

AWS CDK v2 は、コアライブラリを含む AWS コンストラクトライブラリの安定した部分を 1 つのパッケージである aws-cdk-lib に統合します。

Constructクラスは、AWS CDK関連するタイプとともに別のライブラリに抽出されました。

ref. https://docs.aws.amazon.com/ja_jp/cdk/v2/guide/migrating-v2.html

package.json

{
  "peerDependencies": {
    "aws-cdk-lib": "^2.0.0",
    "constructs": "^10.0.0"
  },
  "devDependencies": {
    "aws-cdk-lib": "^2.0.0",
    "constructs": "^10.0.0",
    "typescript": "~3.9.0"
  }  
}

インポートの例

  • import { Construct } from 'constructs'
  • import { App, Stack } from 'aws-cdk-lib'
  • import * as s3 from 'aws-cdk-lib/aws-s3'

App、Stack

  • app: 一つ以上の stack で定義される
  • stackCloudFormationstack と等しい): 1 つ以上の construct を含む

    Stacks (equivalent to AWS CloudFormation stacks) contain constructs, each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on.

    https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html

Construct

A construct represents a “cloud component” and encapsulates everything AWS CloudFormation needs to create the component. A construct can represent a single resource, such as an Amazon Simple Storage Service (Amazon S3) bucket, or it can represent a higher-level component consisting of multiple AWS resources.

https://docs.aws.amazon.com/cdk/latest/guide/constructs.html

Construct の分類

Construct は抽象化の度合いによって L1 から L3 に分けられる。
L1 抽象度が低く、L2 、L3 と高くなる

ref. https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html

  • AWS CloudFormation-only or L1 (short for “level 1”):CloudFormationと直接結びついている

    AWS CloudFormation resources always have names that begin with Cfn.

  • Curated or L2:AWS CDKチームにより特定のユースケースに対応し、インフラストラクチャ開発を簡素化するためにL1をカプセル化したもの。

    These constructs are carefully developed by the AWS CDK team to address specific use cases and simplify infrastructure development. For the most part, they encapsulate L1 modules, providing sensible defaults and best-practice security policies. For example, in the Amazon S3 module, Bucket is the L2 module for an Amazon S3 bucket.

  • Patterns or L3:複数のリソースをカプセル化 選ばれたパラメーターを設定するだけで適切に作成 L1,L2モジュールからは分離されている

    Patterns declare multiple resources to create entire AWS architectures for particular use cases. All the plumbing is already hooked up, and configuration is boiled down to a few important parameters. In the AWS Construct Library, patterns are in separate modules from L1 and L2 constructs.

Curated:精選された

Constructs の引数

  • scope: Tells the bucket that the stack is its parent: it is defined within the scope of the stack. You can define constructs inside of constructs, creating a hierarchy (tree).
  • Id: The logical ID of the Bucket within your AWS CDK app. This (plus a hash based on the bucket’s location within the stack) uniquely identifies the bucket across deployments so the AWS CDK can update it if you change how it’s defined in your app. Buckets can also have a name, which is separate from this ID (it’s the bucketName property).
  • props: A bundle of values that define properties of the bucket. Here we’ve defined only one property: versioned, which enables versioning for the files in the bucket.

Constructs の重要点

Familiarity with AWS CloudFormation is also useful, as the output of an AWS CDK program is a AWS CloudFormation template

https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html

An app defines one or more stacks. Stacks (equivalent to AWS CloudFormation stacks) contain constructs, each of which defines one or more concrete AWS resources, such as Amazon S3 buckets, Lambda functions, Amazon DynamoDB tables, and so on.

https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html

  • constructs:構成(名詞)
  • construct:構成する(動詞)

Structs

AWS CDK (Cloud Development Kit) v2 の Struct は、AWS CDK のコードベース内で使用される、デプロイ対象のリソースを定義するためのデータ構造です。

Struct は、AWS のインフラストラクチャやアプリケーションのリソースを表現するための概念的なモデルです。これにより、AWS CDK を使用して、プログラミング言語を介してインフラストラクチャのコードを記述することができます。

Struct は、AWS の各リソースタイプ(例:S3 バケット、EC2 インスタンス、Lambda 関数など)に対して、そのリソースを作成、構成、管理するために必要なプロパティや設定を持っています。また、リソース間の依存関係や接続なども Struct 内で定義されます。

AWS CDK v2 では、TypeScript や Python などのサポートされているプログラミング言語を使用して、Struct を作成し、AWS のリソースをプログラム的に定義することができます。これにより、インフラストラクチャのコードを再利用しやすくし、より効率的かつ柔軟な方法で AWS リソースを構築および管理することができます。

簡単に言えば、AWS CDK v2 の Struct は、AWS のインフラストラクチャやアプリケーションのリソースを定義するためのデータ構造であり、AWS CDK を使用してインフラストラクチャのコードを記述するための基礎です。

ref. ChatGPT-3.5

AWS CDK v2のaws-cdk-libにおけるStructは、特定のフィールドを持つJavaScriptのオブジェクトを指すもので、複数のデータをまとめるために使われます。これはTypeScriptまたはJavaScriptでの標準的なオブジェクトと同等です。

通常、これらのStructsはAPI呼び出しの引数を定義したり、特定の操作の結果を表現したりするために使用されます。それぞれのStructは、特定のインターフェイスやクラスとして定義され、特定のフィールドとその型を指定します。

たとえば、S3バケットを作成するためのオプションを定義するためのStructは次のようになるかもしれません。

typescript
Copy code
interface BucketProps {
    bucketName: string;
    publicReadAccess?: boolean;
    removalPolicy?: RemovalPolicy;
}
このStructには、バケット名(bucketName)を必須のフィールドとして持ち、パブリックリードアクセスの許可(publicReadAccess)とリソース削除ポリシー(removalPolicy)をオプションとして持つことを指定しています。

このようなStructは、各リソースのPropsオブジェクトとして使われることが多いです。これにより、リソースを定義するときに必要なプロパティを一元管理でき、型の安全性を保つことができます。

typescript
Copy code
const bucket = new s3.Bucket(this, 'MyBucket', {
    bucketName: 'my-bucket-name',
    publicReadAccess: true,
    removalPolicy: RemovalPolicy.DESTROY
});
なお、v1からv2への移行に伴い、aws-cdk-libはすべてのAWS Construct Libraryを単一のライブラリパッケージに統合します。これにより、依存関係の管理がより簡単になり、パッケージのバージョン間での不整合を防ぐことができます。

ref. ChatGpt-4

  • Typescript Enums https://www.typescriptlang.org/docs/handbook/enums.html

AWS Construct Library

  • https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html
  • https://docs.aws.amazon.com/cdk/latest/guide/work-with-cdk-typescript.html

最初のチュートリアル

  • https://docs.aws.amazon.com/ja_jp/cdk/v2/guide/hello_world.html
  • https://cdkworkshop.com/20-typescript/20-create-project.html
  1. sample-appは https://cdkworkshop.com/ja/20-typescript/20-create-project/100-cdk-init.html の雛形。