Borislav Hadzhiev
Last updated: Apr 13, 2022
Check out my new book
A CDK Stack is a combination of all of the constructs we have defined in our CDK application.
CDK Stacks allow us to manage all of the cloud components (constructs) we provision as a single unit.
A CDK application's entry point is the CDK App, which can consist of one or more CDK Stacks, where the CDK Stacks are made up of all of our constructs.
Let's look at an example CDK application that demonstrates all of the moving parts:
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; import * as cdk from 'aws-cdk-lib'; // define our Stack 👇 export class MyCdkStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // create a Dynamodb table using the Table construct const table = new dynamodb.Table(this, 'my-table', { billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, removalPolicy: cdk.RemovalPolicy.DESTROY, partitionKey: {name: 'date', type: dynamodb.AttributeType.STRING}, }); } } // create our App const app = new cdk.App(); // create our DEV stack 👇 new MyCdkStack(app, `my-cdk-stack-dev`, { stackName: `my-cdk-stack-dev`, env: {region: process.env.CDK_DEFAULT_REGION}, tags: {env: 'dev'}, }); // create our PROD stack 👇 new MyCdkStack(app, `my-cdk-stack-prod`, { stackName: `my-cdk-stack-prod`, env: {region: process.env.CDK_DEFAULT_REGION}, tags: {env: 'prod'}, });
This CDK application consists of 2 CDK Stacks - one for our development environment and one for our production environment.
Within the CDK Stack we have used the dynamodb construct to provision a dynamodb table.
We can deploy our cdk stacks by issuing aws-cdk deploy command:
npx aws-cdk deploy \ my-cdk-stack-dev \ my-cdk-stack-prod
The CDK code we write gets compiled down to CloudFormation, so we have to inspect the stacks we provisioned using the CloudFormation console.
If we open the CloudFormation console we would see that our stacks have been created:
We can deploy
our dev
and prod
stacks separately, these are completely
independent units of deployment.
When we have multiple stacks in the same application, we have to specify the name of the stack we're interacting with when using the CDK CLI. Otherwise we get an error.
--all
.To list all of the stacks in our CDK application we can run the list command:
npx aws-cdk list
We can run the aws-cdk destroy
command to delete the stacks, we have
provisioned. Again, we have to specify the stack names:
npx aws-cdk destroy \ my-cdk-stack-dev \ my-cdk-stack-prod
CDK Stacks allow us to manage all of the cloud components (constructs) we provision as a single unit of deployment.
For real world applications we often have to provision more than one Stack in a CDK application. To be precise, we provision one Stack for each environment in our project - i.e. production, development, staging, etc.