PYTHON | Install Module In AWS LAMBDA!

Photo by RetroSupply on Unsplash

PYTHON | Install Module In AWS LAMBDA!

Use lambda layers to install modules in your aws lambda function

Using Lambda Layers-

Concept of Lambda Layer -

  1. Lambda layers provide a convenient way to package libraries and other dependencies that you can use with your Lambda functions. Using layers reduces the size of uploaded deployment archives and makes it faster to deploy your code.

  2. A layer is a .zip file archive that can contain additional code or data. A layer can contain libraries, a custom runtime, data, or configuration files. We can attach the lambda layer to our lambda function. Today, we will make a lambda layer that will contain the modules that our code needs to perform operations.

Let's Start -

  1. Make a new folder and name it lambda_layer. In that folder, Create a text file (name it requirements.txt) and a new folder (name it python). Mention module name with or without version in this text file.

  2. open cmd in <path to lambda_layer folder> and run below command. Below command is used to install modules in a specific directory.

    •   pip install -r requirements.txt -t </path/to/python_folder>
      

  3. Now the modules mentioned in requirements.txt file will get downloaded in that python folder. The next step is to zip the python folder using tools like 7-zip or you can compress it to zip directly.

  4. This zip file is the content that we are going to upload in our lambda layer.

  5. Now, let's go to our AWS console to create a lambda layer. Go to Lambda functions and click on layers.

  6. Give basic configuration to your layer and upload the zip file that we created and create the layer.

  7. Now, let's attach this layer to our lambda. Open your lambda function in console and scroll down below to add a layer.

  8. Choose custom layers and select your created layer.

  9. Now, let's write some code using module that we installed in our lambda to test whether the module is recognized or not.

  10. We are able to use the requests module.

Resource - docs.aws.amazon.com/lambda/latest/dg/config..

Another way of using AWS Lambda involves zipping the modules directly with your lambda project in local and uploading that zip file in lambda function. In this method we don't make use of lambda layers. I will write about this way in coming blogs.
Stay Tuned...