Scala
g8 で雛形をつくり
$ sbt new scala/scala-seed.g8
WARN: No sbt.version set in project/build.properties, base directory: /Users/hoge/Projects/aws-lambda-in-scala
[warn] Executing in batch mode.
[warn] For better performance, hit [ENTER] to switch to interactive mode, or
[warn] consider launching sbt without any commands, or explicitly passing 'shell'
[info] Set current project to aws-lambda (in build file:/Users/hoge/Projects/aws-lambda-in-scala/)
A minimal Scala project.
name [Scala Seed Project]: AWS lambda in Scala
Template applied in ./aws-lambda-in-scala
適当にコードを書く
package example
import scala.collection.JavaConverters._
import com.amazonaws.services.lambda.runtime.Context
object Lambda {
def handler(lambdaInput: Int, context: Context): java.util.List[String] = {
val logger = context.getLogger
logger.log("start lambda handler")
execute(lambdaInput)
}
def execute(input: Int): java.util.List[String] = {
List("%d".format(input)).asJava
}
}
AWS
事前準備
lambda_exec_role
という IAM ロールを事前に作成。
AWSLambdaFullAccess
と CloudWatchLogsFullAccess
のポリシーをアタッチ。
Lambda Function を登録
#!/usr/bin/env bash
export AWS_DEFAULT_PROFILE=lambdatest
AWS_ACCOUNT_ID=xxxxxxxxxxxxxx
aws lambda create-function \
--region ap-northeast-1 \
--function-name aws-lambda-in-scala \
--zip-file fileb://target/scala-2.12/aws-lambda-in-scala-assembly-0.1.0-SNAPSHOT.jar \
--role arn:aws:iam::${AWS_ACCOUNT_ID}:role/lambda_exec_role \
--handler example.Lambda::handler \
--runtime java8 \
--timeout 15 \
--memory-size 512
実行
#!/usr/bin/env bash
export AWS_DEFAULT_PROFILE=lambdatest
aws lambda invoke \
--region ap-northeast-1 \
--function-name aws-lambda-in-scala \
--payload 123 \
--invocation-type RequestResponse /tmp/lambdatest.log
確認
$ cat /tmp/lambdatest.log
["123"]
CloudWatchLogs にもログが出力されてた。