如何在AWS CDK中导入现有VPC?

时间:2019-12-12 09:21:07

标签: amazon-web-services amazon-vpc aws-cdk

嗨,我正在研究AWS CDK。我正在尝试获取现有的非默认vpc。我尝试了以下选项。

vpc = ec2.Vpc.from_lookup(self, id = "VPC", vpc_id='vpcid', vpc_name='vpc-dev')

这将导致以下错误

[Error at /LocationCdkStack-cdkstack] Request has expired.
[Warning at /LocationCdkStack-cdkstack/TaskDef/mw-service] Proper policies need to be attached before pulling from ECR repository, or use 'fromEcrRepository'.
Found errors

我尝试过的其他方法是

vpc = ec2.Vpc.from_vpc_attributes(self, 'VPC', vpc_id='vpc-839227e7', availability_zones=['ap-southeast-2a','ap-southeast-2b','ap-southeast-2c'])

这将导致

[Error at /LocationCdkStack-cdkstack] Request has expired.
[Warning at /LocationCdkStack-cdkstack/TaskDef/mw-service] Proper policies need to be attached before pulling from ECR repository, or use 'fromEcrRepository'.
Found errors

我尝试过的其他方法是

vpc = ec2.Vpc.from_lookup(self, id = "VPC", is_default=True) //这将获得默认的vpc,并且可以正常工作

有人可以帮助我在AWS CDK中获得非默认VPC吗?任何帮助,将不胜感激。谢谢

2 个答案:

答案 0 :(得分:1)

看看aws_cdk.aws_ec2 documentation

  

如果您的VPC是在CDK应用程序外部创建的,则可以使用   Vpc.fromLookup()。 CDK CLI将在以下位置搜索指定的VPC:   堆栈的区域和帐户,然后导入子网配置。   可以通过VPC ID进行查找,但可以通过搜索   VPC上的特定标签。

用法:

# Example automatically generated. See https://github.com/aws/jsii/issues/826
vpc = ec2.Vpc.from_lookup(stack, "VPC",
    # This imports the default VPC but you can also
    # specify a 'vpcName' or 'tags'.
    is_default=True
)

使用相关示例进行更新:

vpc = ec2.Vpc.from_lookup(stack, "VPC",
    vpc_id = VPC_ID
)

More info here.

答案 1 :(得分:0)

这是一个简单的例子

//get VPC Info form AWS account, FYI we are not rebuilding we are referencing 
const DefaultVpc = Vpc.fromVpcAttributes(this, 'vpcdev', {
    vpcId:'vpc-d0e0000b0',
    availabilityZones: core.Fn.getAzs(),
    privateSubnetIds: 'subnet-00a0de00',
    publicSubnetIds: 'subnet-00a0de00'
});

        const yourService = new lambda.Function(this, 'SomeName', {
        code: lambda.Code.fromAsset("lambda"),
        handler: 'handlers.your_handler',
        role: lambdaExecutionRole,
        securityGroup: lambdaSecurityGroup,
        vpc: DefaultVpc,
        runtime: lambda.Runtime.PYTHON_3_7,
        timeout: Duration.minutes(2),
    });