How to write CDK Outputs to a File

avatar

Borislav Hadzhiev

Tue Apr 12 20222 min read

Updated - Tue Apr 12 2022

CDK Outputs - Introduction #

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).

Writing CDK Outputs to a File #

In order to write CDK Outputs to a file we have to:

  1. Use the CfnOutput construct to define the outputs
  2. Use the --outputs-file flag when issuing the cdk deploy command to write the output values to a file
The code for this article is available on GitHub

Here is a simple example of a CDK stack that provisions an Output with the value of the region from the current CDK environment.

lib/cdk-starter-stack.ts
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}); } }
If you still use CDK version 1, switch to the cdk-v1 branch in the GitHub repository.

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:

shell
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-outputs.json
{ "cdk-stack": { "region": "us-east-1" } }
The code for this article is available on GitHub

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.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.