How To Setup AWS CDK With Python

Introduction

How To Setup AWS CDK With Python
How To Setup AWS CDK With Python

We will cover How To Setup AWS CDK With Python.

Did you know that AWS CDK is a programmers dream into DevOps? Read on…

I will break this review in the following sections:

  • Why to use CDK and to whom it may appeal
  • Walk through step by step on how to setup AWS CDK with Python

I have been using these setup instructions successfully in both Mac and Linux.

Going to keep things simple and straight to the point on how to get up and running in less than 3 minutes.

What Is AWS CDK And Why To Use It

AWS CDK is a toolkit made by Amazon AWS to offer a way to programmatically create resources in the AWS cloud infrastructure. Let me elaborate this toolkit is an alternative to existing methods and follows more of a programmers door step into DevOps.

AWS CDK vs Terraform

If you are a coder that has been used into writing programs to deploy your resources AWS CDK is for you. If you however don’t want to get into programming and you are more into DevOps then Terraform is for you.

More specifically AWS CDK is a programmatic way of creating resources on the AWS cloud infrastructure whereas Terraform is more of a descriptive way of accomplishing the same task.

While both methods work and each person may have a preference each has it’s own advantages and disadvantages.

When To Use AWS CDK

  • If you find yourself in a smaller team that doesn’t have a dedicated DevOps resource or doesn’t have the budget for one and you understand some basics of the AWS services then AWS CDK might be a great solution for your team as any programmer can leverage it and perform a setup.
  • Another great reason to use it is if you want to do a lot of conditional stuff that requires programming logic in order to deploy certain resources, as it can be abstracted in languages such as Python and Javascript.
  • Easier to deploy

When To Use Terraform

  • When you know your infrastructure model and you want to simply describe and deploy
  • If you have a dedicated DevOps resource in your team and doesn’t have any programming background
  • If your logic is simple for your resources and doesn’t have a lot of edge cases
  • If you are trying to deploy a lot of resources together in one go
  • Easier to maintain and simpler if you have a lot of things cascaded

How To Setup AWS CDK With Python

Setup PIP and Virtualenv

First we need to install a few Python dependencies. We will need for this PIP and Virtualenv as both will be leveraged by our AWS CDK helper tool which we will be using later on.

$ python -m ensurepip --upgrade
$ python -m pip install --upgrade pip
$ python -m pip install --upgrade virtualenv

Setup NPM

If you have this setup already in your system skip to the next section.

First we will install NPM as we will be using this to install a helper tool by AWS to get our CDK setup.

# Mac
$ brew install nodejs

# Redhat based or later version
$ yum install nodejs (version nodejs14, nodejs17)

# Ubuntu/Debina
$ apt install nodejs

Verify NodeJS Works

To verify just run the version command.

$ npm --version
8.4.1

Setup AWS-CDK

Next we need to install our helper tool from AWS for the CDK. To do this we will use npm to install it globally in our system.

$ npm install -g aws-cdk

Verify AWS-CDK works

Run the version command to make sure our AWS-CDK was successfully installed.

$ cdk --version
2.13.0 (build b0b744d)

How To Create CDK Project

Now that CDK was successfully installed we simply create our first test project to start doing things with it.

$ mkdir test_app
$ cd test_app
$ cdk init app test_app --language python
Applying project template app for python

# Welcome to your CDK Python project!
...

Please run 'python3 -m venv .venv'!
Executing Creating virtualenv...
✅ All done!

Lets see what the CDK command created for us in terms of templating.

The first thing we need to see is that it has initialized a virtualenv for us (if you haven’t installed virtualenv please check above on how to do this).

$ ls -al |grep venv
drwxr-xr-x   6 user  staff   192 Feb 22 13:06 .venv

So the first thing we need to do is activate the virtual environment.

$ source .venv/bin/activate

Now that we are inside the python virtual environment we can go ahead and install some dependencies we may need. To do this you can leverage the requirements.txt file.

Add any dependencies your project may need in the requirements.txt file and let’s get things installed.

$ pip install -r requirements.txt
.....
Installing collected packages: six, attrs, typing-extensions, python-dateutil, cattrs, publication, jsii, constructs, aws-cdk-lib
Successfully installed attrs-21.4.0 aws-cdk-lib-2.13.0 cattrs-1.10.0 constructs-10.0.69 jsii-1.54.0 publication-0.0.3 python-dateutil-2.8.2 six-1.16.0 typing-extensions-4.1.1

The CDK script pre-populated our requirements file with some dependencies such as the base aws-cdk package that has some initial functionality.

As a side note if you later on add more dependencies in your system please ensure you add them into the requirements.txt file to keep things up to date.

Verifying Python AWS CDK Works

To verify everything works we will do an import script for the AWS CDK library and we will also try to import the S3 wrapper.

>>> import aws_cdk
>>> from aws_cdk import aws_s3 as s3
>>> s3
<module 'aws_cdk.aws_s3' from '/Users/user/code/temp/test_app/.venv/lib/python3.9/site-packages/aws_cdk/aws_s3/__init__.py'>

As shown above everything works fine. We have successfully installed and setup AWS CDK for Python.

How To Initialize Your AWS CDK Stack

There’s a few things we need to do before we start deploying our headless stack and this is configuring it out on things such as:

  • Region: The default region your stack will be deployed on
  • Account: Your AWS account your CDK stack will be used to deploy

To do this the CDK tool has pre-created a Python file called app.py which contains these details in the __init__ function to keep things clean.

import os

import aws_cdk as cdk

from test_app.test_app_stack import TestAppStack

app = cdk.App()
TestAppStack(app, "TestAppStack",
    # If you don't specify 'env', this stack will be environment-agnostic.
    # Account/Region-dependent features and context lookups will not work,
    # but a single synthesized template can be deployed anywhere.

    # Uncomment the next line to specialize this stack for the AWS Account
    # and Region that are implied by the current CLI configuration.

    #env=cdk.Environment(account=os.getenv('CDK_DEFAULT_ACCOUNT'), region=os.getenv('CDK_DEFAULT_REGION')),

    # Uncomment the next line if you know exactly what Account and Region you
    # want to deploy the stack to. */

    #env=cdk.Environment(account='123456789012', region='us-east-1'),

    # For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html
    )

app.synth()

If you see the lines above the account and the region is passed on your Environment function, feel in the attributes with the information you have in your AWS account role.

How To Synthesizing and Deploying Your AWS CDK Stack

AWS offers a really nice built in way to do things organized in Stacks. A stack is basically a set of AWS resources which you can use and manipulate programmatically using your CDK.

In order to do this you simply need to run:

$ cdk synth TestAppStack
$ cdk deploy TestAppStack

The above commands will basically let you synthesize and then deploy a stack named TestAppStack.

Conclusion

We were able to successfully show you How To Setup AWS CDK With Python and how that compares to Terraform.

If you found this useful and you think it may have helped you please drop me a cheer below I would appreciate it.

If you have any questions, comments please post them below or send me a note on my twitter. I check periodically and try to answer them in the priority they come in. Also if you have any corrections please do let me know and I’ll update the article with new updates or mistakes I did.

Do you like Terraform or AWS CDK better?

Since I’m a programmer I like to use AWS CDK, however there are times where I need to do a lot of resource allocation coupling in a very straight forward descriptive way and then I use Terraform for the job.

If you would like to find more DevOps and to setup specific AWS resources please check the articles below:

1 thought on “How To Setup AWS CDK With Python”

Leave a Comment

Your email address will not be published. Required fields are marked *