CDK-如何使用VPC配置创建SageMaer模型

问题描述

问题

如何使用带有CDK的VPC配置创建SageMaker模型?

CDK SageMaker CfnModel具有vpc_config参数来保护资源访问。要求不要将流量公开到Internet。在下面指定了vpc_config参数,该参数不会告诉我们如何配置它。

vpc_config (Union[IResolvable,Forwardref,None]) 
AWS::SageMaker::Model.VpcConfig.

实际类是VpcConfigProperty代码在CDK安装的aws / cdk / libcdk_elasticsearch.py​​中。

class VpcConfigProperty:
    def __init__(
        self,*,security_group_ids: typing.List[str],subnets: typing.List[str]
    ) -> None:
        """
        :param security_group_ids: ``CfnModel.VpcConfigProperty.SecurityGroupIds``.
        :param subnets: ``CfnModel.VpcConfigProperty.subnets``.

解决方法

目前,CDK文档和Github示例处于低于标准水平。他们需要清理并提供更好的文档和示例。

from aws_cdk import (
    aws_ec2,aws_sagemaker,aws_iam,core
)

class HelloCdkStack(core.Stack):

    def __init__(self,scope: core.Construct,id: str,**kwargs) -> None:
        super().__init__(scope,id,**kwargs)

        sagemaker_execution_role = aws_iam.Role(
            self,"SagemakerExecutionRole",assumed_by=aws_iam.ServicePrincipal("sagemaker.amazonaws.com")
        )

        sagemaker_vpc = aws_ec2.Vpc(
            self,"Vpc",cidr="192.168.0.0/16"
        )

        sagemaker_security_group = aws_ec2.SecurityGroup(
            self,"SG",vpc=sagemaker_vpc
        )

        subnet_selection = sagemaker_vpc.select_subnets(
            subnet_type=aws_ec2.SubnetType.PRIVATE
        )

        vpc_config = aws_sagemaker.CfnModel.VpcConfigProperty(
            security_group_ids=[
                sagemaker_security_group.security_group_id
            ],# This is how you set the subnets for the SageMaker model
            subnets=subnet_selection.subnet_ids
        )

        sagemaker_model = aws_sagemaker.CfnModel(
            self,"SagemakerModel",execution_role_arn=sagemaker_execution_role.role_arn,containers=[aws_sagemaker.CfnModel.ContainerDefinitionProperty(
                image="123456789012.dkr.ecr.us-west-2.amazonaws.com/mymodel:latest"
            )],# This is how you setup vpc_config here
            vpc_config=vpc_config
        )