How to write CDK Outputs to a File


Borislav Hadzhiev

Thu Apr 22 20212 min read

Updated on Thu Apr 22 2021

In order to write our CDK outputs to a file we have to pass the `outputs-file` flag to the cdk deploy command.

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.

import * as cdk from '@aws-cdk/core';

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 cdk deploy command and specify the --outputs-file flag:

npx cdk deploy YOUR-STACK-NAME \
  --outputs-file ./cdk-outputs.json

After executing the deployment, 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 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee