AWS Summit2016のday2のdevcon2発目のTim Wagner氏のセッションにて、CloudFormationによるLambdaのデプロイのデモが行われました。
その際にCloudFormationのTemplateJSONにlambdaで動かしたいコードがハードコーディングされており、twitter上でマジ?となっていた人がいた気がするので、そうじゃない版の方法を共有したいと思います。
S3にzip形式で圧縮したソースコード(今回はpython)をアップロードしておいて、そいつをTemplateで指定してdeployします。
1. S3へのコードのアップロード
まず、zip形式に圧縮したpythonコードを適当にS3にアップロードします。
今回はAWSのhelloworldのサンプルを使います
code
from __future__ import print_function
import json
print('Loading function')
def lambda_handler(event, context):
#print("Received event: " + json.dumps(event, indent=2))
print("value1 = " + event['key1'])
print("value2 = " + event['key2'])
print("value3 = " + event['key3'])
return event['key1'] # Echo back the first key value
#raise Exception('Something went wrong')
2. Templateの作成
JSONで下記のようにテンプレートを作成します。
注目していただきたいのはCodeの値です。
S3のbucket名とkey名を指定してdeployするコードを指定することができます。
これでJSONにコードを直書きする生活とおさらばできます!
Roleのところは適当にlambda関数を実行する際に使いたいロールを設定してください。
python以外の言語が良ければRuntimeをそれに合わせて変えてください。
なお、RuntimeはEnumなので、決まった値じゃないとcloudformation実行時に失敗します。
これを使ってCloudFormationでStackを作成してください。
template
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Description" : "sample of cloudformation template for deploying a lambda function form S3.",
"Resources" : {
"HelloSample": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Handler": "コードのファイル名.ハンドラ名",
"Role": { "Fn::GetAtt" : ["LambdaExecutionRole", "Arn"] },
"Code": {
"S3Bucket": "コードが置いてあるS3のバケット名",
"S3Key": "zip形式に圧縮してアップロードしたコードのファイル名"
},
"Runtime": "python2.7",
"Timeout": "25"
}
},
"LambdaExecutionRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [{ "Effect": "Allow", "Principal": {"Service": ["lambda.amazonaws.com"]}, "Action": ["sts:AssumeRole"] }]
}
}
}
}
}
以上です