AWS Lambda で go1.x ランタイムが使えなくなる ので、カスタムランタイムに移行しようと思います。 ビルドのコマンドをカスタマイズしたかったので、 Make を使ってビルドできるように設定します。
公式ドキュメント
Building Lambda functions with custom runtimes in AWS SAM - AWS Serverless Application Model
Build custom runtimes required for your Lambda function.
- template.yamlの
Metadata.BuildMethod
をmakefile
にする - Makefileにビルドターゲットを
build-<function-logical-id>
という名前で作成し、ここにビルドコマンドを書く - Makefileの置いてあるディレクトリを
Properties.CodeUri
に指定し、名前はMakefile
にする
サンプル
以下のようなディレクトリ構造の Go アプリケーションを例に説明します。
.
├── cmd
│ └── hello
│ └── main.go
├── sam
│ └── template.yaml
├── go.mod
├── go.sum
├── Makefile
└── app.go
template.yamlを次のようにします。
Runtime
: Amazon Linux 2Architectures
: arm64Handler
:bootstrap
に固定
Resources:
MyLambdaFuction:
Type: AWS::Serverless::Function
Metadata:
BuildMethod: makefile
Properties:
FunctionName: my-lambda
Handler: bootstrap
CodeUri: ../
Runtime: provided.al2
Architectures: [arm64]
MemorySize: 1024
Makefileを作成します。
$(ARTIFACTS_DIR)
はアーティファクトの配置先を格納する環境変数です。{SAM実行ディレクトリ}/.aws-sam/build/MyLambdaFuction
に設定されていて、ここに bootstrap
を配置することでLambdaを実行できます。
MAKEFILE_DIR:=$(dir $(abspath $(lastword $(MAKEFILE_LIST))))
build-MyLambdaFunction:
go build -ldflags '-s -w' -trimpath -tags lambda.norpc -o $(MAKEFILE_DIR)bin/bootstrap ./src/hello
mv $(MAKEFILE_DIR)bin/bootstrap $(ARTIFACTS_DIR)/.