Photo by La-Rel Easter on Unsplash
AWS CDK Stack
Code example on how to create an AWS CDK Stack in TypeScript
What is an AWS CDK Stack
A stack represents a bundle of AWS resources contained for a single deployment. AWS CDK Stacks is based upon AWS CloudFormation stacks, therefore it contains the same features and limitations. Synthesizing the AWS CDK Stack generates a CloudFormation template which can be used to deploy on AWS Cloud.
You can define any number of stacks in your AWS CDK app. Any instance of the Stack construct represents a stack and can be defined directly within the scope of the app. The following code snippet shows how to create an AWS CDK Stack scaffold which you can use as a template to define your stacks.
AWS CDK Stack example
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
export interface ExampleStackProps extends cdk.StackProps {
//insert properties you wish to expose
}
export class ExampleStack extends cdk.Stack {
constructor(scope: Construct, id: string, props: ExampleStackProps) {
super(scope, id, props);
//Insert the AWS components you wish to integrate
}
}
Explanation
A common pattern when creating a stack within your AWS CDK app is to extend the Stack base class cdk.Stack
, as shown in the example. Then you define scope, id and props (interface) that needs to be passed to the cosntructor
.
How to use an AWS CDK Stack
Install packages
Install AWS CDK and the AWS CDK v2 library in your project using yarn
yarn add aws-cdk-lib construct
yarn add -D aws-cdk
Import the Stack Class
Import the newly created stacks in your CDK App
.
import { ExampleStack } from './lib/stack-name';
Instantiate a new stack
After creating the AWS CDK stack class using the templated example above, you can instantiate a new stack in your AWS CDK app using the following code.
import * as cdk from 'aws-cdk-lib';
import { ExampleStack } from './lib/stack-name';
const app = new cdk.App();
new ExampleStack(app, 'newStack', {
//insert props which you exposed in the interface `ExampleStackProps`
});
app.synth();
Learn more about AWS CDK
If you are a beginner or just starting out with AWS CDK, then I can help you learn to set up and deploy your first AWS CDK project using the How to set up AWS CDK - complete guide
Originally posted on Towards the Cloud
If you liked this post, then you can subscribe to my newsletter