Borislav Hadzhiev
Tue Apr 12 2022·2 min read
Photo by Mitchel Lensink
Updated - Tue Apr 12 2022
We often need to use outputs in our CDK stack and redirect the output to a file, so that we can then import some of the AWS resource identifiers in our frontend code (i.e. API Gateway URL, etc).
In order to write CDK Outputs to a file we have to:
--outputs-file
flag when issuing the cdk deploy
command to write
the output values to a fileHere is a simple example of a CDK stack that provisions an Output with the value
of the region
from the current CDK environment.
import * as cdk from 'aws-cdk-lib'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); new cdk.CfnOutput(this, 'region', {value: cdk.Stack.of(this).region}); } }
Let's redirect the outputs from the stack to a file called cdk-outputs.json
located in the root directory.
Run the npx aws-cdk deploy
command and specify the --outputs-file
flag:
npx aws-cdk deploy YOUR-STACK-NAME \ --outputs-file ./cdk-outputs.json
After running the deploy
command, the cdk-outputs.json
file will be created
in the root directory of your CDK App. The file's contents include your default
AWS region, i.e.:
{ "cdk-stack": { "region": "us-east-1" } }
The best way to keep our AWS resource identifiers in sync between the frontend and backend is to redirect our CDK outputs to a file, which can be directly imported and read from the frontend.