如何为 Lambda Python 函数创建层?

2 分钟阅读
0

我想为我的 AWS Lambda Python 函数创建层。

解决方法

以下说明可部署应用程序以创建用于调用 Lambda Python 函数的层。

  1. 打开 AWS Serverless Application Repository 控制台
  2. 在导航窗格中,选择 Available applications(可用应用程序)。
  3. 选择 Show apps that create custom IAM roles or resource policies(显示用于创建自定义 IAM 角色或资源策略的应用程序)。
  4. 在搜索窗格中,输入 python-lambda-layer-creation
  5. 选择 python-lambda-layer-creation 函数。
  6. python-lambda-layer-creation Applications settings(python-lambda-layer-creation 应用程序设置)中,选择 I acknowledge that this app creates custom IAM roles(我确认此应用程序创建了自定义 IAM 角色),然后选择 Deploy(部署)。

您可以创建层来调用您的 Lambda 函数并传递层元数据中包含的依赖项列表。

以下示例创建了包含requests(最新版本)、numpy(版本 1.20.1)和keyring(版本 >= 4.1.1)库的 Python Lambda 层。您可以使用类似于以下内容的负载调用 Lambda 函数:

{
  "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" 
  } 
}

要测试 Lambda Python 函数层,请注意 ARN。然后,使用类似于以下内容的 YAML 模板创建 AWS CloudFormation 堆栈

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: '*'

运行 Lambda Python 函数。示例响应:

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

**注意:**此 Lambda 函数使用 pip 来管理依赖项,因此 Lambda 层中包含的库存在于 Python 包索引存储库

有关为依赖项和层属性定义的层中包含的 Python 库的示例,请参阅 pip 网站上的 pip 安装

有关更多信息,请参阅创建和共享 Lambda 层


相关信息

使用 Python 构建 Lambda 函数

将层与 Lambda 函数结合使用

如何使用带有 Docker 的模拟 Lambda 环境创建 Lambda 层?

如何使用层将最新版本的适用于 JavaScript 的 AWS 开发工具包集成到 Node.js Lambda 函数中?

AWS 官方
AWS 官方已更新 1 年前