---
title: "Deploy these AWS CDK Examples and Dig Deep Into Cloud Infra"
description: "In this example, learn how to leverage AWS CDK examples to provision, deploy, update, and destroy AWS resources!"
canonical: "https://adamtheautomator.com/aws-cdk-examples/"
---

# Deploy these AWS CDK Examples and Dig Deep Into Cloud Infra

> In this example, learn how to leverage AWS CDK examples to provision, deploy, update, and destroy AWS resources!

Source: https://adamtheautomator.com/aws-cdk-examples/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Deploy these AWS CDK Examples and Dig Deep Into Cloud Infra](https://adamtheautomator.com/wp-content/uploads/2022/05/Deploy-these-AWS-CDK-Examples-and-Dig-Deep-Into-Cloud-Infra.jpg)

# Deploy these AWS CDK Examples and Dig Deep Into Cloud Infra

[![](https://secure.gravatar.com/avatar/a3e6f24b6b657f0acd2615f1802513a18663dea2e04d24e1df9c1530290e9b48?s=192&d=mm&r=g)Uzma Younas](https://adamtheautomator.com/author/uzma-younas/)12 May 20228 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[AWS](/tag/aws/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Installing AWS CDK](#installing-aws-cdk)
*   [Creating Your First AWS CDK Example Application](#creating-your-first-aws-cdk-example-application)
*   [Synthesizing an AWS CloudFormation Template From the Application](#synthesizing-an-aws-cloudformation-template-from-the-application)
*   [Bootstrapping the Environment](#bootstrapping-the-environment)
*   [Updating your Application Code](#updating-your-application-code)
*   [Deploy the AWS CDK Example Application](#deploy-the-aws-cdk-example-application)
*   [Testing the AWS CDK Example Application](#testing-the-aws-cdk-example-application)
*   [Cleaning Up](#cleaning-up)
*   [Conclusion](#conclusion)

Deploying applications to the cloud, such as in AWS, can be manual or through automation tools. Suppose you are working with a basic application with only a handful of cloud resources; manual deployment could be manageable. But, as the complexity increases, manual deployment is no longer practical. In such cases, the _[AWS Cloud Development Kit (CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html)_ will be a lifesaver. In this article, you’ll learn some AWS CDK Examples.

AWS CDK is an open-source development framework for defining cloud _infrastructure as code (IaC)_. CDK allows you to code in modern programming languages like Java and Python to automate AWS infrastructure.

By following this tutorial, you’ll learn to create and deploy a basic AWS CDK app, from initializing the project to deploying the resulting AWS [CloudFormation](https://aws.amazon.com/cloudformation/) template. The app will contain one stack, which contains one resource: an [Amazon API Gateway](https://aws.amazon.com/api-gateway/) to call the [Lambda function](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html).

## Prerequisites

To follow along with this hands-on tutorial, make sure you have the following requirements.

*   An AWS account. A [free tier](https://aws.amazon.com/free/) account should suffice.
    
*   An [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) user with the [AWSCloudFormationFullAccess](https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/policies/arn%3Aaws%3Aiam%3A%3Aaws%3Apolicy%2FAWSCloudFormationFullAccess) policy attached to the account
    

Related:[Learning Identity and Access Management (IAM) AWS Through Examples](https://adamtheautomator.com/iam-aws/)

*   The [Access Key ID and Secret Access Key](https://repost.aws/knowledge-center/create-access-key) of your IAM user.
    
*   A Windows or Linux computer. This tutorial will be using a Windows 10 PC.
    
*   Your computer must have the following software to follow along.
    
    *   [Node.js](https://nodejs.org/en) (with tools), here version 16.15.0 LTS is used. According to the [AWS CDK documentation](https://docs.aws.amazon.com/cdk/v2/guide/work-with.html#work-with-prerequisites)

> _Node.js versions 13.0.0 through 13.6.0 are not compatible with the AWS CDK due to compatibility issues with its dependencies._

*   [Git](https://git-scm.com/), here the version used is 2.36.0.
    
*   The latest [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) version, here 2.6.2 is used.
    
*   [Python](https://www.python.org/downloads/) version 3.10.4 is used (3.6 minimum).
    
*   A code editor, such as [Visual Studio Code (VSCode)](https://code.visualstudio.com/), which this tutorial will use.
    

## Installing AWS CDK

AWS CDK converts the infrastructure code to a CloudFormation script before execution. AWS CDK includes a library of AWS constructors for each AWS service, such as _Amazon S3 buckets_, _Lambda functions_, _Amazon DynamoDB tables_, and so on.

The main CDK package is called `aws-cdk-lib`, which contains base classes like `Stack` and `App` used in most CDK applications.

For the guide, you will be using **Python** as the programming language to provision cloud resources using CDK. Before starting, make sure to configure your workstation with your credentials and an AWS region if you have not already done so.

1\. Open a terminal and run the below command to initiate the AWS CLI configuration.

```powershell
aws configure
```

2\. Type in your **AWS Access Key ID**, **Secret Access Key**, and **Default region name**. Do not change the **Default output format** empty.

![Configuring your AWS CLI profile](https://adamtheautomator.com/wp-content/uploads/2022/05/image-201.png)

Configuring your AWS CLI profile

3\. Type the following command to check the calling IAM user id. This role will be the one with which you will create and have complete access to your CDK app.

```powershell
aws sts get-caller-identity
```

![Confirming the AWS profile identity](https://adamtheautomator.com/wp-content/uploads/2022/05/image-200.png)

Confirming the AWS profile identity

4\. Next, install the AWS CDK CLI (`aws-cdk`)on your computer by running the Node Package Manager (`npm`) command.

```powershell
npm install -g aws-cdk
```

![Installing the AWS CDK CLI](https://adamtheautomator.com/wp-content/uploads/2022/05/image-202.png)

Installing the AWS CDK CLI

5\. Restart your terminal and confirm the AWS CDK version you installed. As of this writing, the latest CDK version is 2.23.0 (build 50444aa).

```powershell
cdk --version
```

![ Checking the CDK version](https://adamtheautomator.com/wp-content/uploads/2022/05/image-203.png)

Checking the CDK version

6\. Finally, execute the following command to install the `aws-cdk-lib` module, which contains the base classes for most CDK applications.

```powershell
python -m pip install aws-cdk-lib
```

Wait for the installation to finish.

![Installing AWS CDK](https://adamtheautomator.com/wp-content/uploads/2022/05/image-204.png)

Installing AWS CDK

## Creating Your First AWS CDK Example Application

Two core concepts of AWS CDK are _**[stacks](https://docs.aws.amazon.com/cdk/v2/guide/stacks.html)**_ and _**[constructs](https://docs.aws.amazon.com/cdk/v2/guide/constructs.html)**_. _Stacks_ are the smallest deployable unit in AWS CDK. Resources defined in a stack are assumed to be a single unit. These stacks contain constructs that encapsulate AWS resources to create a reusable cloud component.

For example, the resources can be an **`s3.Bucket`** that represents an Amazon S3 bucket or **`sqs.Queue`** that represents an Amazon SQS queue.

Now you have successfully installed AWS CDK CLI and its Python module, the next step is to create a new CDK project.

1\. Create an empty directory and invoke `cdk init` to create an AWS CDK project. You may create the project directory anywhere you have access. In this example, the directory will be on the user’s Desktop.

```powershell
# Create an empty directory for the project
mkdir cdk_py_project && cd cdk_py_project

# Create the CDK project and set Python as its language
cdk init app --language python
```

![Creating a CDK project](https://adamtheautomator.com/wp-content/uploads/2022/05/image-205.png)

Creating a CDK project

2\. The `cdk init` command created files and directory structure. The command also created a [virtual environment](https://docs.python.org/3/tutorial/venv.html) to run Python and install packages and AWS CDK core dependencies.

To activate the virtual environment, run the below command.

```powershell
.venv\\Scripts\\activate.bat
```

As you can see below, you have now entered the virtual environment. The prompt changed to have the (`.venv`) prefix.

![Activating the virtual environment](https://adamtheautomator.com/wp-content/uploads/2022/05/image-206.png)

Activating the virtual environment

3\. Next, install the CDK project requirements by running the below command and for the installation to complete.

```powershell
python -m pip install -r requirements.txt
```

![Installing the requiremen](https://adamtheautomator.com/wp-content/uploads/2022/05/image-207.png)

Installing the requirement

4\. After the installation of the requirements, list the directory contents to view the files and folders.

```powershell
dir
```

You should see a similar output as below. The folder you will be working with is `cdk_py_project`. The `app.`[`py`](http://app.py/) file instantiates the instance of the stack that you will create.

![Listing the project directory contents](https://adamtheautomator.com/wp-content/uploads/2022/05/image-208.png)

Listing the project directory contents

5\. Lastly, verify everything is working correctly by listing the stacks in your app with the following command.

```powershell
cdk list
```

At this point, you should only see one stack.

![](https://adamtheautomator.com/wp-content/uploads/2022/05/image-209.png)

### Synthesizing an AWS CloudFormation Template From the Application

You’ve finished defining the resources into the stack. Next, you’ll need to translate these resources into an AWS CloudFormation template using a process called synthesizing.

Run the below command to synthesize the CDK app into a CloudFormation template. The process may take several seconds to a few minutes complete.

```powershell
cdk synth
```

> _If your app contains more than one stack, you must specify which stack to synthesize by adding the stack name to the command. For example,`cdk synth <stack name>`._

You’ll see a similar output like the screenshot below after the command ends.

![Synthesizing an AWS CloudFormation Template](https://adamtheautomator.com/wp-content/uploads/2022/05/image-210.png)

Synthesizing an AWS CloudFormation Template

The command saves the template into a JSON document called _`<stack name>.template.json`_ under the _`cdk.out`_ directory. To confirm, list the contents of the directory like so.

```powershell
dir cdk.out
```

![Listing the template directory contents](https://adamtheautomator.com/wp-content/uploads/2022/05/image-211.png)

Listing the template directory contents

### Bootstrapping the Environment

AWS CDK requires resources to perform the deployment. Specifically, the resources CDK requires are an S3 bucket for storage and specific IAM roles to perform the deployment. The process of provisioning these initial resources is called _bootstrapping_.

The bootstrap stack, also known as _CDKToolkit_, includes all these required resources. Follow the below steps to start the bootstrap.

1\. Run the below command to install the bootstrap stack into your virtual environment and wait for the process to complete. `cdk bootstrap`

```powershell
Listing the template directory contents
```

You will see an output on the screen similar to the screenshot below.

![Bootstrapping the environment](https://adamtheautomator.com/wp-content/uploads/2022/05/image-212.png)

Bootstrapping the environment

2\. Next, run the below command to deploy the CDKToolkit to AWS.

```powershell
cdk deploy
```

The output will contain **ACCOUNT-ID**, **STACK-ID,** and **REGION** where you created the app.

![Deploying the CDK stack](https://adamtheautomator.com/wp-content/uploads/2022/05/image-213.png)

Deploying the CDK stack

3\. Now, open a web browser and navigate to the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/home). Make sure you are in the right region. You should now see the stacks you deployed.

![AWS CloudFormation console](https://adamtheautomator.com/wp-content/uploads/2022/05/image-214.png)

AWS CloudFormation console

### Updating your Application Code

You’ve deployed your AWS CDK stack, but because you haven’t added any code yet, the application doesn’t do anything. For your app to be useful, you must add your code for what you intend the app to do.

While there are many [AWS CDK examples](https://github.com/aws-samples/aws-cdk-examples) that exist that you can try, nothing beats creating your own AWS CDK example application from scratch. In this section, you will create a Lambda function that will handle the infrastructure and process the events for your application.

For simplicity, you will create a function that returns the current date and time, including the HTTP status code and HTTP headers.

1\. First, open your project directory in the code editor. This example uses Visual Studio Code as the editor. `# Open the current directory in VSCode code .`

```powershell
# Open the current directory in VSCode
code .
```

2\. Next, create a directory called _lambda_ at the root of your project. And under the _lambda_ folder, create a new file called _time\_.py_.

![Creating a new folder and file](https://adamtheautomator.com/wp-content/uploads/2022/05/image-215.png)

Creating a new folder and file

3\. Copy the function code below and paste it into the _time\_.py_ file. This code returns the current date and time. Save the file after adding the code.

```python
import json

import datetime


def handler(event, context):

    current_time = datetime.datetime.now()

    body = {

        "message": "Hello, the current date and time is " + str(current_time)

    }

    response = {

        "statusCode": 200,
        "headers": {
            'Content-Type': 'text/plain'
        },

        "body": json.dumps(body)

    }

    return response
```

4\. Now, open _cdk\_py\_project/cdk\_py\_project\_stack.py._

![Open the cdk\_py\_project\_stack.py file ](https://adamtheautomator.com/wp-content/uploads/2022/05/Untitled-2022-05-11T220736.814.png)

Open the _cdk\_py\_project\_stack.py file_

Replace the existing code with the one below. To briefly explain this code:

*   Import `aws_lambda` module as `_lambda` (note the underscore) because `lambda` is a built-in identifier in Python.
*   The function will use the Python 3.9 runtime.
*   The `time_.handler` refers to the function handler in app.py.

```python
from aws_cdk import (
    # Duration,
    Stack,
    # aws_sqs as sqs,
    aws_lambda as _lambda,
)
from constructs import Construct


class CdkPyProjectStack(Stack):

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # Defines an AWS Lambda resource
        my_lambda = _lambda.Function(
            self, 'TimeHandler',
            runtime=_lambda.Runtime.PYTHON_3_9,
            code=_lambda.Code.from_asset('lambda'),
            handler='time_.handler',
        )
```

Save the _cdk\_py\_project\_stack.py_ file after editing.

5\. Before deploying your modified application, inspect the changes by running the below command. `cdk diff`

```powershell
cdk diff
```

Based on the result below, the code will synthesize an **AWS::Lambda::Function** resource and a couple of [CloudFormation parameters](https://docs.aws.amazon.com/cdk/latest/guide/get_cfn_param.html) that the toolkit will use to propagate the location of the handler code.

![Review changes before deployment](https://adamtheautomator.com/wp-content/uploads/2022/05/image-216.png)

Review changes before deployment

### Deploy the AWS CDK Example Application

Finally, you can now deploy the application. In this example, when you deploy the application, the command uploads the _lambda_ directory from your disk directly to the bootstrap bucket.

Run the below command to deploy the AWS CDK example application.

```powershell
cdk deploy
```

Press Y to confirm the deployment.

![Deploying the application](https://adamtheautomator.com/wp-content/uploads/2022/05/image-217.png)

Deploying the application

Using your web browser, navigate to the [AWS Lambda Console](https://console.aws.amazon.com/lambda/home#/functions), and you should see the function that you created and deployed.

![Viewing the Lambda event handler function in the AWS console](https://adamtheautomator.com/wp-content/uploads/2022/05/image-218.png)

Viewing the Lambda event handler function in the AWS console

### Testing the AWS CDK Example Application

So you’ve deployed the application and confirmed its existence in the AWS console. But does it work? To find out, you must test the application by following the below steps.

1\. Click on the function name and scroll down to the **Code source** section.

2\. Click on the **Test** button drop-down arrow and click **Configure test event**.

![Select Configure test event option](https://adamtheautomator.com/wp-content/uploads/2022/05/image-219.png)

Select Configure test event option

3\. Enter _Test_ as the **Event name**, select **Amazon API Gateway AWS Proxy** from the **Event template** list, and click on the **Save** button.

![Set up required parameters](https://adamtheautomator.com/wp-content/uploads/2022/05/image-220.png)

Set up required parameters

4\. Now, click the **Test** button again and wait for the execution to complete. As you can see below, the function worked and returned the current date and time.

![Testing the AWS CDK example application](https://adamtheautomator.com/wp-content/uploads/2022/05/image-221.png)

Testing the AWS CDK example application

## Cleaning Up

If at some point, the application is no longer necessary, you may need to destroy the stack. Destroying the stack means that you’re deleting the application along with all the resources that the bootstrapping created.

To destroy the stack, run the below command—Press Y at the confirmation prompt.

![Destroying the stack](https://adamtheautomator.com/wp-content/uploads/2022/05/image-222.png)

Destroying the stack

## Conclusion

You’ve learned to wield the AWS CDK toolkit as a _weapon of mass deployment_. You’ve created and deployed an AWS CDK example application. Along with the application, the CDK toolkit also cloud-forms or provisions the resources that the application requires – eliminating efforts to create them separately.

What other [AWS](https://adamtheautomator.com/aws-powershell/) CDK examples would you be interested in trying out? Remember, you’re not limited to using Python when deploying applications with CDK!

Related:[How to Leverage AWS PowerShell Commands for Automation](https://adamtheautomator.com/aws-powershell/)

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Faws-cdk-examples%2F&text=Deploy%20these%20AWS%20CDK%20Examples%20and%20Dig%20Deep%20Into%20Cloud%20Infra)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Faws-cdk-examples%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Faws-cdk-examples%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2022/05/HMaster-Your-Data-with-AWS-Quicksight.jpg)

### [Make Data-Driven Decisions with AWS QuickSight Analytics](/aws-quicksight/)

Struggling to make sense of your data? Discover how AWS QuickSight transforms data into actionable insights for smarter decision-making.

![](https://adamtheautomator.com/wp-content/uploads/2023/11/aws-network-access-analyzer-2.jpg)

### [Getting Started with AWS Network Access Analyzer](/aws-network-access-analyzer/)

Unlock the power of AWS Network Access Analyzer. Master network security with step-by-step guidance in this tutorial today!

![](https://adamtheautomator.com/wp-content/uploads/2023/11/ngrok-remote.jpg)

### [Hosting an Ngrok Remote Web App on AWS](/ngrok-remote/)

Learn how to run the Ngrok remote web application on AWS with the FastAPI Python endpoint in Linux through this ATA Learning tutorial!

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
