DEV Community

Cover image for AWS CDK in Python - Schedule Lambda Functions
Vinh Le
Vinh Le

Posted on • Edited on

AWS CDK in Python - Schedule Lambda Functions

🗒️ 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
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.

> sudo apt install nodejs
> npm install -g aws-cdk
> cdk --version
Enter fullscreen mode Exit fullscreen mode
  • Install virtualenv package

If your programming language is Python, using a virtual environment is recommended.

> pip install virtualenv
Enter fullscreen mode Exit fullscreen mode
  • Configure your AWS credentials

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

> aws configure
Enter fullscreen mode Exit fullscreen mode

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

  • Step 1: Initialize the app using the cdk init command
> mkdir ScheduleLambda
> cd ScheduleLambda
> cdk init app --language python
...
Executing Creating virtualenv...
✅ All done!
Enter fullscreen mode Exit fullscreen mode

Note that cdk init cannot be run in a non-empty directory!

  • Step 2: Activate the app's Python virtual environment and install dependencies
> source .venv/bin/activate
> python -m pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

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.

> cdk bootstrap aws://<your_account_id>/<your_region>
Enter fullscreen mode Exit fullscreen mode

CDKToolkit Stack

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

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
Enter fullscreen mode Exit fullscreen mode
  • Step 4: Update the content of schedule_lambda_stack.py as the following
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))
Enter fullscreen mode Exit fullscreen mode
  • Step 5: Synthesize an AWS CloudFormation template
> cdk synth
Enter fullscreen mode Exit fullscreen mode
  • Step 6: Deploying the stack
> cdk deploy
...
Do you wish to deploy these changes (y/n)? y
...
 ✅  ScheduleLambdaStack
Enter fullscreen mode Exit fullscreen mode
  • Step 7: Confirm deployment in CloudFormation console
    ScheduleLambda Stack

  • Final step: Clean your resource

> cdk destroy ScheduleLambdaStack
Are you sure you want to delete: ScheduleLambdaStack (y/n)? y
...
 ✅  ScheduleLambdaStack: destroyed
Enter fullscreen mode Exit fullscreen mode

Top comments (0)