Adam Divall

Walkthrough Guides and Other Useful Information on AWS

How to Set Up AWS CDK for Python

2024-10-02 4 min read Walkthroughs Adam Divall

In this guide, I’ll walk through setting up AWS CDK with Python, including all the required dependencies and steps, and demonstrate how to deploy a simple app that provisions an Amazon S3 bucket.

What is the AWS CDK?

The AWS Cloud Development Kit (CDK) is an open-source software development framework designed to facilitate the creation and management of cloud infrastructure using familiar programming languages. Here are several important features and concepts associated with AWS CDK.:

  • Infrastructure as Code (IaC): AWS CDK enables developers to define cloud resources using code, simplifying the management, versioning, and deployment of infrastructure in a consistent and repeatable way.
  • Multi-Language Support: CDK supports various programming languages, such as TypeScript, JavaScript, Python, Java, and C#. This versatility enables developers to work with their preferred language when creating cloud resources.
  • High-Level Abstractions: CDK offers high-level constructs that encapsulate AWS resources, enabling developers to interact with abstractions instead of managing low-level resource configurations. For instance, rather than specifying every detail of an S3 bucket, you can use a straightforward construct that streamlines the process.
  • Reusable Constructs: CDK encourages the development of reusable components, known as constructs, which can be shared across projects or within organizations. This practice fosters consistency and promotes best practices in cloud architecture.
  • Integration with AWS Services: CDK effortlessly integrates with a range of AWS services, enabling you to provision resources such as EC2 instances, Lambda functions, S3 buckets, DynamoDB tables, and more with minimal configuration.
  • Deployment Automation: CDK can automatically create CloudFormation templates from the defined infrastructure, streamlining the deployment process. You can apply changes to your stack with just one command.

Prerequisites

Before starting, ensure that the following tools are installed on your system:

  • Node.js: AWS CDK is a Node.js application, so you’ll need Node.js installed.

  • Python: AWS CDK supports Python 3.8 or later.

  • AWS CLI: The AWS Command Line Interface (CLI) is needed to interact with your AWS account.

    • Install using the instructions from AWS CLI documentation.
    • Configure it with your AWS credentials:
      aws configure
      
      You’ll be prompted for your AWS Access Key, Secret Key, region, and output format.

Install AWS CDK

To install AWS CDK globally, use npm:

npm install -g aws-cdk

Verify the installation by checking the CDK version:

cdk --version

This confirms that AWS CDK is installed successfully.

Setup a Python Virtual Environment

To isolate project dependencies, it’s recommended to create a Python virtual environment. Follow these steps:

  • Create a virtual environment in your project folder:
python -m venv .venv
  • Activate the virtual environment:
    • macOS/Linux:

      source .venv/bin/activate
      
    • Windows:

      .venv\Scripts\activate
      

Initialise a New CDK Project

Next, create a new AWS CDK project. CDK provides a convenient init command that helps bootstrap your project structure.

Navigate to your project directory and initialize a new CDK project for Python:

cdk init app --language python

This command will generate the necessary project files, including:

  • app.py: The main entry point of your CDK application.
  • cdk.json: Configuration file for your CDK project.
  • requirements.txt: File listing the Python dependencies.

Install Required Python Dependencies

After initializing the project, install the required dependencies listed in requirements.txt. Run the following command to install them:

pip install -r requirements.txt

This installs the core AWS CDK libraries and dependencies for Python.

Bootstrap the AWS Environment

CDK requires that your AWS account be bootstrapped to deploy resources. This creates the necessary infrastructure (like S3 buckets) for managing CDK deployments.

Run the following command to bootstrap your AWS environment:

cdk bootstrap aws://<Account-Number>/<Region>

Replace <Account>-Number> with your AWS account number and <Region> with the AWS region where you want to deploy.

Create your CDK Stack

Open app.py in your project directory and start defining AWS resources. For example, the following code creates an S3 bucket:

from aws_cdk import core
from aws_cdk import aws_s3 as s3

class MyStack(core.Stack):
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Define an S3 bucket
        s3.Bucket(self, "MyBucket",
                  versioned=True,
                  removal_policy=core.RemovalPolicy.DESTROY)

app = core.App()
MyFirstStack(app, "my-stack")
app.synth()

Deploy your CDK Stack

Once you’ve defined your infrastructure in the stack, deploy it to AWS using the following command:

cdk deploy

CDK will display a summary of changes and prompt for confirmation before deploying the resources.

Managing your CDK Stack

To view the resources in your stack, run:

cdk ls

To destroy the stack and remove the resources from AWS, run:

cdk destroy

Summary

We’ve just successfully set up AWS CDK for Python and configured a simple S3 bucket. We’re nowable to define and manage our AWS infrastructure using Python code. The AWS CDK simplifies infrastructure management by allowing developers to write code in familiar programming languages and manage cloud resources efficiently.