コンストラクト - AWS Cloud Development Kit (AWS CDK) v2

これは AWS CDK v2 デベロッパーガイドです。古い CDK v1 は 2022 年 6 月 1 日にメンテナンスを開始し、2023 年 6 月 1 日にサポートを終了しました。

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

コンストラクト

コンストラクトは、 AWS Cloud Development Kit (AWS CDK) アプリケーションの基本的な構成要素です。コンストラクトは、1 つ以上の AWS CloudFormation リソースとその設定を表すアプリケーション内のコンポーネントです。コンストラクトをインポートして設定することで、アプリケーションを個別に構築できます。

コンストラクトは CDK アプリにインポートするクラスです。コンストラクトは AWS 、 コンストラクトライブラリから入手できます。また、独自のコンストラクトを作成して配布したり、サードパーティーのデベロッパーが作成したコンストラクトを使用したりできます。

コンストラクトは、コンストラクトプログラミングモデル (CPM) の一部です。CDK for Terraform (CDKtf )、CDK for Kubernetes (CDK8s )、 などの他のツールで使用できますProjen。

AWS ライブラリを構築する

AWS Construct Library には、 によって開発および管理されるコンストラクトのコレクションが含まれています AWS。これは、 で使用できるすべてのリソースを表すコンストラクトを含むさまざまなモジュールで構成されています AWS。リファレンス情報については、AWS CDK 「 API リファレンス」を参照してください。

メイン CDK パッケージは と呼ばれaws-cdk-lib、 AWS ほとんどの コンストラクトライブラリが含まれています。また、 Stackや などの基本クラスも含まれていますApp

メイン CDK パッケージの実際のパッケージ名は言語によって異なります。

TypeScript
インストール npm install aws-cdk-lib
Import import * as cdk from 'aws-cdk-lib';
JavaScript
インストール npm install aws-cdk-lib
Import const cdk = require('aws-cdk-lib');
Python
インストール python -m pip install aws-cdk-lib
Import import aws_cdk as cdk
Java
pom.xml、 を追加します。 Group software.amazon.awscdk; artifact aws-cdk-lib
Import import software.amazon.awscdk.App;
C#
インストール dotnet add package Amazon.CDK.Lib
Import using Amazon.CDK;
Go
インストール go get github.com/aws/aws-cdk-go/awscdk/v2
Import
import ( "github.com/aws/aws-cdk-go/awscdk/v2" )
注記

を使用して CDK プロジェクトを作成した場合はcdk init、 を手動でインストールする必要はありませんaws-cdk-lib

AWS Construct Library には、Construct基本クラスを含む constructsパッケージも含まれています。CDK for Terraform や CDK for Kubernetes など、 に加えて他のコンストラクトベースのツールで使用されるため AWS CDK、独自のパッケージに含まれています。

多数の第三者が、 と互換性のあるコンストラクトを公開しています AWS CDK。「Construct Hub」にアクセスして、 AWS CDK コンストラクトパートナーエコシステムをご覧ください。

コンストラクトレベル

コンストラクトライブラリからのコンストラクトは 3 AWS つのレベルに分類されます。各レベルでは、抽象化のレベルが高くなります。抽象化が高いほど、設定が簡単になり、専門知識が少なくなります。抽象化が小さいほど、利用できるカスタマイズが多くなり、より多くの専門知識が必要になります。

レベル 1 (L1) コンストラクト

L1 コンストラクトは CFN リソースとも呼ばれ、最下位コンストラクトであり、抽象化されません。各 L1 コンストラクトは、単一の AWS CloudFormation リソースに直接マッピングされます。L1 コンストラクトでは、特定の AWS CloudFormation リソースを表すコンストラクトをインポートします。次に、コンストラクトインスタンス内でリソースのプロパティを定義します。

L1 コンストラクトは、 に精通し AWS CloudFormation ていて、 AWS リソースプロパティの定義を完全に制御する必要がある場合に適しています。

Construct Library AWS では、L1 コンストラクトの名前は で始まりCfn、その後にそれが表す AWS CloudFormation リソースの識別子が続きます。例えば、 CfnBucketコンストラクトは AWS::S3::Bucket AWS CloudFormation リソースを表す L1 コンストラクトです。

L1 コンストラクトは、AWS CloudFormation リソース仕様 から生成されます。リソースが に存在する場合 AWS CloudFormation、そのリソースは L1 コンストラクト AWS CDK として で使用できます。新しいリソースまたはプロパティが Construct Library で使用可能になるまでに最大 1 AWS 週間かかる場合があります。詳細については、「 ユーザーガイド」の「 AWS リソースタイプとプロパティタイプのリファレンス」を参照してください。 AWS CloudFormation

レベル 2 (L2) コンストラクト

キュレートされたコンストラクトとも呼ばれる L2 コンストラクトは CDK チームによって意図的に開発されており、通常は最も広く使用されているコンストラクトタイプです。L2 コンストラクトは、L1 コンストラクトと同様に、単一の AWS CloudFormation リソースに直接マッピングされます。L1 コンストラクトと比較すると、L2 コンストラクトは直感的なインテントベースの API を通じて高レベルの抽象化を提供します。L2 コンストラクトには、適切なデフォルトのプロパティ設定、ベストプラクティスのセキュリティポリシー、定型コードとグルーロジックの多くが含まれています。

L2 コンストラクトは、ほとんどのリソースのヘルパーメソッドも提供しており、プロパティ、アクセス許可、リソース間のイベントベースのインタラクションなどを簡単にすばやく定義できます。

s3.Bucket クラスは、Amazon Simple Storage Service (Amazon S3) バケットリソースの L2 コンストラクトの例です。

AWS Construct Library には、安定しており、本番環境で使用できる L2 コンストラクトが含まれています。開発中の L2 コンストラクトは実験的なものとして指定され、別のモジュールで提供されます。

レベル 3 (L3) コンストラクト

パターン とも呼ばれる L3 コンストラクトは、最高レベルの抽象化です。 各 L3 コンストラクトには、アプリケーション内の特定のタスクまたはサービスを達成するために連携するように設定されたリソースのコレクションを含めることができます。L3 コンストラクトは、アプリケーション内の特定のユースケースの AWS アーキテクチャ全体を作成するために使用されます。

完全なシステム設計、または大規模なシステムのかなりの部分を提供するために、L3 コンストラクトは独自のデフォルトのプロパティ設定を提供します。これらは、問題の解決とソリューションの提供に関する特定のアプローチを中心に構築されています。L3 コンストラクトを使用すると、入力とコードの量を最小限に抑えながら、複数のリソースをすばやく作成して設定できます。

ecsPatterns.ApplicationLoadBalancedFargateService クラスは、Amazon Elastic Container Service (Amazon ECS) クラスターで実行され、Application Load Balancer によって前面にある AWS Fargate サービスを表す L3 コンストラクトの例です。

L2 コンストラクトと同様に、本番環境で使用できる L3 AWS コンストラクトは コンストラクトライブラリに含まれています。開発中のモジュールは、個別のモジュールで提供されます。

コンストラクトの定義

コンポジション

コンポジションは、コンストラクトを通じて高レベルの抽象化を定義するための重要なパターンです。高レベルコンストラクトは、任意の数の低レベルコンストラクトから構成できます。ボトムアップの観点からは、コンストラクトを使用して、デプロイする個々の AWS リソースを整理します。任意の抽象化を使用し、必要な数だけレベルを設定できます。

コンポジションでは、再利用可能なコンポーネントを定義し、他のコードと同様に共有します。例えば、チームは、バックアップ、グローバルレプリケーション、自動スケーリング、モニタリングなど、Amazon DynamoDB テーブルに関する会社のベストプラクティスを実装するコンストラクトを定義できます。チームは、コンストラクトを他のチームと共有することも、パブリックに共有することもできます。

チームは他のライブラリパッケージと同様にコンストラクトを使用できます。ライブラリが更新されると、デベロッパーは他のコードライブラリと同様に、新しいバージョンの改善とバグ修正にアクセスできます。

初期化

コンストラクトは、Construct 基本クラスを拡張するクラスで実装されます。コンストラクトを定義するには、 クラスをインスタンス化します。すべてのコンストラクトは、初期化時に次の 3 つのパラメータを取ります。

  • scope – コンストラクトの親または所有者。これはスタックでも別のコンストラクトでもかまいません。スコープは、コンストラクトツリー 内のコンストラクトの位置を決定します。通常、スコープの現在のオブジェクトを表す this (self の Python) を渡す必要があります。

  • id – スコープ内で一意でなければならない識別子。識別子は、コンストラクト内で定義されているすべての名前空間として機能します。リソース名や AWS CloudFormation 論理 IDs などの一意の識別子を生成するために使用されます。

    識別子はスコープ内でのみ一意である必要があります。これにより、含まれる可能性のあるコンストラクトや識別子を気にせずにコンストラクトをインスタンス化して再利用でき、コンストラクトを上位レベルの抽象化に構成できます。さらに、スコープを使用すると、コンストラクトのグループを一度に参照できます。例としては、 のタグ付けや、コンストラクトをデプロイする場所の指定などがあります。

  • props – 言語に応じて、コンストラクトの初期設定を定義するプロパティまたはキーワード引数のセット。上位レベルのコンストラクトはより多くのデフォルトを提供し、すべてのプロパ要素がオプションの場合は、props パラメータを完全に省略できます。

構成

ほとんどのコンストラクトは、3 番目の引数 (または Python ではキーワード引数) propsとして、コンストラクトの設定を定義する名前/値コレクションを受け入れます。次の例では、 AWS Key Management Service (AWS KMS) 暗号化と静的ウェブサイトホスティングが有効になっているバケットを定義します。暗号化キーを明示的に指定しないため、Bucketコンストラクトは新しい を定義kms.Keyしてバケットに関連付けます。

TypeScript
new s3.Bucket(this, 'MyEncryptedBucket', { encryption: s3.BucketEncryption.KMS, websiteIndexDocument: 'index.html' });
JavaScript
new s3.Bucket(this, 'MyEncryptedBucket', { encryption: s3.BucketEncryption.KMS, websiteIndexDocument: 'index.html' });
Python
s3.Bucket(self, "MyEncryptedBucket", encryption=s3.BucketEncryption.KMS, website_index_document="index.html")
Java
Bucket.Builder.create(this, "MyEncryptedBucket") .encryption(BucketEncryption.KMS_MANAGED) .websiteIndexDocument("index.html").build();
C#
new Bucket(this, "MyEncryptedBucket", new BucketProps { Encryption = BucketEncryption.KMS_MANAGED, WebsiteIndexDocument = "index.html" });
Go
awss3.NewBucket(stack, jsii.String("MyEncryptedBucket"), &awss3.BucketProps{ Encryption: awss3.BucketEncryption_KMS, WebsiteIndexDocument: jsii.String("index.html"), })

コンストラクトの操作

コンストラクトは、基本コンストラクトクラスを拡張するクラスです。コンストラクトをインスタンス化すると、コンストラクトオブジェクトはコンストラクトとやり取りし、システムの他の部分への参照として渡すことができる一連のメソッドとプロパティを公開します。

この AWS CDK フレームワークは、コンストラクトの APIs に制限を課しません。作成者は任意の API を定義できます。ただし、 などの コンストラクトライブラリに含まれている AWS コンストラクト AWS はs3.Bucket、ガイドラインと一般的なパターンに従います。これにより、すべての AWS リソースで一貫したエクスペリエンスが得られます。

ほとんどの AWS コンストラクトには、そのコンストラクトに対する AWS Identity and Access Management (IAM) アクセス許可をプリンシパルに付与するために使用できる一連のグラントメソッドがあります。次の例では、Amazon S3 バケット から読み取るアクセスdata-science許可を IAM グループに付与しますraw-data。 Amazon S3

TypeScript
const rawData = new s3.Bucket(this, 'raw-data'); const dataScience = new iam.Group(this, 'data-science'); rawData.grantRead(dataScience);
JavaScript
const rawData = new s3.Bucket(this, 'raw-data'); const dataScience = new iam.Group(this, 'data-science'); rawData.grantRead(dataScience);
Python
raw_data = s3.Bucket(self, 'raw-data') data_science = iam.Group(self, 'data-science') raw_data.grant_read(data_science)
Java
Bucket rawData = new Bucket(this, "raw-data"); Group dataScience = new Group(this, "data-science"); rawData.grantRead(dataScience);
C#
var rawData = new Bucket(this, "raw-data"); var dataScience = new Group(this, "data-science"); rawData.GrantRead(dataScience);
Go
rawData := awss3.NewBucket(stack, jsii.String("raw-data"), nil) dataScience := awsiam.NewGroup(stack, jsii.String("data-science"), nil) rawData.GrantRead(dataScience, nil)

もう 1 つの一般的なパターンは、 AWS コンストラクトが他の場所で提供されるデータからリソースの属性の 1 つを設定することです。属性には、Amazon リソースネーム (ARNs名前、または URLsを含めることができます。

次のコードは、 AWS Lambda 関数を定義し、 環境変数のキューの URL を介して Amazon Simple Queue Service (Amazon SQS) キューに関連付けます。

TypeScript
const jobsQueue = new sqs.Queue(this, 'jobs'); const createJobLambda = new lambda.Function(this, 'create-job', { runtime: lambda.Runtime.NODEJS_18_X, handler: 'index.handler', code: lambda.Code.fromAsset('./create-job-lambda-code'), environment: { QUEUE_URL: jobsQueue.queueUrl } });
JavaScript
const jobsQueue = new sqs.Queue(this, 'jobs'); const createJobLambda = new lambda.Function(this, 'create-job', { runtime: lambda.Runtime.NODEJS_18_X, handler: 'index.handler', code: lambda.Code.fromAsset('./create-job-lambda-code'), environment: { QUEUE_URL: jobsQueue.queueUrl } });
Python
jobs_queue = sqs.Queue(self, "jobs") create_job_lambda = lambda_.Function(self, "create-job", runtime=lambda_.Runtime.NODEJS_18_X, handler="index.handler", code=lambda_.Code.from_asset("./create-job-lambda-code"), environment=dict( QUEUE_URL=jobs_queue.queue_url ) )
Java
final Queue jobsQueue = new Queue(this, "jobs"); Function createJobLambda = Function.Builder.create(this, "create-job") .handler("index.handler") .code(Code.fromAsset("./create-job-lambda-code")) .environment(java.util.Map.of( // Map.of is Java 9 or later "QUEUE_URL", jobsQueue.getQueueUrl()) .build();
C#
var jobsQueue = new Queue(this, "jobs"); var createJobLambda = new Function(this, "create-job", new FunctionProps { Runtime = Runtime.NODEJS_18_X, Handler = "index.handler", Code = Code.FromAsset(@".\create-job-lambda-code"), Environment = new Dictionary<string, string> { ["QUEUE_URL"] = jobsQueue.QueueUrl } });
Go
createJobLambda := awslambda.NewFunction(stack, jsii.String("create-job"), &awslambda.FunctionProps{ Runtime: awslambda.Runtime_NODEJS_18_X(), Handler: jsii.String("index.handler"), Code: awslambda.Code_FromAsset(jsii.String(".\\create-job-lambda-code"), nil), Environment: &map[string]*string{ "QUEUE_URL": jsii.String(*jobsQueue.QueueUrl()), }, })

コンストラクトライブラリの最も一般的な API AWS パターンについては、「」を参照してくださいリソース

アプリケーションとスタックのコンストラクト

コンストラクトライブラリの AWS Appおよび Stack クラスは、一意のコンストラクトです。他のコンストラクトと比較すると、リソースは単独で設定 AWS されません。代わりに、他のコンストラクトのコンテキストを提供するために使用されます。 AWS リソースを表すすべてのコンストラクトは、Stackコンストラクトの範囲内で直接または間接的に定義する必要があります。 Stack コンストラクトはコンストラクトの範囲内で定義されますApp

CDK アプリの詳細については、「」を参照してくださいアプリケーション。CDK スタックの詳細については、「」を参照してくださいスタック

次の例では、単一のスタックを持つアプリケーションを定義します。スタック内では、L2 コンストラクトを使用して Amazon S3 バケットリソースを設定します。

TypeScript
import { App, Stack, StackProps } from 'aws-cdk-lib'; import * as s3 from 'aws-cdk-lib/aws-s3'; class HelloCdkStack extends Stack { constructor(scope: App, id: string, props?: StackProps) { super(scope, id, props); new s3.Bucket(this, 'MyFirstBucket', { versioned: true }); } } const app = new App(); new HelloCdkStack(app, "HelloCdkStack");
JavaScript
const { App , Stack } = require('aws-cdk-lib'); const s3 = require('aws-cdk-lib/aws-s3'); class HelloCdkStack extends Stack { constructor(scope, id, props) { super(scope, id, props); new s3.Bucket(this, 'MyFirstBucket', { versioned: true }); } } const app = new App(); new HelloCdkStack(app, "HelloCdkStack");
Python
from aws_cdk import App, Stack import aws_cdk.aws_s3 as s3 from constructs import Construct class HelloCdkStack(Stack): def __init__(self, scope: Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) s3.Bucket(self, "MyFirstBucket", versioned=True) app = App() HelloCdkStack(app, "HelloCdkStack")
Java
import software.amazon.awscdk.*; import software.amazon.awscdk.services.s3.*; public class HelloCdkStack extends Stack { public HelloCdkStack(final Construct scope, final String id) { this(scope, id, null); } public HelloCdkStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); Bucket.Builder.create(this, "MyFirstBucket") .versioned(true).build(); } }
C#
using Amazon.CDK; using Amazon.CDK.AWS.S3; namespace HelloCdkApp { internal static class Program { public static void Main(string[] args) { var app = new App(); new HelloCdkStack(app, "HelloCdkStack"); app.Synth(); } } public class HelloCdkStack : Stack { public HelloCdkStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props) { new Bucket(this, "MyFirstBucket", new BucketProps { Versioned = true }); } } }
Go
func NewHelloCdkStack(scope constructs.Construct, id string, props *HelloCdkStackProps) awscdk.Stack { var sprops awscdk.StackProps if props != nil { sprops = props.StackProps } stack := awscdk.NewStack(scope, &id, &sprops) awss3.NewBucket(stack, jsii.String("MyFirstBucket"), &awss3.BucketProps{ Versioned: jsii.Bool(true), }) return stack }

コンストラクトツリー

コンストラクトは、すべてのコンストラクトに渡される scope引数を使用して他のコンストラクトの内部で定義され、 App クラスをルートとして使用します。このようにして、 AWS CDK アプリケーションはコンストラクトツリー と呼ばれるコンストラクトの階層を定義します。

このツリーのルートは、 App クラスのオブジェクトであるアプリです。アプリ内で、1 つ以上のスタックをインスタンス化します。スタック内では、 AWS CloudFormation リソースまたは上位レベルのコンストラクトのいずれかをインスタンス化します。それ自体がリソースやその他のコンストラクトをインスタンス化する場合などに、ツリーの下に置かれます。

コンストラクトは常に別のコンストラクトの範囲内で明示的に定義されるため、コンストラクト間の関係に疑問はありません。ほとんどの場合、スコープとして this (Python では self) を渡す必要があります。これは、新しいコンストラクトが現在のコンストラクトの子であることを示します。意図したパターンは、 からコンストラクトを導き出しConstruct、コンストラクターで使用するコンストラクトをインスタンス化することです。

スコープを明示的に渡すと、各コンストラクトはそれ自体をツリーに追加できます。この動作は、すべてConstruct基本クラス に含まれます。これは、 でサポートされているすべての言語で同じように機能 AWS CDK し、イントロスペクションやその他の「マジック」を必要としません。

重要

厳密には、コンストラクトをインスタンス化thisするときに、 以外のスコープを渡すことができます。ツリー内の任意の場所、または同じアプリ内の別のスタックにコンストラクトを追加できます。例えば、引数として渡されたスコープにコンストラクトを追加する混合形式の関数を記述できます。ここでの実用的な難点は、コンストラクトに選択した IDs が他のユーザーのスコープ内で一意であることを簡単に保証できないことです。また、このプラクティスにより、コードの理解、保守、再利用が難しくなります。引scope数を悪用することなく、インテントを表現する方法を見つけるのがほとんどの場合です。

AWS CDK は、ツリーのルートから各子コンストラクトへのパス内のすべてのコンストラクトの IDs を使用して、 に必要な一意の IDs を生成します AWS CloudFormation。このアプローチでは、コンストラクト IDsは、ネイティブ のようにスタック全体ではなく、スコープ内で一意である必要があるだけです AWS CloudFormation。ただし、コンストラクトを別のスコープに移動すると、生成されたスタック固有の ID が変更され、同じリソースと見な AWS CloudFormation されません。

コンストラクトツリーは、 AWS CDK コードで定義したコンストラクトとは別のものです。ただし、ツリー内のそのコンストラクトを表すノードへの参照である任意のコンストラクトの node 属性からアクセスできます。各ノードは、ツリーのルートとノードの親スコープおよび子へのアクセスを提供する の属性であるNodeインスタンスです。

  • node.children - コンストラクトの直接の子。

  • node.id – スコープ内のコンストラクトの識別子。

  • node.path - すべての親の IDs を含むコンストラクトのフルパス。

  • node.root – コンストラクトツリー (アプリ) のルート。

  • node.scope – コンストラクトのスコープ (親)。ノードがルートの場合は未定義。

  • node.scopes - ルートまでのコンストラクトのすべての親。

  • node.uniqueId – ツリー内のこのコンストラクトの一意の英数字識別子 (デフォルトでは、 node.pathとハッシュから生成されます)。

コンストラクトツリーは、コンストラクトが最終 AWS CloudFormation テンプレートのリソースに合成される暗黙的な順序を定義します。あるリソースを別のリソースの前に作成する必要がある場合、 AWS CloudFormation または Construct Library AWS が一般的に依存関係を推測します。次に、リソースが正しい順序で作成されていることを確認します。

を使用して、2 つのノード間に明示的な依存関係を追加することもできますnode.addDependency()。詳細については、 AWS CDK API リファレンス「依存関係」を参照してください。

AWS CDK は、コンストラクトツリー内のすべてのノードにアクセスし、各ノードに対してオペレーションを実行する簡単な方法を提供します。詳細については、「側面」を参照してください。

コンストラクトの使用

L1 コンストラクトの使用

L1 は、個々の AWS CloudFormation リソースに直接マッピングします。リソースに必要な設定を指定する必要があります。

この例では、L1 CfnBucket コンストラクトを使用して bucket オブジェクトを作成します。

TypeScript
const bucket = new s3.CfnBucket(this, "MyBucket", { bucketName: "MyBucket" });
JavaScript
const bucket = new s3.CfnBucket(this, "MyBucket", { bucketName: "MyBucket" });
Python
bucket = s3.CfnBucket(self, "MyBucket", bucket_name="MyBucket")
Java
CfnBucket bucket = new CfnBucket.Builder().bucketName("MyBucket").build();
C#
var bucket = new CfnBucket(this, "MyBucket", new CfnBucketProps { BucketName= "MyBucket" });
Go
awss3.NewCfnBucket(stack, jsii.String("MyBucket"), &awss3.CfnBucketProps{ BucketName: jsii.String("MyBucket"), })

シンプルなブール値、文字列、数値、コンテナではないコンストラクトプロパティは、サポートされている言語で異なる方法で処理されます。

TypeScript
const bucket = new s3.CfnBucket(this, "MyBucket", { bucketName: "MyBucket", corsConfiguration: { corsRules: [{ allowedOrigins: ["*"], allowedMethods: ["GET"] }] } });
JavaScript
const bucket = new s3.CfnBucket(this, "MyBucket", { bucketName: "MyBucket", corsConfiguration: { corsRules: [{ allowedOrigins: ["*"], allowedMethods: ["GET"] }] } });
Python

Python では、これらのプロパティは L1 コンストラクトの内部クラスとして定義されたタイプで表されます。例えば、 cors_configurationのオプションプロパティには、タイプ のラッパーCfnBucketが必要ですCfnBucket.CorsConfigurationProperty。ここでは、 CfnBucket インスタンスcors_configurationで を定義します。

bucket = CfnBucket(self, "MyBucket", bucket_name="MyBucket", cors_configuration=CfnBucket.CorsConfigurationProperty( cors_rules=[CfnBucket.CorsRuleProperty( allowed_origins=["*"], allowed_methods=["GET"] )] ) )
Java

Java では、これらのプロパティは L1 コンストラクトの内部クラスとして定義されたタイプで表されます。例えば、 corsConfigurationのオプションプロパティには、タイプ のラッパーCfnBucketが必要ですCfnBucket.CorsConfigurationProperty。ここでは、 CfnBucket インスタンスcorsConfigurationで を定義します。

CfnBucket bucket = CfnBucket.Builder.create(this, "MyBucket") .bucketName("MyBucket") .corsConfiguration(new CfnBucket.CorsConfigurationProperty.Builder() .corsRules(Arrays.asList(new CfnBucket.CorsRuleProperty.Builder() .allowedOrigins(Arrays.asList("*")) .allowedMethods(Arrays.asList("GET")) .build())) .build()) .build();
C#

C# では、これらのプロパティは L1 コンストラクトの内部クラスとして定義されたタイプで表されます。例えば、 CorsConfigurationのオプションプロパティには、タイプ のラッパーCfnBucketが必要ですCfnBucket.CorsConfigurationProperty。ここでは、 CfnBucket インスタンスCorsConfigurationで を定義します。

var bucket = new CfnBucket(this, "MyBucket", new CfnBucketProps { BucketName = "MyBucket", CorsConfiguration = new CfnBucket.CorsConfigurationProperty { CorsRules = new object[] { new CfnBucket.CorsRuleProperty { AllowedOrigins = new string[] { "*" }, AllowedMethods = new string[] { "GET" }, } } } });
Go

Go では、これらのタイプは L1 コンストラクトの名前、アンダースコア、およびプロパティ名を使用して名前が付けられます。例えば、 CorsConfigurationのオプションの プロパティには、タイプ のラッパーCfnBucketが必要ですCfnBucket_CorsConfigurationProperty。ここでは、 CfnBucket インスタンスCorsConfigurationで を定義します。

awss3.NewCfnBucket(stack, jsii.String("MyBucket"), &awss3.CfnBucketProps{ BucketName: jsii.String("MyBucket"), CorsConfiguration: &awss3.CfnBucket_CorsConfigurationProperty{ CorsRules: []awss3.CorsRule{ awss3.CorsRule{ AllowedOrigins: jsii.Strings("*"), AllowedMethods: &[]awss3.HttpMethods{"GET"}, }, }, }, })
重要

L1 コンストラクトで L2 プロパティタイプを使用することはできません。その逆も同様です。 L1 L1 コンストラクトを使用する場合は、使用している L1 コンストラクトに定義されているタイプを常に使用してください。他の L1 コンストラクトの型は使用しないでください (名前は同じでも、型は同じではない場合もあります)。

言語固有の API リファレンスの一部では、現在 L1 プロパティタイプへのパスにエラーがあるか、これらのクラスを一切ドキュメント化していません。この問題は間もなく修正されます。その間、このようなタイプは常に、使用される L1 コンストラクトの内部クラスであることに注意してください。

L2 コンストラクトの使用

次の例では、L2 コンストラクトからオブジェクトを作成して Amazon S3 Bucket バケットを定義します。

TypeScript
import * as s3 from 'aws-cdk-lib/aws-s3'; // "this" is HelloCdkStack new s3.Bucket(this, 'MyFirstBucket', { versioned: true });
JavaScript
const s3 = require('aws-cdk-lib/aws-s3'); // "this" is HelloCdkStack new s3.Bucket(this, 'MyFirstBucket', { versioned: true });
Python
import aws_cdk.aws_s3 as s3 # "self" is HelloCdkStack s3.Bucket(self, "MyFirstBucket", versioned=True)
Java
import software.amazon.awscdk.services.s3.*; public class HelloCdkStack extends Stack { public HelloCdkStack(final Construct scope, final String id) { this(scope, id, null); } public HelloCdkStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); Bucket.Builder.create(this, "MyFirstBucket") .versioned(true).build(); } }
C#
using Amazon.CDK.AWS.S3; // "this" is HelloCdkStack new Bucket(this, "MyFirstBucket", new BucketProps { Versioned = true });
Go
import ( "github.com/aws/aws-cdk-go/awscdk/v2/awss3" "github.com/aws/jsii-runtime-go" ) // stack is HelloCdkStack awss3.NewBucket(stack, jsii.String("MyFirstBucket"), &awss3.BucketProps{ Versioned: jsii.Bool(true), })>

MyFirstBucket は、 が AWS CloudFormation 作成するバケットの名前ではありません。これは CDK アプリのコンテキスト内の新しいコンストラクトに与えられる論理識別子です。physicalName 値を使用して AWS CloudFormation リソースに名前を付けます。

サードパーティーのコンストラクトの使用

Construct Hub は、 AWS、サードパーティ、およびオープンソース CDK コミュニティから追加のコンストラクトを発見するのに役立つリソースです。

独自のコンストラクトを作成する

既存のコンストラクトを使用するだけでなく、独自のコンストラクトを記述して、誰でもアプリで使用できるようにすることもできます。すべてのコンストラクトは で等しくなります AWS CDK。コンストラクトライブラリからの AWS コンストラクトは、NPM、、Mavenまたは を介して公開されたサードパーティーライブラリからのコンストラクトと同じように扱われますPyPI。会社の内部パッケージリポジトリに公開されたコンストラクトも同じ方法で扱われます。

新しいコンストラクトを宣言するには、 constructsパッケージでコンストラクトベースクラスを拡張するクラスを作成し、イニシャライザ引数のパターンに従います。

次の例は、Amazon S3 バケットを表すコンストラクトを宣言する方法を示しています。S3 バケットは、誰かがファイルをアップロードするたびに Amazon Simple Notification Service (Amazon SNS) 通知を送信します。

TypeScript
export interface NotifyingBucketProps { prefix?: string; } export class NotifyingBucket extends Construct { constructor(scope: Construct, id: string, props: NotifyingBucketProps = {}) { super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); const topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(new s3notify.SnsDestination(topic), { prefix: props.prefix }); } }
JavaScript
class NotifyingBucket extends Construct { constructor(scope, id, props = {}) { super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); const topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(new s3notify.SnsDestination(topic), { prefix: props.prefix }); } } module.exports = { NotifyingBucket }
Python
class NotifyingBucket(Construct): def __init__(self, scope: Construct, id: str, *, prefix=None): super().__init__(scope, id) bucket = s3.Bucket(self, "bucket") topic = sns.Topic(self, "topic") bucket.add_object_created_notification(s3notify.SnsDestination(topic), s3.NotificationKeyFilter(prefix=prefix))
Java
public class NotifyingBucket extends Construct { public NotifyingBucket(final Construct scope, final String id) { this(scope, id, null, null); } public NotifyingBucket(final Construct scope, final String id, final BucketProps props) { this(scope, id, props, null); } public NotifyingBucket(final Construct scope, final String id, final String prefix) { this(scope, id, null, prefix); } public NotifyingBucket(final Construct scope, final String id, final BucketProps props, final String prefix) { super(scope, id); Bucket bucket = new Bucket(this, "bucket"); Topic topic = new Topic(this, "topic"); if (prefix != null) bucket.addObjectCreatedNotification(new SnsDestination(topic), NotificationKeyFilter.builder().prefix(prefix).build()); } }
C#
public class NotifyingBucketProps : BucketProps { public string Prefix { get; set; } } public class NotifyingBucket : Construct { public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id) { var bucket = new Bucket(this, "bucket"); var topic = new Topic(this, "topic"); bucket.AddObjectCreatedNotification(new SnsDestination(topic), new NotificationKeyFilter { Prefix = props?.Prefix }); } }
Go
type NotifyingBucketProps struct { awss3.BucketProps Prefix *string } func NewNotifyingBucket(scope constructs.Construct, id *string, props *NotifyingBucketProps) awss3.Bucket { var bucket awss3.Bucket if props == nil { bucket = awss3.NewBucket(scope, jsii.String(*id+"Bucket"), nil) } else { bucket = awss3.NewBucket(scope, jsii.String(*id+"Bucket"), &props.BucketProps) } topic := awssns.NewTopic(scope, jsii.String(*id+"Topic"), nil) if props == nil { bucket.AddObjectCreatedNotification(awss3notifications.NewSnsDestination(topic)) } else { bucket.AddObjectCreatedNotification(awss3notifications.NewSnsDestination(topic), &awss3.NotificationKeyFilter{ Prefix: props.Prefix, }) } return bucket }
注記

NotifyingBucket コンストラクトは からではなくBucket、 から継承しますConstruct。Amazon S3 バケットと Amazon SNS トピックをバンドルするために、継承ではなくコンポジションを使用しています。一般に、 AWS CDK コンストラクトを開発する場合は、継承よりもコンポジションが優先されます。

NotifyingBucket コンストラクタには、、scopeidおよび の一般的なコンストラクトシグネチャがありますprops。最後の引数 はオプション (デフォルト値 を取得{}) です。これはprops、すべての props がオプションであるためです。(基本Constructクラスは引props数を取りません。) このコンストラクトのインスタンスはprops、 なしでアプリで定義できます。次に例を示します。

TypeScript
new NotifyingBucket(this, 'MyNotifyingBucket');
JavaScript
new NotifyingBucket(this, 'MyNotifyingBucket');
Python
NotifyingBucket(self, "MyNotifyingBucket")
Java
new NotifyingBucket(this, "MyNotifyingBucket");
C#
new NotifyingBucket(this, "MyNotifyingBucket");
Go
NewNotifyingBucket(stack, jsii.String("MyNotifyingBucket"), nil)

または、 props (Java では追加のパラメータ) を使用して、フィルタリングするパスプレフィックスを指定できます。次に例を示します。

TypeScript
new NotifyingBucket(this, 'MyNotifyingBucket', { prefix: 'images/' });
JavaScript
new NotifyingBucket(this, 'MyNotifyingBucket', { prefix: 'images/' });
Python
NotifyingBucket(self, "MyNotifyingBucket", prefix="images/")
Java
new NotifyingBucket(this, "MyNotifyingBucket", "/images");
C#
new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketProps { Prefix = "/images" });
Go
NewNotifyingBucket(stack, jsii.String("MyNotifyingBucket"), &NotifyingBucketProps{ Prefix: jsii.String("images/"), })

通常、コンストラクトのプロパティやメソッドを公開する必要もあります。コンストラクトのユーザーがサブスクライブできないため、コンストラクトの背後でトピックを非表示にすることはあまり有用ではありません。topic プロパティを追加すると、次の例に示すように、コンシューマーは内部トピックにアクセスできます。

TypeScript
export class NotifyingBucket extends Construct { public readonly topic: sns.Topic; constructor(scope: Construct, id: string, props: NotifyingBucketProps) { super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); this.topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(new s3notify.SnsDestination(this.topic), { prefix: props.prefix }); } }
JavaScript
class NotifyingBucket extends Construct { constructor(scope, id, props) { super(scope, id); const bucket = new s3.Bucket(this, 'bucket'); this.topic = new sns.Topic(this, 'topic'); bucket.addObjectCreatedNotification(new s3notify.SnsDestination(this.topic), { prefix: props.prefix }); } } module.exports = { NotifyingBucket };
Python
class NotifyingBucket(Construct): def __init__(self, scope: Construct, id: str, *, prefix=None, **kwargs): super().__init__(scope, id) bucket = s3.Bucket(self, "bucket") self.topic = sns.Topic(self, "topic") bucket.add_object_created_notification(s3notify.SnsDestination(self.topic), s3.NotificationKeyFilter(prefix=prefix))
Java
public class NotifyingBucket extends Construct { public Topic topic = null; public NotifyingBucket(final Construct scope, final String id) { this(scope, id, null, null); } public NotifyingBucket(final Construct scope, final String id, final BucketProps props) { this(scope, id, props, null); } public NotifyingBucket(final Construct scope, final String id, final String prefix) { this(scope, id, null, prefix); } public NotifyingBucket(final Construct scope, final String id, final BucketProps props, final String prefix) { super(scope, id); Bucket bucket = new Bucket(this, "bucket"); topic = new Topic(this, "topic"); if (prefix != null) bucket.addObjectCreatedNotification(new SnsDestination(topic), NotificationKeyFilter.builder().prefix(prefix).build()); } }
C#
public class NotifyingBucket : Construct { public readonly Topic topic; public NotifyingBucket(Construct scope, string id, NotifyingBucketProps props = null) : base(scope, id) { var bucket = new Bucket(this, "bucket"); topic = new Topic(this, "topic"); bucket.AddObjectCreatedNotification(new SnsDestination(topic), new NotificationKeyFilter { Prefix = props?.Prefix }); } }
Go

Go でこれを行うには、少し追加の列が必要です。元のNewNotifyingBucket関数は を返しますawss3.Bucket。構造体を作成して、topicメンバーを含めるBucketように NotifyingBucket を拡張する必要があります。次に、このタイプが関数によって返されます。

type NotifyingBucket struct { awss3.Bucket topic awssns.Topic } func NewNotifyingBucket(scope constructs.Construct, id *string, props *NotifyingBucketProps) NotifyingBucket { var bucket awss3.Bucket if props == nil { bucket = awss3.NewBucket(scope, jsii.String(*id+"Bucket"), nil) } else { bucket = awss3.NewBucket(scope, jsii.String(*id+"Bucket"), &props.BucketProps) } topic := awssns.NewTopic(scope, jsii.String(*id+"Topic"), nil) if props == nil { bucket.AddObjectCreatedNotification(awss3notifications.NewSnsDestination(topic)) } else { bucket.AddObjectCreatedNotification(awss3notifications.NewSnsDestination(topic), &awss3.NotificationKeyFilter{ Prefix: props.Prefix, }) } var nbucket NotifyingBucket nbucket.Bucket = bucket nbucket.topic = topic return nbucket }

これで、コンシューマーはトピックにサブスクライブできます。次に例を示します。

TypeScript
const queue = new sqs.Queue(this, 'NewImagesQueue'); const images = new NotifyingBucket(this, '/images'); images.topic.addSubscription(new sns_sub.SqsSubscription(queue));
JavaScript
const queue = new sqs.Queue(this, 'NewImagesQueue'); const images = new NotifyingBucket(this, '/images'); images.topic.addSubscription(new sns_sub.SqsSubscription(queue));
Python
queue = sqs.Queue(self, "NewImagesQueue") images = NotifyingBucket(self, prefix="Images") images.topic.add_subscription(sns_sub.SqsSubscription(queue))
Java
NotifyingBucket images = new NotifyingBucket(this, "MyNotifyingBucket", "/images"); images.topic.addSubscription(new SqsSubscription(queue));
C#
var queue = new Queue(this, "NewImagesQueue"); var images = new NotifyingBucket(this, "MyNotifyingBucket", new NotifyingBucketProps { Prefix = "/images" }); images.topic.AddSubscription(new SqsSubscription(queue));
Go
queue := awssqs.NewQueue(stack, jsii.String("NewImagesQueue"), nil) images := NewNotifyingBucket(stack, jsii.String("MyNotifyingBucket"), &NotifyingBucketProps{ Prefix: jsii.String("/images"), }) images.topic.AddSubscription(awssnssubscriptions.NewSqsSubscription(queue, nil))

詳細はこちら

次の動画では、CDK コンストラクトの包括的な概要と、CDK アプリでの使用方法について説明します。