How to Generate a CloudFormation Template in AWS CDK


Borislav Hadzhiev

Sat Apr 24 20212 min read


Photo by Maria Camargo

Updated on Sat Apr 24 2021

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/aws-s3'; import * as cdk from '@aws-cdk/core'; 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've defined our CDK stack and used the Bucket construct to create a bucket resource

  2. We've 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 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 #

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