How to Generate a CloudFormation Template in AWS CDK


Borislav Hadzhiev

Thu Apr 14 20222 min read


Photo by Maria Camargo

Updated - Thu Apr 14 2022

Generating CloudFormation Templates in AWS CDK #

In order to generate a CloudFormation template in AWS CDK we have to use the cdk synth command.

The cdk synth command does a couple of things for us:

  • it runs our CDK code, so we would get notified if we had any syntax, type or cdk validation errors
  • it generates the CloudFormation equivalent of our CDK stack and stores it in the cdk.out directory
The code for this article is available on GitHub

In order to demo the process, I'll create a small cdk application that consists of a single S3 bucket:

import * as s3 from 'aws-cdk-lib/aws-s3'; import * as cdk from 'aws-cdk-lib'; export class MyCdkStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props: cdk.StackProps) { super(scope, id, props); // 👇 create our Bucket resource const s3Bucket = new s3.Bucket(this, 'avatars-bucket', { removalPolicy: cdk.RemovalPolicy.DESTROY, }); } } const app = new cdk.App(); new MyCdkStack(app, 'my-cdk-stack', { stackName: 'my-cdk-stack', env: { region: process.env.CDK_DEFAULT_REGION, account: process.env.CDK_DEFAULT_ACCOUNT, }, });

In the code snippet:

  1. We defined our CDK stack and used the Bucket construct to create a bucket resource

  2. We instantiated our CDK stack in the scope of the CDK app

In order to generate the CloudFormation template equivalent of our CDK stack, I have to run the synth command:

npx aws-cdk synth

The command outputs the complete CloudFormation equivalent of our CDK stack, in our case the S3 bucket:

synth output

If we take a look at the cdk.out directory, we can see that our CloudFormation template has been generated and is ready for deployment:

cdk out template

When we run the cdk deploy command, the CDK CLI automatically runs the cdk synth command for us and generates the CloudFormation template.

At this point we've generated the CloudFormation equivalent of our CDK stack and we're ready to deploy using the cdk deploy command.

Further Reading #

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