如何針對 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 年前