PowerShellでLambdaを実装しよう!~コードの準備からデプロイまで~

記事タイトルとURLをコピーする

技術4課のPowerShellおじさんこと、鎌田です。 先のブログで、PowerShellでLambdaを実装するための準備をしました。さあいよいよ、実装していきましょう。

1.実装の基礎知識

PowerShell Lambdaを実装する時は、専用コマンドでテンプレートからスターターコードを作成し、テンプレート中にあるファイルを編集して、実装します。 テンプレートは以下のコマンドで種類を確認できます。

Get-AWSPowerShellLambdaTemplate

いくつかありますが、Basicでまずは実装に慣れると良いでしょう。

2.テンプレートからスターターコードを生成する

まずは、テンプレートからスターターとなるコードを生成します。

New-AWSPowerShellLambda -ScriptName <スクリプト名> -Template Basic
例) New-AWSPowerShellLambda -ScriptName test -Template Basic

こちらで、testフォルダが作られ、test.ps1とreadme.txtが入っています。

PowerShellのファイル名は、コマンドで指定したScriptNameが使われます。 このPowerShellファイルにコードを追加します。

3.実装

ファイルを開くと、次のようになっています。Requires以下に、実装をしていきましょう。

ここは基本の、"Hello World"を実装してみます。 Write-Hostで、Cloud Watch Logsに文字を出力できます。

出来上がったコードはこちら。

# PowerShell script file to be executed as a AWS Lambda function. 
# 
# When executing in Lambda the following variables will be 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 will be 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.335.0'}

# Uncomment to send the input event to CloudWatch Logs
# Write-Host (ConvertTo-Json -InputObject $LambdaInput -Compress -Depth 5)

Write-Host "Hello World!"

4Lambdaへデプロイしてみる

コードが書けたらデプロイです。 PowerShell6を起動し、New-AWSPowerShellLambdaのコマンドで生成したフォルダに移動した上で、次のコマンドを実行します。

Publish-AWSPowerShellLambda -ScriptPath .\<スクリプト名>.ps1 -Name <スクリプト名> -Region ap-northeast-1
例) Publish-AWSPowerShellLambda -ScriptPath .\test.ps1 -Name test -Region ap-northeast-1

初回デプロイ時は、付与するroleをどうするか選択することになりますので、roleをあらかじめ作っておくことをお勧めします。

5.テスト実行してみよう

デプロイできたら、マネージメントコンソールでLambdaの画面にアクセスしてみましょう。 PowerShellのコードが、ばっちりデプロイされています!

普通にテストもできます。テストイベントを作って実行してみると・・・! お、ありました、HelloWorld!

まとめ

みなさま、LambdaのPowerShell実装、いかがでしたでしょうか。 PowerShellでもLambdaを実装したかった皆様には嬉しい!?アップデートですね。

せっかくなので、私はSlack Botを実装してみました。 次回はそのネタをお送りしたいと思います!