Skip to content
Advertisement

How to install external modules in a Python Lambda Function created by AWS CDK?

I’m using the Python AWS CDK in Cloud9 and I’m deploying a simple Lambda function that is supposed to send an API request to Atlassian’s API when an Object is uploaded to an S3 Bucket (also created by the CDK). Here is my code for CDK Stack:

JavaScript

The lambda function code uses the requests module which I’ve imported. However, when I check the CloudWatch Logs, and test the lambda function – I get:

Unable to import module ‘JiraFileLambda’: No module named ‘requests’

My Question is: How do I install the requests module via the Python CDK?

I’ve already looked around online and found this. But it seems to directly modify the lambda function, which would result in a Stack Drift (which I’ve been told is BAD for IaaS). I’ve also looked at the AWS CDK Docs too but didn’t find any mention of external modules/libraries (I’m doing a thorough check for it now) Does anybody know how I can work around this?

Edit: It would appear I’m not the only one looking for this.

Here’s another GitHub issue that’s been raised.

Advertisement

Answer

UPDATE:

It now appears as though there is a new type of (experimental) Lambda Function in the CDK known as the PythonFunction. The Python docs for it are here. And this includes support for adding a requirements.txt file which uses a docker container to add them to your function. See more details on that here. Specifically:

If requirements.txt or Pipfile exists at the entry path, the construct will handle installing all required modules in a Lambda compatible Docker container according to the runtime.

Original Answer:

So this is the awesome bit of code my manager wrote that we now use:

JavaScript

It’s actually part of the Stack class as a method (not inside the init). The way we have it set up here is that we have a folder called lambda_dependencies which contains a text file for every lambda function we are deploying which just has a list of dependencies, like a requirements.txt.

And to utilise this code, we include in the lambda function definition like this:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement