AWS CDK。如何将第一个堆栈的 `id` 传递给第二个堆栈

AWS CDK. How to pass `id` of first stack to second stack

我有一个项目有多个堆栈,但有共同的 stacks.ts 文件。


堆叠vpc.tf

export class stack-vpc extends Stack {
   constructor(scope: Construct, id: string, props?: props) {
       super(scope, id, props);
       new ec2.Vpc(this, 'dev-vpc', {
           cidr: "10.0.0.0/16",
           vpcName: "dev-vpc"
       })
   }
}

堆叠ecs.tf

export interface Istack-ecs extends StackProps {
   vpc: ec2.Vpc;
}


export class stack-ecs extends Construct {
   constructor(scope: Construct, id: string, props: Istack-ecs) {
       super(scope, id);
       new ecs.Cluster(this, "fargate", {
           vpc: props.vpc,
           clusterName: "test",
           enableFargateCapacityProviders: true
       });
   }
}

这是 stacks.ts 文件

const app = new cdk.App();
const vpc = new stack-vpc(app, "Dev_VPC_CF", props);
const ecs = new stack-ecs(app, "Dev_ECS_CF", props);

vpc 的创建没有任何问题,但是一旦我将 ecs 放入我的堆栈,cdk 就会给我错误:

[Error at /stack-ecs] Could not find any VPCs matching {"account":"__--__","region":"eu-central-1",
"filter":{"tag:Name":"stack-vpc","isDefault":"false"},
"returnAsymmetricSubnets":true,
"lookupRoleArn":"arn:aws:iam::__--__:role/cdk-hnb659fds-lookup-role-__--__-eu-central-1"}

cdk.context.json 正在从我的 aws 凭据中检索正确的值,所以我不能责怪身份验证,所以我的问题我需要以某种方式等到一个堆栈给我一个输出,这样我就可以在我的其他书架

fromLookup 方法用于引用现有的已部署资源。这不是你想要的。相反,使用 Typescript 语言功能在堆栈内和堆栈之间传递构造。正如@gshpychka 在评论中解释的那样,有几种 CDK 模式:

对于一个简单的应用程序,具有 Vpc 和 Ecs 资源的单个堆栈是 good approach. The cdk-examples repo has several such ECS examples with a Vpc:

export class MySingleStack extends Stack {
  constructor(scope: Construct, id: string, props?: props) {
    super(scope, id, props);
    const vpc = new ec2.Vpc(this, 'dev-vpc', {
      cidr: '10.0.0.0/16',
      vpcName: 'dev-vpc',
    });

    const cluster = new ecs.Cluster(this, 'Ec2Cluster', { vpc });
  }
}

或者,在同一应用程序的堆栈之间传递 Vpc 引用。 VpcStack 导出一个 Vpc。 EcsStack 的道具应该扩展 cdk.StackProps,添加一个 vpc: ec2.Vpc 属性。 vpc从VpcStack中导出并作为prop传递给EcsStack:

// vpc.ts
export class VpcStack extends Stack {
  readonly vpc: ec2.Vpc;

  constructor(scope: Construct, id: string, props?: props) {
    super(scope, id, props);
    this.vpc = new ec2.Vpc(this, 'dev-vpc', {
      cidr: '10.0.0.0/16',
      vpcName: 'dev-vpc',
    });
  }
}


// stacks.ts
const app = new cdk.App();
const { vpc } = new VpcStack(app, 'Dev_VPC_CF', props);
new EcsStack(app, 'Dev_ECS_CF', { ...props, vpc });

正如@fedonev 所说

The fromLookup methods are for referencing existing deployed resources.

所以你可以这样做:

  1. 您的 vpc 应该导出 ec2.Vpc
  2. Construct 不适用于您的情况,您需要从 cdk.Stack
  3. 扩展
  4. 由于您的 ecs 界面 Istack-ecs 已经期待 vpc
const app = new cdk.App();
const your_vpc = new stack-vpc(app, "Dev_VPC_CF", props);
const your_ecs = new stack-ecs(app, "Dev_ECS_CF", {
    vpc: your_vpc.vpc // As your props expects one single value
});
your_ecs.addDependency(your_vpc); // Guarantees That your `vpc` will be created firstly
app.synth();