AWS CDKでDependsOnの動作を複製できますか?

Aug 21 2020

AWS CDK(python)を使用して、分離されたサブネットといくつかのインターフェイスエンドポイントを備えたVPCを作成しています。

また、Codecommitリポジトリが関連付けられたSagemakerノートブックを起動します

CodecommitとGitCodecommitのインターフェースエンドポイントを作成しましたが、Sagemakerノートブックのデプロイを開始してもインターフェースエンドポイントが作成されているため、Cloudformationスタックがエラーで失敗します

fatal: unable to access 'https://git-codecommit.us-east-1.amazonaws.com/v1/repos/SomeRepo/': Failed to connect to git-codecommit.us-east-1.amazonaws.com port 443: Connection timed out

Sagemakerノートブックをコメントアウトして実行するcdk deploy myStackと、エンドポイントが作成されます。その後、ノートブックのコメントを解除できます。Codecommitインターフェイスエンドポイントが既に存在するため、問題なく起動します。

CDKをDependsOn使用して作成したリソースにを追加する方法はCDKにありますか?

以下の関連コード

from aws_cdk import (
    core,
    aws_sagemaker as sagemaker,
    aws_iam as iam,
    aws_ec2 as ec2
)

class SagemakerStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, bucket, repo, **kwargs) -> None:  # repo is passed with the codecommit repo I created in a previous stack
        super().__init__(scope, id, **kwargs)

        self.sagemaker_vpc = ec2.Vpc(
            # Leaving out some details
            self, "SagemakerVPC",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    subnet_type=ec2.SubnetType.ISOLATED,  # <-- Isolated, therefore need interface endpoints
                    name="IsolatedA",
                    cidr_mask=24
                )
            ]
        )

        self.sagemaker_vpc.add_interface_endpoint(
            "GitCodecommitInterface",
            service=ec2.InterfaceVpcEndpointAwsService.CODECOMMIT_GIT  # Needed to be created before I can create notebook
        )


        sagemaker_role = iam.Role()  # Hiding details
        sagemaker_repo = sagemaker.CfnCodeRepository()  # hiding details
        sagemaker_sg = ec2.SecurityGroup()  # Hiding details

        # Need for this to wait until GitCodecommitInterface has been created
        notebook = sagemaker.CfnNotebookInstance(
            self, "MyNotebook",
            instance_type="ml.t3.medium",
            role_arn=sagemaker_role.role_arn,
            default_code_repository=repo.repository_clone_url_http,
            subnet_id=self.sagemaker_vpc.isolated_subnets[0].subnet_id,
            direct_internet_access="Disabled",
            security_group_ids=[sagemaker_sg.security_group_id]
        )

回答

2 MauricioKlein Oct 14 2020 at 16:14

CDKにTypescriptを使用しているため、Pythonの構文はどうなっているのかわかりませんが、CDKコンストラクトは最終的にCloudFormationリソースで解決されるため、実際に可能です。

Typescriptを使用した例を次に示します。

const x = new apigateway.LambdaRestApi(this, "apigw", {...})
const y = new lambda.Function(this, "lambda", {...})

// Y will be deployed before X
x.node.addDependency(y)

したがって、CDKコンストラクトから内部ノードにアクセスする方法を理解した後は、非常に簡単です。