如何在aws cdk中导入现有的VPC?

How to import existing VPC in 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 吗?任何帮助,将不胜感激。谢谢

看看aws_cdk.aws_ec2 documentation and at CDK Runtime Context

If your VPC is created outside your CDK app, you can use Vpc.fromLookup(). The CDK CLI will search for the specified VPC in the the stack’s region and account, and import the subnet configuration. Looking up can be done by VPC ID, but more flexibly by searching for a specific tag on the VPC.

用法:

# Example automatically generated. See https://github.com/aws/jsii/issues/826
from aws_cdk.core import App, Stack, Environment
from aws_cdk import aws_ec2 as ec2

# Information from environment is used to get context information
# so it has to be defined for the stack
stack = MyStack(
    app, "MyStack", env=Environment(account="account_id", region="region")
)

# Retrieve VPC information
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
)

使用打字稿示例更新:

import ec2 = require('@aws-cdk/aws-ec2');
const getExistingVpc = ec2.Vpc.fromLookup(this, 'ImportVPC',{isDefault: true});

More info here.

这是一个简单的例子

//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),
    });