我正在尝试为2个单独帐户中2个vpc之间的vpc对等创建cdk打字稿。相关代码如下。 vpc创建良好,但是我无法从vpc1和vpc2引用vpcId和peerVpcId。谁能帮忙。任何有效的示例代码将非常有帮助。谢谢。
//creation of vpc 1
export class vpc1 extends cdk.Stack {
constructor(scope: cdk.App, id: string, props: EnvProps) {
super(scope, id, props);
const vpc = new ec2.Vpc(this, 'vpc1',{
cidr: props.vpcCidr ,
enableDnsHostnames: true,
enableDnsSupport: true,
maxAzs: 3,
subnetConfiguration: [{
cidrMask: 24,
name: 'Public',
subnetType: ec2.SubnetType.PUBLIC,
},
{
cidrMask: 24,
name: 'Private',
subnetType: ec2.SubnetType.PRIVATE,
}],
natGateways: 1
}); }}
//creation of vpc 2
export class vpc2 extends cdk.Stack {
constructor(scope: cdk.App, id: string, props: EnvProps) {
super(scope, id, props);
const vpc = new ec2.Vpc(this, 'vpc2',{
cidr: props.vpcCidr ,
enableDnsHostnames: true,
enableDnsSupport: true,
maxAzs: 3,
subnetConfiguration: [{
cidrMask: 24,
name: 'Public',
subnetType: ec2.SubnetType.PUBLIC,
},
{
cidrMask: 24,
name: 'Private',
subnetType: ec2.SubnetType.PRIVATE,
}],
natGateways: 1
});
}}
export class vpcPeeringfisHiDev extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const vpc_peering = new ec2.CfnVPCPeeringConnection (this, 'vpcPeer',{
vpcId: vpc1.vpc.vpcId, //Error - Property 'vpc' does not exist on type 'typeof vpc1'.ts(2339)
peerVpcId: vpc2.vpc.vpcId //Error - Property 'vpc' does not exist on type 'typeof vpc2'.ts(2339)
}); }}
答案 0 :(得分:0)
您必须在各自的堆栈中公开正在创建的vpc: ec2.Vpc
构造,以便vpcPeeringfisHiDev
可以使用它们:
export class vpc1 extends cdk.Stack {
readonly vpc: ec2.Vpc // <-- add this
constructor (...) {
// :: instead of `const vpc =`
this.vpc = new ec2.Vpc (...)
}
// ...
}
// :: do that for the vpc2 stack too
export interface VpcPeeringStackProps extends cdk.StackProps {
vpc1: ec2.Vpc,
vpc2: ec2.Vpc
}
export class VpcPeeringStack extends cdk.Stack {
constructor (scope: cdk.Construct, id: string, props: VpcPeeringStackProps) {
// ...
const peering = new ec2.CfnVPCPeeringConnection(this, '...', {
// :: now you can use them here
vpcId: props.vpc1.vpcId,
peerVpcId: props.vpc2.vpcId
})
}
}
然后在CDK应用程序定义文件中,您需要正确传递引用:
const vpc1stack = new vpc1(app, 'vpc1')
const vpc2stack = new vpc2(app, 'vpc2')
// :: the peering stack --- note how we're passing in the 2 previous VPCs
new VpcPeeringStack(app, 'peering', {
vpc1: vpc1stack.vpc,
vpc2: vpc2stack.vpc
})