AWS CDKでリソース間の依存性をaddDependsOnで明示的に定義する

2021.06.12

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

こんにちは、CX事業本部の若槻です。

今回は、AWS CDKでリソース間の依存性をaddDependsOnで明示的に定義してみました。

他のリソースに依存しているリソースの作成が失敗する

下記のようにCDKでロググループと、そのロググループに属するログストリームのリソースを作成する機会がありました。

cdk-stack.ts

import * as logs from '@aws-cdk/aws-logs';
  //中略
    const myLogGroup = new logs.CfnLogGroup(
      this,
      'MyLogGroup',
      {
        logGroupName: "/aws/kinesisfirehose/myLogGroup",
      },
    );
    const myLogStream = new logs.CfnLogStream(
      this,
      'MyLogStream',
      {
        logGroupName: myLogStream.logGroupName as string,
        logStreamName: "myLogStream",
      },
    );

しかし、上記の定義をcdk deployした時に、いずれのリソースも正常に作成が成功する時もあれば、ロググループが作成されないうちにログストリームの作成が行われ下記のようなエラーとなることがありました。

The specified log group does not exist. (Service: AWSLogs; Status Code: 400; Error Code: ResourceNotFoundException; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx; Proxy: null)

addDependsOnでリソース間の依存性を明示的に定義してみた

そこでリソース間の依存性を定義する必要があるのではと考えドキュメントを見ると、下記のようにありました。cfnResourceのaddDependsOnメソッドを使えばよさそうです。

CloudFormation resources can also specify resource attributes. The CfnResource class allows accessing those through the cfnOptions property:

Resource dependencies (the DependsOn attribute) is modified using the cfnResource.addDependsOn method:

早速スタックの記述に下記のハイライトの行を追加したところ、リソースの作成が正常に行えるようになりました。

cdk-stack.ts

import * as logs from '@aws-cdk/aws-logs';
  //中略
    const myLogGroup = new logs.CfnLogGroup(
      this,
      'MyLogGroup',
      {
        logGroupName: "/aws/kinesisfirehose/myLogGroup",
      },
    );
    const myLogStream = new logs.CfnLogStream(
      this,
      'MyLogStream',
      {
        logGroupName: myLogStream.logGroupName as string,
        logStreamName: "myLogStream",
      },
    );
    myLogStream.addDependsOn(myLogGroup);  //追記

おわりに

AWS CDKでリソース間の依存性をaddDependsOnで明示的に定義してみました。

addDependsOn()はCloudFormationのDependOnに対応しているもののようで、過去のDev.IOの記事でも何度か取り上げられています。CDKで同様のリソース作成を行う際に使う機会がありそうですね。

参考

以上