繁体   English   中英

AWS CDK - 从其他堆栈访问资源

[英]AWS CDK- Access resource from other stack

假设我在一个堆栈中有一个资源,比如 stepfunction 活动。 我如何访问它在其他堆栈中的 arn?

我发现 CfnConstruct 适合导出 ( https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CfnOutput.html )。 截至目前,我已经使用 CfnConstruct 将其导出:

this.initiateValidationActivityArn = new cdk.CfnOutput(this, 'InitiateValidationActivityArn', {
      value: igvsStateMachine.initiateValidationActivity.activityArn
    });

现在我如何在其他文件中访问它。 我试过这个:

ecsService.initiateValidationActivityArn.value

但是价值是私有的,所以不能使用它。

如果您在一个可部署的 cdk-app 中拥有堆栈,则可以通过使其从外部/非私有访问来访问堆栈中的属性值。 我建议做的是将其保持为readonly状态,这样就无法从堆栈外部重新初始化它。

// file: ./lib/first-stack.ts

// import statements

export class FirstStack extends Stack {
  readonly vpc: IVpc;
  
  constructor(...) {
     // setup
     this.vpc = new Vpc(this, "VPC", {...});
  }
}

在依赖堆栈中,您可以通过(自定义)道具传递它。

// file: ./lib/second-stack.ts

export interface SecondStackProps extends StackProps {
   importedVpc: IVpc;
}

export class SecondStack extends Stack {
  constructor(scope: cdk.Construct, id: string, props: SecondStackProps) {
    super(scope, id, props);
    const importedVpc = props.importedVpc;

    // do sth. with your imported resource
  }
}

你可能会问为什么这样工作......? 它之所以有效,是因为 CDK 生成资源 ID,并且在合成阶段,它可以将资源的令牌放入生成的模板中。

当您分离了 cdk-apps/堆栈部署时,这不起作用,因为 CDK 无法在 cdk-synth 期间解析(现有的)资源 ID 令牌。 有了这个,你需要有另一种方法:

// file: ./lib/first-stack-separated-deployment.ts

// import statements

export class FirstStackSeparatedDeployment extends Stack {
  cfnVpcId: CfnOutput;
  
  constructor(...) {
     // setup
     const vpc = new Vpc(this, "VPC", {...});
     this.cfnVpcId= new cdk.CfnOutput(this, "FirstStackCfnVpcId", {
      value: vpc.vpcId,
      exportName: "UniqueNameForYourVpcId"
    });
  }
}

在需要已部署资源的另一个堆栈中,您执行以下操作:

// file: ./lib/second-stack-separated-deployment.ts
export class SecondStackSeparatedDeployment extends Stack {
  constructor(...) {
    // setup
    const vpcId = Fn.importValue("UniqueNameForYourVpcId")
    const importedVpc = ec2.Vpc.fromVpcAttributes(this, "ImportedVpc", {
      vpcId: vpcId,
      availabilityZones: [this.region],
    })

    // proceed further...
  }
}

基本上,您将exportName构造中的CfnOutput作为标识符,并通过核心Fn.importValue将其导入。 使用这种方法,已经需要部署第一个堆栈。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM