Table of Contents
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 need to be passed to the cosntructor
.
How to create 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 have a look at this article where you learn what AWS CDK is and how it can improve your development cycle.
Elevate Your AWS CDK App with Expert Review & Guidance
Unlock the full potential of your AWS CDK app with our Expert AWS CDK App Code Review Service, conveniently delivered through AWS IQ.
Gain invaluable insights, minimize risks, and set a clear path forward for your project’s success.