How can I create a layer for my Lambda Python function?

3 minute read
0

I want to create a layer for my AWS Lambda Python function.

Resolution

The following instructions deploy an application to create a layer to invoke a Lambda Python function.

  1. Open the AWS Serverless Application Repository console.
  2. In the navigation pane, choose Available applications.
  3. Select Show apps that create custom IAM roles or resource policies.
  4. In the search pane, enter python-lambda-layer-creation.
  5. Choose the python-lambda-layer-creation function.
  6. From the python-lambda-layer-creation Applications settings, select I acknowledge that this app creates custom IAM roles, and then choose Deploy.

You can create a layer to invoke your Lambda function and pass a list of dependencies included with the layer metadata.

The following example creates Python Lambda layers containing requests (latest version), numpy (version 1.20.1), and keyring (version >= 4.1.1) libraries. You can invoke the Lambda function with a payload similar to the following:

{
  "dependencies": { 
    "requests": "latest",
    "numpy": "== 1.20.1",
    "keyring": ">= 4.1.1" 
  },
   "layer": { 
     "name": "a-sample-python-lambda-layer",
     "description": "this layer contains requests, numpy and keyring libraries",
     "compatible-runtimes": ["python3.6","python3.7","python3.8"],
     "license-info": "MIT" 
  } 
}

To test the Lambda Python function layer, note the ARN. Then, create an AWS CloudFormation stack using a YAML template similar to the following:

AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  Layer:
    Type: String
    Description: The ARN of the lambda function layer
Resources:
  LambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: |
          import json
          import requests
          import numpy as np
          def handler(event, context):
            try:
                ip = requests.get("http://checkip.amazonaws.com/")
                x = np.array([2,3,1,0])
            except requests.RequestException as e:
                raise e

            return {
                "statusCode": 200,
                "body": json.dumps({
                    "array[0]": ("%s" % str(x[0])),
                    "location": ip.text.replace("\n", "")
                }),
            }
      Handler: index.handler
      Runtime: python3.7
      MemorySize: 128
      Timeout: 30
      Layers:
        - !Ref Layer
      Role:
        Fn::GetAtt:
        - LambdaExecutionRole
        - Arn
  LambdaExecutionRole:
    Description: Allow Lambda to connect function to publish Lambda layers
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - lambda.amazonaws.com
          Action: sts:AssumeRole
      Path: /
      ManagedPolicyArns:
      - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      # Policies:
      # - PolicyName: AllowPublishLambdaLayer
      #   PolicyDocument:
      #     Version: '2012-10-17'
      #     Statement:
      #     - Effect: Allow
      #       Action: lambda:PublishLayerVersion
      #       Resource: '*'

Run the Lambda Python function. Example response:

{
  "statusCode": 200,
  "body": "{\"array[0]\": \"2\", \"location\": \"[your-outbound-ip-address]\"}"
}

Note: This Lambda function uses pip to manage dependencies so that libraries included in the Lambda layer exist in the Python package index repository.

For examples of Python libraries included in the layer defined for the dependencies and layer attributes, see pip install on the pip website.

For more information, see Creating and sharing Lambda layers.


Related information

Building Lambda functions with Python

Using layers with your Lambda function

How do I create a Lambda layer using a simulated Lambda environment with Docker?

How do I integrate the latest version of the AWS SDK for JavaScript into my Node.js Lambda function using layers?

AWS OFFICIAL
AWS OFFICIALUpdated a year ago