AWS CDK 構築 - AWS Cloud Development Kit (AWS CDK) v2

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

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

AWS CDK 構築

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

コンストラクトをインポートして使用する

コンストラクトは、コンストラクトAWS ライブラリ からCDKアプリケーションにインポートするクラスです。また、独自のコンストラクトを作成して配布したり、サードパーティー開発者が作成したコンストラクトを使用したりできます。

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

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

ビルドレベル

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

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

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

L1 コンストラクトは、 AWS リソースプロパティの定義に慣れており AWS CloudFormation 、完全に制御する必要がある場合に最適です。

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

L1 コンストラクトはAWS CloudFormation リソース仕様 から生成されます。リソースが に存在する場合 AWS CloudFormation、L1 コンストラクト AWS CDK として で使用できます。新しいリソースまたはプロパティがコンストラクトライブラリで利用可能になるまでに最大 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 コンストラクトの例です。Amazon S3

AWS コンストラクトライブラリには、安定しており、本番環境で使用できるように指定された 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 CDKである必要があります。識別子は、 コンストラクト内で定義されているすべての名前空間として機能します。リソース名や AWS CloudFormation 論理 などの一意の識別子を生成するために使用されますIDs。

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

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

構成

ほとんどのコンストラクトは、3 props番目の引数 (または Python ではキーワード引数) として、コンストラクトの設定を定義する名前/値コレクションを受け入れます。次の例では、 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

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 CDK

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

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

CDK アプリケーションの詳細については、「」を参照してくださいAWS CDK アプリ。CDK スタックの詳細については、「」を参照してくださいAWS 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

HelloCdkStack.java ファイルで定義されるスタック:

import software.constructs.Construct; import software.amazon.awscdk.Stack; import software.amazon.awscdk.StackProps; 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(); } }

HelloCdkApp.java ファイルで定義されるアプリケーション:

import software.amazon.awscdk.App; import software.amazon.awscdk.StackProps; public class HelloCdkApp { public static void main(final String[] args) { App app = new App(); new HelloCdkStack(app, "HelloCdkStack", StackProps.builder() .build()); app.synth(); } }
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 }

コンストラクトの使用

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 コンストラクタには、、scope、および という一般的なコンストラクト署名がありますidprops。最後の引数 はオプション (デフォルト値 を取得{}) です。これは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.BucketNotifyingBucket 構造体を作成してtopic、メンバーを含めるBucketように拡張する必要があります。その後、関数はこのタイプを返します。

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。