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

Nir*_*jan 19 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')
Run Code Online (Sandbox Code Playgroud)

这导致以下错误

[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
Run Code Online (Sandbox Code Playgroud)

我试过的其他方法是

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

这导致

[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
Run Code Online (Sandbox Code Playgroud)

我试过的其他方法是

vpc = ec2.Vpc.from_lookup(self, id = "VPC", is_default=True) // 这将获得默认的 vpc,这将起作用

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

Ami*_*nes 24

查看aws_cdk.aws_ec2 文档CDK 运行时上下文

如果您的 VPC 是在 CDK 应用程序之外创建的,您可以使用 Vpc.fromLookup()。CDK CLI 将在堆栈的区域和帐户中搜索指定的 VPC ,并导入子网配置。可以通过 VPC ID 进行查找,但通过搜索 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
)
Run Code Online (Sandbox Code Playgroud)

使用相关示例进行更新:

vpc = ec2.Vpc.from_lookup(stack, "VPC",
    vpc_id = VPC_ID
)
Run Code Online (Sandbox Code Playgroud)

更新打字稿示例:

import ec2 = require('@aws-cdk/aws-ec2');
const getExistingVpc = ec2.Vpc.fromLookup(this, 'ImportVPC',{isDefault: false,vpcId: vpcId });
Run Code Online (Sandbox Code Playgroud)

更多信息在这里。