15 Sep, 2024 Β· 8 min read

"Getting started with AWS CDK: commands you need to know to deploy cloud resources"
Letβs dive in! β‘οΈ
Note:- Β If you are using AWS for resources and you want separate code for infrastructure management then go for AWS CDK
Cool, right ? π
npm install -g cdkcdk --versioncdk init --language python
As I am referring python, so I will install libraries using pip
pip install -r requirements.txt
cdk init --language pythoncdk bootstrap
cdk synth cdk synth <stack_name>
cdk deploy cdk deploy <stack_name> cdk deploy --allcdk diff cdk diff <stack_name>cdk ls cdk ls <stack_name>cdk destroy cdk destroy <stack_name>
CfnAn AWS CDK stack is a collection of one or more constructs that define AWS resources
Each CDK stack represents a CloudFormation stack in your CDK app
When you run cdk init, you get only one stack by default in your app, but now we will create two stacks in separate files
1# Stack 1 - s3_stack.py 2 3from aws_cdk import Stack, aws_s3 as s3 4from constructs import Construct 5 6class S3BucketStack(Stack): 7 def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: 8 super().__init__(scope, construct_id, **kwargs) 9 10 firstBucket = s3.Bucket( 11 self, 12 "FirstBucket", 13 bucket_name="first-bucket-s3", 14 versioned=True, 15 )
1# Stack 2 - lambda_stack.py 2 3from aws_cdk import Stack, aws_lambda as _lambda 4from constructs import Construct 5 6class LambdaStack(Stack): 7 def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: 8 super().__init__(scope, construct_id, **kwargs) 9 10 myLambda = _lambda.Function( 11 self, 12 "FirstLambda", 13 runtime=_lambda.Runtime.PYTHON_3_9, 14 code=_lambda.Code.from_asset("lambda"), 15 handler="hello.handler", 16 )
1# app.py 2 3#!/usr/bin/env python3 4import aws_cdk as cdk 5from cdk_practice.lambda_stack import LambdaStack 6from cdk_practice.s3_stack import S3BucketStack 7 8app = cdk.App() 9 10LambdaStack(app, "LambdaStack") 11S3BucketStack(app, "S3BucketStack") 12 13app.synth()
AWS CDK app is a collection of one or more CDK Stacks
App construct doesnβt require any initialization argument, it is only a construct that can be used as root
The App and Stack classes from the AWS Construct Library are unique constructs that provide context to your other constructs without setting up AWS resources themselves
All constructs representing AWS resources must be defined within a Stack construct, and Stack constructs must be defined within an App Construct
By default, when a CDK project is initialized, it will have only one app and one stack
1# app.py 2 3#!/usr/bin/env python3 4from aws_cdk import App 5from cdk_demo.cdk_demo_stack import CdkDemoStack 6 7app = App() 8CdkDemoStack(app, "CdkDemoStack") 9 10app.synth()
This is more than enough to get started with AWS CDK. You can learn as you code. For more details, you can always refer to the CDK documentation