Raymond Chenon
Raymond Chenon

Reputation: 12682

AWS CDK python bundle with dependencies in requirements.txt

I have been playing with the simple examples in https://github.com/aws-samples/aws-cdk-examples/tree/master/python , all projects starting by lambda-*

However, I haven't seen one example where the aws-lambda handler imports libraries. These libraries are defined in requirements.txt

  1. how can AWS lambda imports their own requirements.txt
  2. if the dependencies cannot be imported. I package them into .zip file .

However the existing methods don't take a .zip . See this proposal https://github.com/aws/aws-cdk/issues/6294

The project structure is like this:

project/

|
|-- lambda/
|-- lambda/handler.py
|-- lambda/module1.py
|-- lambda/module2.py
|-- lambda/requirements.txt
|
|-- stack/ias_stack.py # define the Infrastructure as code
|
|-- app.py # call "ias_stack" module
| 
|-- requirements.txt

I want to deploy tht code + dependencies inside the folder "lambda/"

How can you import dependencies in your Python AWS-Lambda using CDK ?

This must be possible. I've already packaged a JVM code base into .zip . Terraform pushes this .zip into the AWS lambda.

Searching

After search , I am not the only one facing the issue How to install external modules in a Python Lambda Function created by AWS CDK?

I solved by creating a Lambda Layer. I will post an all inclusive solution.

Upvotes: 5

Views: 5795

Answers (1)

gshpychka
gshpychka

Reputation: 11522

The aws-cdk.aws-lambda-python L2 construct exist specifically for this.

Here's the documentation:

https://docs.aws.amazon.com/cdk/api/latest/docs/aws-lambda-python-readme.html

Typescript example form the docs above:

import * as lambda from "@aws-cdk/aws-lambda";
import { PythonFunction } from "@aws-cdk/aws-lambda-python";

new PythonFunction(this, 'MyFunction', {
  entry: '/path/to/my/function', // required
  index: 'my_index.py', // optional, defaults to 'index.py'
  handler: 'my_exported_func', // optional, defaults to 'handler'
  runtime: lambda.Runtime.PYTHON_3_6, // optional, defaults to lambda.Runtime.PYTHON_3_7
});

It will install dependencies from a poetry file, a pipfile, or requiremenets.txt

Upvotes: 2

Related Questions