AWS Lambda and API Gateway でサーバーレス application を構築する terraform tutorial をやってみた

AWS Lambda の使い方を手探りで調べていたら、Hashicorp が出している tutorial にたどり着いた。

developer.hashicorp.com

AWSの勉強はリソースが残ったときにお金がかかるのが悩みだろう。 私は普段は terraform でリソースを記載して、一日の終わりに terraform destroy するなどしている。

この方法で時にしんどいのは、触ったことがない AWS サービスを勉強する場合だ。そもそもの仕組みがわかっていない中、terraform の書き方と両方を同時に調べながら試す必要がある。

AWS Lambda は AWS Game Day などでマネコンで触ることはあれど、運用で触ったことはなかったので、デプロイの方法等はわかっていなかった。 そのため、terraform で書きつつ動作も確認して、と中々理解が進まない状況だった。

そんな中見つけた冒頭の tutorial が、ちょうど自分の状況にあっていて助かった。

以下、発見や感想をつらつら残しておく

Lambda

Lambda は関数を記載したファイルや環境を zip 化しておく必要があり、手元で zip コマンドを実行してから terraform apply を叩いていた。

実は、zip の処理は terraform のコードで表現できる(terraform が機能として提供している)らしい。tutorial で初めて知った。

data "archive_file" "lambda_hello_world" {
  type = "zip"

  source_dir  = "${path.module}/hello-world"
  output_path = "${path.module}/hello-world.zip"
}

resource "aws_s3_object" "lambda_hello_world" {
  bucket = aws_s3_bucket.lambda_bucket.id

  key    = "hello-world.zip"
  source = data.archive_file.lambda_hello_world.output_path

  etag = filemd5(data.archive_file.lambda_hello_world.output_path)
}

なお、手元では terraform init -upgrade が必要だった

terraform apply
╷
│ Error: Inconsistent dependency lock file
│ 
│ The following dependency selections recorded in the lock file are inconsistent with the current configuration:
│   - provider registry.terraform.io/hashicorp/archive: required by this configuration but no version is selected
│ 
│ To update the locked dependency selections to match a changed configuration, run:
│   terraform init -upgrade

js file に変更を加えた際に差分が反映されるか疑問だったが、hash 値の管理を忘れなければ問題ない。

source_code_hash = data.archive_file.lambda_hello_world.output_base64sha256

Lambda Function を作った後に AWS CLI で lambda の動作確認をするステップが入っているのも、tutorial の丁寧さを感じる。

API Gateway

この tutorial をやる前は、手探りで調べていたので、 api gateway には aws_api_gateway_rest_api という resource を指定していた。

tutorial では aws_apigatewayv2_api resource を指定しており、その存在から初めて知った。

aws_apigatewayv2_stage resource を作ることで API Gateway がデプロイされるらしい。これも tutorial がなければしばらく調査の海を彷徨っていたかもしれない。

終わりに

普段は serverless なシステムを作ったりしないので、知らない知識が多くて勉強になった。

tutorial のままの設計だと認証がないので、まだまだ調べる必要はある。