如何使aws lambda函数复制与另一个相同

时间:2018-05-24 13:22:00

标签: amazon-web-services aws-lambda

我有api网关触发器的aws lambda函数。我想用相同的触发器创建相同的lambda函数。我该怎么做?虽然创建版本我看到api网关没有复制,也无法更改代码。

我是AWS lambda的新手

3 个答案:

答案 0 :(得分:3)

在编辑lambda函数时,您可以转到“动作”>“导出函数”>“下载部署包”。

enter image description here

这将下载该功能的.zip文件。

然后创建一个新的Lambda,然后执行“操作”(在代码编辑器的上方,与第一个“操作”按钮不同)>上载.zip文件

Upload a .zip file

这将复制代码和npm模块,等等。不过不是该函数的触发器或权限。

答案 1 :(得分:2)

没有提供复制/克隆Lambda函数和API网关配置的函数。您需要从头开始创建一个新功能。

如果您希望将来必须复制函数,则使用AWS CloudFormation创建Lambda函数可能是值得的。然后,您可以在以后轻松部署更多。

答案 2 :(得分:2)

使用Lambda函数复制其他函数

不幸的是,AWS Web控制台和命令行工具都没有 功能来复制服务中的功能。

这是一个明显的疏忽,使看似简单的工作变得困难 事情,例如从“模板”函数创建新函数或重命名 功能(也无法直接实现),方法是使用 名称不同。

我发现完成这项工作的最简单方法是创建一个Lambda函数 重复了 other 函数。

do_duplicate_function.py Python 3函数 以下代码可以部署到Lambda或在本地运行,以在 您的AWS帐户。

要使用它,请在AWS控制台中配置测试事件,或以其他方式调用 事件数据至少包含以下功能:

{
    "SourceFunctionName": "function_name_to_copy",
    "FunctionName": "function_name_to_create"
}

SourceFunctionName是要复制的函数的名称,并且 FunctionName是要创建的函数的名称。

在功能代码本身的顶部,还有更多有关如何 使用并部署它,有关详细信息,请参见代码。

注意:我已经在this mini-post中单独编写了该文档,您也可以在其中获得do_duplicate_function.py function code file。在此处查看最新版本。我也将所有内容都放在这里,因此该答案将是完整且独立的。

"""
This is a Python 3 utility function that creates a duplicate copy of another
function in this AWS account with the same configuration settings, environment
variables, etc.

In short, this does the job that should be handled by a "Duplicate" feature
that is missing from the AWS console and CLI.


Usage in AWS
------------

To use this function, configure a test event in the AWS console or otherwise
invoke the function with event data containing at least:


    {
        "SourceFunctionName": "function_name_to_copy",
        "FunctionName": "function_name_to_create"
    }

Where `SourceFunctionName` is the name of a function to be duplicated, and
`FunctionName` is the name of the function to create.

You can override configuration settings of the new function copy by including
extra optional variables in the event data like `Description`, `Timeout`,
`MemorySize`, etc to have your provided values override the values of the
source function's configuration.

See the parameters for the boto3 `create_function()` method for details:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#Lambda.Client.create_function


Usage locally
-------------

You can run this function locally without needing to deploy it to AWS Lambda at
all provided you meet these requirements:

- run it within a python3 virtualenv with `boto3` installed
- set up an AWS profile and credentials as for the AWS CLI tool, with
  sufficient permissions to do the work.

Once you have these in place, run the function like this:

    AWS_PROFILE=your-aws-profile \
        python3 do_duplicate_function.py \
        '{"SourceFunctionName": "fn_to_copy", "FunctionName": "fn_to_create"}'


Deployment to AWS
-----------------

Deploy this function with the Python 3.8 runtime (it might work on earlier
versions of Python 3 but hasn't been tested).

This function must have sufficient permissions to fetch and create Lambda
functions and to pass copy roles to the new function. To permit this, apply
something like the following permissions policy document to the deployed
function:

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "lambda:CreateFunction",
                    "lambda:ListFunctions",
                    "lambda:GetFunction",
                    "iam:GetRole",
                    "iam:PassRole"
                ],
                "Resource": "*"
            }
        ]
    }

Author: James Murty (https://github.com/jmurty) License: MIT
"""
import os
import json
import sys

import boto3
import urllib3


def lambda_handler(event, context):
    # Optional envvar, only used to run functions locally
    aws_profile = os.environ.get("AWS_PROFILE")
    if aws_profile:
        session = boto3.Session(profile_name=aws_profile)
        lambda_client = session.client("lambda")
    else:
        lambda_client = boto3.client("lambda")

    # Fetch source function metadata
    function_data = lambda_client.get_function(
        FunctionName=event.pop("SourceFunctionName"),
        Qualifier=event.pop("SourceFunctionVersion", "$LATEST"),
    )
    function_data.pop("ResponseMetadata")

    # Download function code from temporary URL
    code_url = function_data.pop("Code")["Location"]
    http = urllib3.PoolManager()
    response = http.request("GET", code_url)
    if not 200 <= response.status < 300:
        raise Exception(f"Failed to download function code: {response}")
    function_code = response.data

    # Build metadata for new function based on original function's
    new_function_data = {
        n: v
        for n, v in function_data["Configuration"].items()
        if n in (
            "Runtime",
            "Role",
            "Handler",
            "Description",
            "Timeout",
            "MemorySize",
            "Publish",
            "Environment",
        )
    }
    # Override function metadata values with those provided in event
    new_function_data.update(event)
    # Provide function code zip data
    new_function_data["Code"] = {"ZipFile": function_code}

    # Create a new function
    return lambda_client.create_function(**new_function_data)


# Support running this function locally
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <EVENT_JSON_TEXT_OR_FILE>")
        sys.exit(1)

    # Parse event data from JSON file path, or literal JSON
    try:
        with open(sys.argv[1], "rt") as f:
            event = json.load(f)
    except Exception:
        event = json.loads(sys.argv[1])

    context = None

    print(lambda_handler(event, context))