A short tutorial to master CDK Basics in minutes.
The AWS Cloud Development Kit (CDK) is a powerful framework for defining cloud infrastructure in code. CDK supports widely used languages like JavaScript, TypeScript, Python, Java, C#, and Go. With CDK, you can leverage the familiarity and expressiveness of programming languages to build, manage, and deploy your AWS resources efficiently.
This tutorial will guide you through the essential steps to get started with AWS CDK on a Windows machine and will use CDK with Python.
Step 1: Install Prerequisites
Before diving into AWS CDK, ensure you have the necessary tools installed on your Windows machine.
Install AWS CLI:
- Download and install the AWS CLI from the official AWS website.
- The AWS Command Line Interface (AWS CLI) is an open-source tool that enables you to interact with AWS services using commands in your command-line shell.
- After installation, verify by running:
aws --version
The output looks something like this:
Install Node.js:
- Download and install Node.js from the official Node.js website.
- Verify the installation by running:
node --version
The output looks something like this:
Install AWS CDK:
Open a command prompt and install AWS CDK globally using npm:
npm install -g aws-cdk
Verify the installation by running:
cdk --version
The output looks something like this:
Step 2: Set Up Your AWS CDK Project
Initialize Your CDK Application:
Create a new directory for your project and navigate into it:
mkdir sqs_lambda_cdk_demo cd sqs_lambda_cdk_demo
Initialize a new CDK project using Python:
cdk init sample-app --language python
You can change the language as necessary and keep in mind that the CDK project initializes only in an empty directory.
Set Up Python Environment:
Ensure you have Python installed. CDK creates a virtual environment for you. Activate the virtual environment:
source .venv/Scripts/activate
The CDK project also creates a requirements file. Install the necessary dependencies:
python -m pip install -r requirements.txt
Step 3: Configure AWS Credentials
Your AWS account needs to be associated with the CLIusing access keys. You can create access keys in aws IAMconsole. Configure your AWS CLI with the necessary credentials:
aws configure
Follow the prompts to enter your AWS Access Key, Secret Key, region, and output format.
Step 4: Bootstrap Your Environment
Run the following command to create the necessary resources for your CDK app (e.g., S3 buckets for storing assets):
cdk bootstrap
The cdk bootstrap command sets up the necessary infrastructure for deploying AWS CDK applications. It creates an S3 bucket for storing assets, an ECR repository for Docker images if needed, and IAM roles and policies for deployment permissions. Additionally, it provisions these resources within a CloudFormation stack named CDKToolkit. This setup is required before deploying CDK apps to a new AWS account or region to ensure all necessary resources are available.
Step 5: Deploy Your CDK Stack
Make Changes to Your Stack:
- Open sqs_lambda_cdk_demo/sqs_lambda_cdk_demo_stack.py and modify the resources as per your requirements.
- Note that the project generated some mock code and files based on our project folder name.
- For now, we will add a lambda function which is triggered by a SQS queue.
from constructs import Construct
from aws_cdk import (
Duration,
Stack,
aws_sqs as sqs,
aws_lambda as lambda_,
aws_lambda_event_sources as lambda_event_sources,
)
class SqsLambdaCdkDemoStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
# Create SQS queue
queue = sqs.Queue(
self, "SqsLambdaCdkDemoQueue",
visibility_timeout=Duration.seconds(300),
)
# Create Lambda function
sqs_lambda = lambda_.Function(
self,
"SQSLambda",
handler="lambda_handler.handler",
runtime=lambda_.Runtime.PYTHON_3_10,
code = lambda_.Code.from_asset("lambda"),
)
# Create event source for Lambda function
sqs_event_soure = lambda_event_sources.SqsEventSource(queue)
# Add event source to Lambda function
sqs_lambda.add_event_source(sqs_event_soure)
- This code defines an AWS Cloud Development Kit (CDK) stack in Python that integrates AWS Lambda with Amazon Simple Queue Service (SQS). The SqsLambdaCdkDemoStack class extends the CDK Stack class and sets up an SQS queue with a visibility timeout of 300 seconds. It then creates a Lambda function named "SQSLambda" using Python 3.10 runtime, specifying a handler located in the lambda_handler.handler and loading the code from a directory named "lambda". To connect the Lambda function to the SQS queue, an event source mapping is established using the SqsEventSource class, linking the queue to the Lambda function. This setup ensures that messages sent to the SQS queue trigger the Lambda function, enabling serverless processing of the queued messages.
- The lambda function is in the directory lambda with file name lambda_handler.py
def handler(event, context):
print(event)
return { "statusCode": 200, "body": "Success!!!" }
Synthesize the CloudFormation Template:
To Generate the CloudFormation template:
cdk synth
View Differences:
See what changes will be applied before deploying:
cdk diff
The output looks something like this:
Deploy the Stack:
Deploy your stack to AWS:
cdk deploy
The lambda function triggered by the SQSqueue can be seen here
Now to test it out send a message to SQS
You can see the lambda function triggered here:
Step 6: Update and Redeploy
Whenever you make changes to your CDK application, follow these steps:
- Make changes to your stack as necessary
- Synthesize the template:
cdk synth
- View differences:
cdk diff
- Deploy the updated stack:
cdk deploy
AND IT'S THAT EASY!!
Step 7: Clean Up
If you need to destroy the resources created by your CDK app, run:
cdk destroy
Now, just imagine how difficult it would have been to delete all the resources if we had to do it from the console.
Important Note
Never modify the infrastructure directly in the AWS Management Console. Always make changes through your CDK code to ensure your infrastructure remains consistent and manageable.
By following these steps, you can leverage the full power of AWS CDK to manage your AWS infrastructure efficiently and effectively.
Happy coding!
This Article was first published in Medium by my self.
Top comments (0)