示例:为 Amazon Lambda 函数创建 Amazon CodeCommit 触发器 - Amazon CodeCommit
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

示例:为 Amazon Lambda 函数创建 Amazon CodeCommit 触发器

您可以为仓库创建触发器,以便 CodeCommit 存储库中的事件调用 Lambda 函数。在此示例中,您将创建一个 Lambda 函数,该函数将用于将存储库克隆到亚马逊 CloudWatch 日志的 URL 返回。

创建 Lambda 函数

当您使用 Lambda 控制台创建函数时,也可以为 Lambda 函数创建 CodeCommit触发器。以下步骤包含一个示例 Lambda 函数。该示例有两种语言版本: JavaScript 和 Python。该函数返回用于将存储库克隆到 CloudWatch 日志的 URL。

使用 Lambda 蓝图创建 Lambda 函数
  1. 登录到 Amazon Web Services Management Console,然后通过以下网址打开 Amazon Lambda 控制台:https://console.aws.amazon.com/lambda/

  2. Lambda 函数页面上,选择创建函数。(如果以前未使用过 Lambda,请选择立即开始使用。)

  3. 创建函数页面上,选择从头开始创作。例如,在函数名称中,提供函数的名称MyLambdaFunctionforCodeCommit。在 Runtime (运行时) 中,选择要用于编写函数的语言,然后选择 Create function (创建函数)

  4. Configuration (配置) 选项卡中,选择 Add trigger (添加触发器)

  5. 触发器配置中,CodeCommit从服务下拉列表中进行选择。

    
                        从控制台创建存储库

    • 存储库名称中,选择要配置触发器(该触发器使用 Lambda 函数响应存储库事件)的存储库的名称。

    • 触发器名称中,输入触发器的名称(例如 MyLambdaFunctionTrigger)。

    • 事件中,选择触发 Lambda 函数的存储库事件。如果选择 All repository events,则无法选择任何其他事件。如果需要选择事件的子集,请清除 All repository events,然后从列表中选择所需的事件。例如,如果希望触发器只在用户在 Amazon CodeCommit 存储库中创建标签或分支时运行,请删除所有存储库事件,然后选择创建分支或标记

    • 如果希望将触发器应用于存储库的所有分支,请在 Branches 中选择 All branches。否则,请选择 Specific branches。默认情况下将添加存储库的默认分支。您可以保留或从列表中删除该分支。最多可从存储库分支列表中选择 10 个分支名称。

    • (可选)在自定义数据中,输入要包含在 Lambda 函数中的信息(例如,开发人员用于讨论存储库中的开发工作的 IRC 通道的名称)。该字段是一个字符串。它不能用于传递任何动态参数。

    选择添加

  6. Configuration (配置) 页面的 Function Code (函数代码) 中的 “Code entry (代码条码)”类型中,选择“Edit code inline (内联编辑代码)”。在 Runtime (运行时) 中,选择 Node.js。如果需要创建示例 Python 函数,请选择 Python

  7. Code entry type 中,选择 Edit code inline,然后使用以下两个示例之一替换 hello world 代码。

    对于 Node.js:

    import { CodeCommitClient, GetRepositoryCommand, } from "@aws-sdk/client-codecommit"; const codecommit = new CodeCommitClient({ region: "your-region" }); /** * @param {{ Records: { codecommit: { references: { ref: string }[] }, eventSourceARN: string }[]} event */ export const handler = async (event) => { // Log the updated references from the event const references = event.Records[0].codecommit.references.map( (reference) => reference.ref, ); console.log("References:", references); // Get the repository from the event and show its git clone URL const repository = event.Records[0].eventSourceARN.split(":")[5]; const params = { repositoryName: repository, }; try { const data = await codecommit.send(new GetRepositoryCommand(params)); console.log("Clone URL:", data.repositoryMetadata.cloneUrlHttp); return data.repositoryMetadata.cloneUrlHttp; } catch (error) { console.error("Error:", error); throw new Error( `Error getting repository metadata for repository ${repository}`, ); } };

    对于 Python:

    import json import boto3 codecommit = boto3.client("codecommit") def lambda_handler(event, context): # Log the updated references from the event references = { reference["ref"] for reference in event["Records"][0]["codecommit"]["references"] } print("References: " + str(references)) # Get the repository from the event and show its git clone URL repository = event["Records"][0]["eventSourceARN"].split(":")[5] try: response = codecommit.get_repository(repositoryName=repository) print("Clone URL: " + response["repositoryMetadata"]["cloneUrlHttp"]) return response["repositoryMetadata"]["cloneUrlHttp"] except Exception as e: print(e) print( "Error getting repository {}. Make sure it exists and that your repository is in the same region as this function.".format( repository ) ) raise e
  8. 权限选项卡的执行角色中,选择角色以在 IAM 控制台中打开。编辑附加的策略以为要使用触发器的存储库添加 GetRepository 权限。

在 Amazon CodeCommit 存储库中查看 Lambda 函数的触发器

创建 Lambda 函数后,可以在 Amazon CodeCommit 中查看和测试触发器。测试触发器将运行函数以响应您指定的存储库事件。

查看和测试 Lambda 函数的触发器
  1. 打开 CodeCommit 控制台,网址为 https://console.aws.amazon.com/codesuite/codecommit/home

  2. 存储库中,选择要查看其触发器的存储库。

  3. 在存储库的导航窗格中,选择设置,然后选择触发器

  4. 查看存储库的触发器列表。您应该会看到您在 Lambda 控制台中创建的触发器。从列表中选择该触发器,然后选择测试触发器。该选项将尝试使用有关您的存储库的示例数据(包括存储库的最新提交 ID)调用该函数。(如果不存在提交历史记录,则将生成由零组成的示例值。) 这可帮助您确认是否已正确配置 Amazon CodeCommit 和 Lambda 函数之间的访问。

  5. 要进一步验证触发器的功能,请生成并向配置该触发器的存储库推送一个提交。在 Lambda 控制台中该函数的监控选项卡上,您应该会看到 Lambda 函数的响应。从 “监控” 选项卡中,选择 “查看登录信息” CloudWatch。 CloudWatch 控制台将在新选项卡中打开,并显示您的函数的事件。从与您推送提交的时间相对应的列表中选择日志流。您应会看到类似以下内容的事件数据:

    START RequestId: 70afdc9a-EXAMPLE Version: $LATEST 2015-11-10T18:18:28.689Z 70afdc9a-EXAMPLE References: [ 'refs/heads/main' ] 2015-11-10T18:18:29.814Z 70afdc9a-EXAMPLE Clone URL: https://git-codecommit.us-east-2.amazonaws.com/v1/repos/MyDemoRepo END RequestId: 70afdc9a-EXAMPLE REPORT RequestId: 70afdc9a-EXAMPLE Duration: 1126.87 ms Billed Duration: 1200 ms Memory Size: 128 MB Max Memory Used: 14 MB