Home > Mobile >  How to deploy Python AWS Lambda with its dependencies using Javascript AWS CDK?
How to deploy Python AWS Lambda with its dependencies using Javascript AWS CDK?

Time:11-05

I have an AWS CDK stack built using javascript. The Stack has multiple lambdas. Most of them are in javascript. I want to add one lambda in python. The python lambda works fine when I don't import external dependencies, but doesn't understand when I install them. I've tried installing the packages in a package folder or a python folder and zipping them as these articles suggested but didn't work:

https://docs.aws.amazon.com/lambda/latest/dg/python-package.html https://aws.amazon.com/premiumsupport/knowledge-center/lambda-import-module-error-python/

The error I'm getting is "Unable to import module 'py1': No module named 'x'" (x refer to any package name I'm trying to import)

My javascript CDK library code is like this:

// javascript lambda
new lambda.Function(this, 'lambda-js1', {
  functionName: `js1`,
  code: lambda.Code.fromAsset('assets/lambdajs'),
  handler: 'js1.handler',
  runtime: lambda.Runtime.NODEJS_14_X,
})

// python lambda
new lambda.Function(this, 'lambda-py1', {
  functionName: `py1`,
  code: lambda.Code.fromAsset('assets/lambdapy'),
  handler: 'py1.handler',
  runtime: lambda.Runtime.PYTHON_3_8,
})

I installed the dependency in assets/lambdapy using

pip install x
pip install --target ./package x
pip install -t python/ x

I zipped them after

My python code is in assets/lambdapy/py1.py

# not sure how to import. none of the below worked
import x
import package.x
import python.x

def handler(event, context):
    return { 
        'statusCode': 200
    }

Upon invocation of the python lambda, I get

{
  "errorMessage": "Unable to import module 'py1': No module named 'x'",
  "errorType": "Runtime.ImportModuleError",
  "stackTrace": []
}

CodePudding user response:

Create a Lambda layers for Python. Package all your dependencies in zip file and upload it to the layer created. Please refer the link for the same https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

CodePudding user response:

Use the aws-cdk.aws-lambda-python L2 construct, it installs the dependencies automatically.

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

  • Related