AWS CDK: run external build command in CDK sequence?

Question:

Is it possible to run an external build command as part of a CDK stack sequence? Intention: 1) create a rest API, 2) write rest URL to config file, 3) build and deploy a React app:

Answer:

Unfortunately, it is not possible, as the necessary references are only available after deploy and therefore after you try to write the file (the file will contain cdk tokens).

I personally have solved this problem by telling cdk to output the apigateway URLs to a file and then parse it after the deploy to upload it so a S3 bucket, to do it you need:

  • deploy with the output file options, for example:
    cdk deploy -O ./cdk.out/deploy-output.json
  • In ./cdk.out/deploy-output.json you will find a JSON object with a key for each stack that produced an output (e.g. your stack that contains an API gateway)
  • manually parse that JSON to get your apigateway url
  • create your configuration file and upload it to S3 (you can do it via aws-sdk)

Of course, you have the last steps in a custom script, which means that you have to wrap your cdk deploy. I suggest to do so with a nodejs script, so that you can leverage aws-sdk to upload your file to S3 easily.

Leave a Reply