首页 > 解决方案 > 通过 AWS CDK Typescript 进行 VPC 对等互连(2 个 VPCS 在 2 个不同的账户中)

问题描述

我正在尝试为 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)
}); }}

标签: typescriptamazon-web-servicesamazon-vpcaws-cdk

解决方案


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
})

推荐阅读