使用.zip 文件存档部署 PowerShell Lambda 函数 - AWS Lambda

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

使用.zip 文件存档部署 PowerShell Lambda 函数

PowerShell 运行时的部署包包含您的 PowerShell 脚本、脚本所需的 PowerShell 模块以及托管 PowerShell Core 所需的程序集。 PowerShell

创建 Lambda 函数

要开始使用 Lambda 编写和调用 PowerShell 脚本,您可以使用 New-AWSPowerShellLambda cmdlet 基于模板创建入门脚本。您可以使用 Publish-AWSPowerShellLambda cmdlet 将脚本部署到 Lambda。然后,您可以通过命令行或 Lambda 控制台测试您的脚本。

要创建新 PowerShell 脚本、上传脚本并对其进行测试,请执行以下操作:

  1. 要查看可用模板列表,请运行以下命令:

    PS C:\> Get-AWSPowerShellLambdaTemplate Template Description -------- ----------- Basic Bare bones script CodeCommitTrigger Script to process AWS CodeCommit Triggers ...
  2. 要基于 Basic 模板创建示例脚本,请运行以下命令:

    New-AWSPowerShellLambda -ScriptName MyFirstPSScript -Template Basic

    当前目录的新子目录中创建一个名为 MyFirstPSScript.ps1 的新文件。目录名称基于 -ScriptName 参数。您可以使用 -Directory 参数来选择其他目录。

    您可以看到新文件包含以下内容:

    # PowerShell script file to run as a Lambda function # # When executing in Lambda the following variables are predefined. # $LambdaInput - A PSObject that contains the Lambda function input data. # $LambdaContext - An Amazon.Lambda.Core.ILambdaContext object that contains information about the currently running Lambda environment. # # The last item in the PowerShell pipeline is returned as the result of the Lambda function. # # To include PowerShell modules with your Lambda function, like the AWSPowerShell.NetCore module, add a "#Requires" statement # indicating the module and version. #Requires -Modules @{ModuleName='AWSPowerShell.NetCore';ModuleVersion='3.3.618.0'} # Uncomment to send the input to CloudWatch Logs # Write-Host (ConvertTo-Json -InputObject $LambdaInput -Compress -Depth 5)
  3. 要查看 PowerShell 脚本中的日志消息是如何发送到 Amazon L CloudWatch ogs 的,请取消对示例脚本Write-Host行的注释。

    要演示如何从 Lambda 函数返回数据,请使用 $PSVersionTable 在脚本末尾添加新的一行。这会将$PSVersionTable添加到 PowerShell 管道中。 PowerShell 脚本完成后, PowerShell 管道中的最后一个对象是 Lambda 函数的返回数据。 $PSVersionTable是一个 PowerShell 全局变量,它还提供有关运行环境的信息。

    做出这些更改之后,示例脚本的最后两行如下所示:

    Write-Host (ConvertTo-Json -InputObject $LambdaInput -Compress -Depth 5) $PSVersionTable
  4. 编辑 MyFirstPSScript.ps1 文件后,将目录更改为脚本的位置。然后运行以下命令,将脚本发布到 Lambda:

    Publish-AWSPowerShellLambda -ScriptPath .\MyFirstPSScript.ps1 -Name MyFirstPSScript -Region us-east-2

    注意,-Name 参数指定 Lambda 函数名称,该名称将显示在 Lambda 控制台中。您可以使用此函数手动调用脚本。

  5. 使用 AWS Command Line Interface (AWS CLI) invoke 命令调用您的函数。

    > aws lambda invoke --function-name MyFirstPSScript out