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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import apigateway = require('@aws-cdk/aws-apigateway'); import cdk = require('@aws-cdk/core'); import fs = require('fs') import s3deployment = require('@aws-cdk/aws-s3-deployment'); export class MyStack extends cdk.Stack { const restApi = new apigateway.RestApi(this, ..); fs.writeFile('src/app-config.json', JSON.stringify({ "api": restApi.deploymentStage.urlForPath('/myResource') })) // TODO locally run 'npm run build', create 'build' folder incl rest api config const websiteBucket = new s3.Bucket(this, ..) new s3deployment.BucketDeployment(this, .. { sources: [s3deployment.Source.asset('build')], destinationBucket: websiteBucket }) } |
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.