AWS CDK in Python - Schedule Lambda Functions
Tags: aws, tutorial, cdk, lambda
Published: 2022-06-29 05:06:32

---
title: AWS CDK in Python - Schedule Lambda Functions
published: true
description: "AWS CDK in Python - Schedule Lambda Functions"
tags: aws,tutorial,cdk,lambda
cover_image: https://d1j7zd7t38gahw.cloudfront.net/dev.to/AWS_CDK_ScheduleLambda.jpg
series: Infrastructure as Code in AWS
---

## 🗒️ Content

1. AWS CDK 101
2. CDK Installation
3. Hands-on Lab: Schedule Lambda Functions with AWS CDK in Python

---
## 1. AWS CDK 101
### 1.1. Infrastructure as Code (IaC)
Treating infrastructure in the same way as developers treat code is one of the most fundamental principles of DevOps.

> **Infrastructure as code (IaC)** means provisioning, configuring and managing your infrastructure resources using code and templates. 

### 1.2. AWS CDK
CloudFormation templates are used to define our application infrastructure. However, thanks to AWS CDK, the full power of a programming language can be leveraged to describe our infrastructure.

> **AWS CDK** is a framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation.

### 1.3. AWS CDK Basic Concepts
- Supported languages: TypeScript, JavaScript, Python, Java, C#/.Net and Go
- AWS CDK App: an application written in a supported language
- AWS CDK Stack: the unit of deployment in the AWS CDK, equivalent to AWS CloudFormation
- AWS CDK Constructs: the basic building blocks, represents a "cloud component"

![CDK App Structure](https://docs.aws.amazon.com/cdk/v2/guide/images/AppStacks.png) 
CDK App Structure (source: https://docs.aws.amazon.com/cdk/v2/guide/images/AppStacks.png)


## 2. CDK Installation
- Install Node.js

AWS CDK uses Node.js as its back-end regardless of the programming language you use, so `nodejs` is required.
```shell
> sudo apt install nodejs
> npm install -g aws-cdk
> cdk --version
```

- Install `virtualenv` package  

If your programming language is `Python`, using a virtual environment is recommended.
```shell
> pip install virtualenv
```

- Configure your AWS credentials  

AWS credentials also need to be configured in your local development environment, so that CDK CLI can communicate with AWS.
```shell
> aws configure
```

## 3. Hands-on Lab: Schedule Lambda Functions with AWS CDK in Python
This tutorial shows how to use AWS CDK to build our first application, which is a AWS Lambda function on a schedule ⏰.
![Schedule Lambda Functions Architecture](https://d1j7zd7t38gahw.cloudfront.net/dev.to/AWS_CDK_ScheduleLambda.jpg)

- **Step 1**: Initialize the app using the cdk init command 
```shell
> mkdir ScheduleLambda
> cd ScheduleLambda
> cdk init app --language python
...
Executing Creating virtualenv...
✅ All done!
```
Note that `cdk init` cannot be run in a non-empty directory! 

- **Step 2**: Activate the app's Python virtual environment and install dependencies
```shell
> source .venv/bin/activate
> python -m pip install -r requirements.txt
```

Only in the first time, **Bootstrapping** is required to provision resources that AWS CDK needs to perform the deployment, such as S3 bucket and IAM roles.
```shell
> cdk bootstrap aws://<your_account_id>/<your_region>
```
![CDKToolkit Stack](https://d1j7zd7t38gahw.cloudfront.net/dev.to/CDK_CDKToolkit_Stack.png)

- **Step 3**: Add file `lambda/lambda-handler.py` with the below content
```python
def handler(event, context):
    print("This is the Schedule Lambda Function's log")
    print(event['time'])
```

We can see that cdk prepares a virtual environment for us.
The structure of our application is as below.
```
├── app.py
├── cdk.json
├── lambda
│   └── lambda-handler.py
├── README.md
├── requirements-dev.txt
├── requirements.txt
├── schedule_lambda
│   ├── __init__.py
│   └── schedule_lambda_stack.py
├── source.bat
└── tests
```

- **Step 4**: Update the content of `schedule_lambda_stack.py` as the following
```python
from aws_cdk import (
    Duration, Stack,
    aws_lambda,
    aws_events,
    aws_events_targets
)
from constructs import Construct

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

        # The code that defines your stack goes here
        schedule_lambda = aws_lambda.Function(self,
            'ScheduleLambda',
            handler='lambda-handler.handler',
            runtime=aws_lambda.Runtime.PYTHON_3_9,
            code=aws_lambda.Code.from_asset('lambda'),
            timeout=Duration.seconds(300)
        )
        schedule_lambda_rule = aws_events.Rule(self,
            "ScheduleLambdaRule",
            schedule=aws_events.Schedule.rate(Duration.minutes(1))
        )
        schedule_lambda_rule.add_target(aws_events_targets.LambdaFunction(schedule_lambda))
```

- **Step 5**: Synthesize an AWS CloudFormation template
```shell
> cdk synth
```

- **Step 6**: Deploying the stack
```shell
> cdk deploy
...
Do you wish to deploy these changes (y/n)? y
...
 ✅  ScheduleLambdaStack
```

- **Step 7**: Confirm deployment in CloudFormation console
![ScheduleLambda Stack](https://d1j7zd7t38gahw.cloudfront.net/dev.to/CDK_ScheduleLambda_Stack.png)

- **Final step**: Clean your resource
```shell
> cdk destroy ScheduleLambdaStack
Are you sure you want to delete: ScheduleLambdaStack (y/n)? y
...
 ✅  ScheduleLambdaStack: destroyed
```