简体   繁体   English

如何在AWS CDK中执行代码之前等待堆栈完成?

[英]How to wait stack to complete before executing code in AWS CDK?

I'm trying AWS CDK and got stuck when I tried to execute a code block that depends on the stack completion. 我正在尝试AWS CDK并在尝试执行依赖于堆栈完成的代码块时陷入困境。

Here's my current code: 这是我当前的代码:

class Application extends cdk.Construct {
    constructor(scope: cdk.Construct, id: string) {
        super(scope, id);
        const webStack = new WebsiteStack(app, `website-stack-${id}`, { stage: id })
        const buildStack = new CodeBuildStack(app, `codebuild-stack-${id}`, { stage:id, bucket: webStack.websiteBucket, distribution: webStack.websiteDistribution });
        this.generateBuildParameter(id, webStack, buildStack)
    }

    generateBuildParameter(id: string, webStack: WebsiteStack, buildStack: CodeBuildStack) {
        const buildParam = {
            projectName: buildStack.buildProject.projectName,
            sourceVersion: id,
            environmentVariablesOverride: [
              { name: "STAGE", value: id, type: "PLAINTEXT" },
              { name: "WEBSITE_BUCKET", value: webStack.websiteBucket.bucketName, type: "PLAINTEXT" },
              { name: "CLOUDFRONT_DISTRIBUTION_ID", value: webStack.websiteDistribution.distributionId, "type": "PLAINTEXT" }
            ],
            buildspecOverride: "./buildspec.yml"
        }
        fse.outputJson(`./cdk.out/build-parameters/build-${id}.json`, buildParam, (err: Error) => {
            if (err) {
                throw err
            };
            console.log(`build parameter has been created in "../cdk.out/build-parameters/build-${id}.json"`);
        })
    }
}

I'm just trying to generate a json file that depends on the buildStack . 我只是想生成一个依赖于buildStack的json文件。 However, it seems that it's not waiting for the stack to complete. 但是,似乎不是在等待堆栈完成。

Here's my current output: 这是我当前的输出:

{
   "projectName":"${Token[TOKEN.41]}",
   "sourceVersion":"master",
   "environmentVariablesOverride":[{"name":"STAGE","value":"master","type":"PLAINTEXT"},{"name":"WEBSITE_BUCKET","value":"${Token[TOKEN.17]}","type":"PLAINTEXT"},{"name":"CLOUDFRONT_DISTRIBUTION_ID","value":"${Token[TOKEN.26]}","type":"PLAINTEXT"}],
   "buildspecOverride":"./buildspec.yml"
}

Does AWS CDK support Promise or some sort to wait the stack to be completed? AWS CDK是否支持Promise或某种形式来等待堆栈完成?

If you're trying to reference 'dynamic' things like the CloudFront distribution Id that will be generated, I would probably try to have 2 different stacks, and have one depend on the other. 如果您尝试引用“动态”事物,例如将要生成的CloudFront分配ID,则我可能会尝试具有2个不同的堆栈,而其中一个依赖于另一个。

I'm not sure I understand your use case correctly. 我不确定我是否正确理解了您的用例。 But maybe check out the Core package readme that contains how to parameterize certain things and pass in information across stacks. 但是,也许请查看Core软件包自述文件,其中包含如何参数化某些内容以及如何在堆栈之间传递信息。

https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html

EDIT: you can do something like: 编辑:您可以做类似的事情:

var s1 = new stackOne();
var s2 = new stackTwo().addDependency(s1);

This blog post was helpful for me: https://lanwen.ru/posts/aws-cdk-edge-lambda/ 这篇博客文章对我很有帮助: https : //lanwen.ru/posts/aws-cdk-edge-lambda/

Edit: Some practical examples of sharing resources between stacks. 编辑:在堆栈之间共享资源的一些实际示例。 StackA creates a CloudFront distribution (The ID of the distribution is dynamic) StackA创建一个CloudFront分配(分配的ID是动态的)

StackB needs the CloudFront distribution Id to set up the alarm. StackB需要CloudFront分配ID来设置警报。

// stackA
export class CloudFrontStack extends cdk.Stack {
  readonly distribution: cf.CloudFrontWebDistribution;
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
 distribution = new cf.CloudFrontWebDistribution(this, 'my-cloud-front-dist', {//props here...} );
 }
}

// stack B
export class AlarmStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, cloudfrontDistributionId: string, props?: cdk.StackProps) {
    super(scope, id, props);   
    new alarm.Alarm()// alarm definition, need ID of CF Distribution here.
 }
}

//index.ts where everything is linked:
const app = new cdk.App();
const stack1= new CloudFrontStack(app, 'CFStack1');
const stack2= new AlarmStack(app, 'AlarmStack', stack1.distribution.distributionId);
// you can even specify that stack2 cannot be created unless stack1 succeeds.
stack2.addDependency(stack1);

EDIT2 : For using resources that have been created after a stack is built and outside of the CDK, the easiest way I can think of is to define CfnOutputs and then query the AWS api using the CLI, either manually or in the CI/CD pipeline if we're automating more things after. EDIT2 :对于使用在堆栈建立之后并在CDK之外创建的资源,我想到的最简单的方法是定义CfnOutputs,然后使用CLI手动或在CI / CD管道中查询AWS api如果之后我们要自动化更多的事情。

Example2: using the previous example we will define an output called CloudFront-DistributioId and query it using the CLI. 例2:使用上一个示例,我们将定义一个名为CloudFront-DistributioId的输出,并使用CLI对其进行查询。

// stackA
export class CloudFrontStack extends cdk.Stack {
  readonly distribution: cf.CloudFrontWebDistribution;
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
 distribution = new cf.CloudFrontWebDistribution(this, 'my-cloud-front-dist', {//props here...} );

// define a cloud formation output so we can query later  
new CfnOutput(this, 'CloudFront-DistributionId', {
  exportName: 'CloudFront-DistributionId',
  value: cloudFrontDistribution.distributionId,
  description: 'The dynamic value created by aws of our CloudFront distribution id. '
});
 }
}

After the stack is created, in the pipeline/cli, use the following command to get the value of the variable: 创建堆栈后,在管道/ cli中,使用以下命令获取变量的值:

aws cloudformation describe-stacks --stack-name CloudFrontStack --query "Stacks[0].Outputs[?OutputKey=='CloudFront-DistributionId'].OutputValue"

This will produce the Distribution ID that was created after the stack built. 这将生成在构建堆栈之后创建的分发ID。

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

相关问题 在执行下一个代码之前打字稿会等待循环完成吗? - Will typescript wait for a loop to complete before executing the next code? 如何等待一个 function 在 angular 6 执行完之后再执行下面的代码执行? - how to wait for a function to complete its execution in angular 6 before executing the following code execution? 在Angular中执行代码之前如何等待API响应 - how to wait for API response before executing code in Angular 如何在执行更多代码之前等待 observable 更新? - How do I wait for an observable to update before executing more code? AWS CDK。 如何将第一个堆栈的 `id` 传递给第二个堆栈 - AWS CDK. How to pass `id` of first stack to second stack 如何在执行下一行代码之前等待嵌套订阅中的 API 响应 - How to wait for API response in the nested subscription before executing next line of code 如何在执行代码块之前等待多个异步 http 调用返回 - How to wait for multiple async http calls to return before executing a block of code AWS CDK stack.regionalFact 不是 function - AWS CDK stack.regionalFact is not a function AWS CDK 断言 - 查看堆栈中的单个资源 - AWS CDK Assertions - Looking at Individual Resources In A Stack 无法在 CDK 应用程序中为 AWS S3 Glacier 创建 CDK 堆栈? - Cannot create CDK stack for AWS S3 Glacier in CDK app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM