.zip ファイルアーカイブを使用して PowerShell Lambda 関数をデプロイする - AWS Lambda

.zip ファイルアーカイブを使用して PowerShell Lambda 関数をデプロイする

PowerShell ランタイムのデプロイパッケージには、 PowerShell スクリプト、 PowerShell スクリプトに必要な PowerShell モジュール、 PowerShell Core をホストするために必要なアセンブリが含まれています。

Lambda 関数の作成

Lambda で PowerShell スクリプトの記述と呼び出しを開始するには、 New-AWSPowerShellLambda コマンドレットを使用して、テンプレートに基づいてスタータースクリプトを作成します。Lambda にスクリプトをデプロイするには、Publish-AWSPowerShellLambda コマンドレットを使用します。その後、コマンドラインあるいは 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 CloudWatch Logs にどのように送信されるかを確認するには、サンプルスクリプトの Write-Host行のコメントを解除します。

    Lambda 関数からデータを返す方法を示すには、スクリプトの末尾に新しい行 ($PSVersionTable) を追加します。これにより、 が PowerShell パイプライン$PSVersionTableに追加されます。 PowerShell スクリプトが完了すると、 PowerShell パイプラインの最後のオブジェクトは Lambda 関数の戻りデータです。 $PSVersionTable は、実行中の環境に関する情報も提供する PowerShell グローバル変数です。

    上述の変更を行った後のサンプルスクリプトの最後の 2 行は次のようになります。

    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