TerraformでAWSLambda&APIGatewayをデプロイする方法

Terraformの公式チュートリアルをやっていきます。

前提条件

  • Terraform CLI (1.0.1+) がインストールされていること
  • AWSアカウントを持っていること
  • AWS CLI がインストールされていてアカウントの設定が完了していること

この記事では以前構築したCloud9の環境を使用します。

Terraform環境をAWS Cloud9で構築する方法

手順

このチュートリアルの最終的なコードはこちらのリポジトリにあります。

注意

この記事ではmain.tfを一部書き換えています。*1,2

main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.1.0"
    }
    archive = {
      source  = "hashicorp/archive"
      version = "~> 2.2.0"
    }
  }

  required_version = "~> 1.0"
}

provider "aws" {
  region = var.aws_region
}

resource "random_pet" "lambda_bucket_name" {
  prefix = "learn-terraform-functions"
  length = 4
}

# aws-provider4.0で破壊的変更が入ったため変更 *1
resource "aws_s3_bucket" "lambda_bucket" {
  bucket = random_pet.lambda_bucket_name.id

# acl           = "private" この行を削除
  force_destroy = true
}

# aws_s3_bucket_aclを追加
resource "aws_s3_bucket_acl" "lambda_bucket_acl" {
  bucket = aws_s3_bucket.lambda_bucket.id
  acl    = "private"
}

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)
}

resource "aws_lambda_function" "hello_world" {
  function_name = "HelloWorld"

  s3_bucket = aws_s3_bucket.lambda_bucket.id
  s3_key    = aws_s3_object.lambda_hello_world.key

  runtime = "nodejs12.x"
  handler = "hello.handler"

  source_code_hash = data.archive_file.lambda_hello_world.output_base64sha256

  role = aws_iam_role.lambda_exec.arn
}

resource "aws_cloudwatch_log_group" "hello_world" {
  name = "/aws/lambda/${aws_lambda_function.hello_world.function_name}"

  retention_in_days = 30
}

# cloud9のAWSマネージド一時認証情報では'Cloud9-'から始まる名前のみ操作を許可される *2
resource "aws_iam_role" "lambda_exec" {
  name = "Cloud9-serverless_lambda" # 先頭に'Cloud9-'を付ける

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action = "sts:AssumeRole"
      Effect = "Allow"
      Sid    = ""
      Principal = {
        Service = "lambda.amazonaws.com"
      }
      }
    ]
  })
}

resource "aws_iam_role_policy_attachment" "lambda_policy" {
  role       = aws_iam_role.lambda_exec.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

resource "aws_apigatewayv2_api" "lambda" {
  name          = "serverless_lambda_gw"
  protocol_type = "HTTP"
}

resource "aws_apigatewayv2_stage" "lambda" {
  api_id = aws_apigatewayv2_api.lambda.id

  name        = "serverless_lambda_stage"
  auto_deploy = true

  access_log_settings {
    destination_arn = aws_cloudwatch_log_group.api_gw.arn

    format = jsonencode({
      requestId               = "$context.requestId"
      sourceIp                = "$context.identity.sourceIp"
      requestTime             = "$context.requestTime"
      protocol                = "$context.protocol"
      httpMethod              = "$context.httpMethod"
      resourcePath            = "$context.resourcePath"
      routeKey                = "$context.routeKey"
      status                  = "$context.status"
      responseLength          = "$context.responseLength"
      integrationErrorMessage = "$context.integrationErrorMessage"
      }
    )
  }
}

resource "aws_apigatewayv2_integration" "hello_world" {
  api_id = aws_apigatewayv2_api.lambda.id

  integration_uri    = aws_lambda_function.hello_world.invoke_arn
  integration_type   = "AWS_PROXY"
  integration_method = "POST"
}

resource "aws_apigatewayv2_route" "hello_world" {
  api_id = aws_apigatewayv2_api.lambda.id

  route_key = "GET /hello"
  target    = "integrations/${aws_apigatewayv2_integration.hello_world.id}"
}

resource "aws_cloudwatch_log_group" "api_gw" {
  name = "/aws/api_gw/${aws_apigatewayv2_api.lambda.name}"

  retention_in_days = 30
}

resource "aws_lambda_permission" "api_gw" {
  statement_id  = "AllowExecutionFromAPIGateway"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.hello_world.function_name
  principal     = "apigateway.amazonaws.com"

  source_arn = "${aws_apigatewayv2_api.lambda.execution_arn}/*/*"
}

Terraformプロバイダーを指定

variables.tfを作成

デプロイするリージョンを入力できるようにします。指定しなかった場合は米国東部が使用されます。

bash
touch variables.tf
variables.tf
variable "aws_region" {
  description = "AWS region for all resources."

  type    = string
  default = "us-east-1"
}

main.tfを作成

プロバイダーの指定を行います。

bash
touch main.tf
main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.1.0"
    }
    archive = {
      source  = "hashicorp/archive"
      version = "~> 2.2.0"
    }
  }

  required_version = "~> 1.0"
}


provider "aws" {
  region = var.aws_region
}

Lambda関数アーカイブをS3にアップロード

Lambda関数のスクリプトを作成

HTTPで”Hello, World!”を返します。

bash
mkdir hello-world
touch hello-world/hello.js
hello-world/hello.js
module.exports.handler = async (event) => {
  console.log('Event: ', event);
  let responseMessage = 'Hello, World!';

  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      message: responseMessage,
    }),
  }
}

main.tfにS3バケット、オブジェクトを追加

バケットを作成し圧縮したスクリプトをアップロードします。

main.tf
resource "random_pet" "lambda_bucket_name" {
  prefix = "learn-terraform-functions"
  length = 4
}

resource "aws_s3_bucket" "lambda_bucket" {
  bucket = random_pet.lambda_bucket_name.id

  force_destroy = true
}

resource "aws_s3_bucket_acl" "lambda_bucket_acl" {
  bucket = aws_s3_bucket.lambda_bucket.id
  acl    = "private"
}

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を実行

bash
terraform init
terraform apply
yes

実行が完了するとS3にhello-world.zipがアップロードされます。

https://s3.console.aws.amazon.com/s3/

Lambda関数を作成

main.tfにLambda関数を追加

Lambda関数用のCloudWatchロググループとIAMロールも同時に作成します。

main.tf
resource "aws_lambda_function" "hello_world" {
  function_name = "HelloWorld"

  s3_bucket = aws_s3_bucket.lambda_bucket.id
  s3_key    = aws_s3_object.lambda_hello_world.key

  runtime = "nodejs12.x"
  handler = "hello.handler"

  source_code_hash = data.archive_file.lambda_hello_world.output_base64sha256

  role = aws_iam_role.lambda_exec.arn
}

resource "aws_cloudwatch_log_group" "hello_world" {
  name = "/aws/lambda/${aws_lambda_function.hello_world.function_name}"

  retention_in_days = 30
}

resource "aws_iam_role" "lambda_exec" {
  name = "serverless_lambda"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action = "sts:AssumeRole"
      Effect = "Allow"
      Sid    = ""
      Principal = {
        Service = "lambda.amazonaws.com"
      }
      }
    ]
  })
}

resource "aws_iam_role_policy_attachment" "lambda_policy" {
  role       = aws_iam_role.lambda_exec.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

outputs.tfを作成

Lambda関数の名前を出力するようにします。

bash
touch outputs.tf
outputs.tf
output "function_name" {
  description = "Name of the Lambda function."

  value = aws_lambda_function.hello_world.function_name
}

Terraformを実行

bash
terraform apply
yes

実行が完了するとLambda関数が作成されます

https://us-east-1.console.aws.amazon.com/lambda/home?region=us-east-1#/functions

AWS CLIからLambda関数を呼び出す

Lambda関数を呼び出して結果をresponse.jsonに保存します。

bash
aws lambda invoke --region=us-east-1 --function-name=$(terraform output -raw function_name) response.json
出力
{
    "StatusCode": 200,
    "ExecutedVersion": "$LATEST"
}

response.jsonを表示します。

bash
 cat response.json
出力
{"statusCode":200,"headers":{"Content-Type":"application/json"},"body":"{\"message\":\"Hello, World!\"}"}

APIGatewayを使用してHTTP APIを作成

main.tfにAPIGatewayを追加

APIGateway用のCloudWatchロググループも同時に作成します。

main.tf
resource "aws_apigatewayv2_api" "lambda" {
  name          = "serverless_lambda_gw"
  protocol_type = "HTTP"
}

resource "aws_apigatewayv2_stage" "lambda" {
  api_id = aws_apigatewayv2_api.lambda.id

  name        = "serverless_lambda_stage"
  auto_deploy = true

  access_log_settings {
    destination_arn = aws_cloudwatch_log_group.api_gw.arn

    format = jsonencode({
      requestId               = "$context.requestId"
      sourceIp                = "$context.identity.sourceIp"
      requestTime             = "$context.requestTime"
      protocol                = "$context.protocol"
      httpMethod              = "$context.httpMethod"
      resourcePath            = "$context.resourcePath"
      routeKey                = "$context.routeKey"
      status                  = "$context.status"
      responseLength          = "$context.responseLength"
      integrationErrorMessage = "$context.integrationErrorMessage"
      }
    )
  }
}

resource "aws_apigatewayv2_integration" "hello_world" {
  api_id = aws_apigatewayv2_api.lambda.id

  integration_uri    = aws_lambda_function.hello_world.invoke_arn
  integration_type   = "AWS_PROXY"
  integration_method = "POST"
}

resource "aws_apigatewayv2_route" "hello_world" {
  api_id = aws_apigatewayv2_api.lambda.id

  route_key = "GET /hello"
  target    = "integrations/${aws_apigatewayv2_integration.hello_world.id}"
}

resource "aws_cloudwatch_log_group" "api_gw" {
  name = "/aws/api_gw/${aws_apigatewayv2_api.lambda.name}"

  retention_in_days = 30
}

resource "aws_lambda_permission" "api_gw" {
  statement_id  = "AllowExecutionFromAPIGateway"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.hello_world.function_name
  principal     = "apigateway.amazonaws.com"

  source_arn = "${aws_apigatewayv2_api.lambda.execution_arn}/*/*"
}

outputs.tfにAPIのURLを追加

outputs.tf
output "base_url" {
  description = "Base URL for API Gateway stage."

  value = aws_apigatewayv2_stage.lambda.invoke_url
}

Terraformを実行

bash
terraform apply
yes

実行が完了するとAPIGatewayが作成されます。

https://us-east-1.console.aws.amazon.com/apigateway/main/apis?region=us-east-1

cURLでAPIを呼び出す

HTTPリクエストを送ります。

bash
curl "$(terraform output -raw base_url)/hello"
出力
{"message":"Hello, World!"}

Lambda関数を更新

スクリプトを更新

クエリパラメータのNameを返すように変更します。

hello-world/hello.js
module.exports.handler = async (event) => {
  console.log('Event: ', event)
  let responseMessage = 'Hello, World!';

  if (event.queryStringParameters && event.queryStringParameters['Name']) {
    responseMessage = 'Hello, ' + event.queryStringParameters['Name'] + '!';
  }

  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      message: responseMessage,
    }),
  }
}

Terraformを実行

bash
terraform apply
yes

cURLでAPIを呼び出す

再度HTTPリクエストを送り、変更が反映されているか検証します。

bash
curl "$(terraform output -raw base_url)/hello?Name=Terraform"
出力
{"message":"Hello, Terraform!"}

クリーンアップ

Terraformで環境をクリーンアップ

bash
terraform destroy
yes

実行が完了するとS3、Lambda、APIGatewayが破棄されます。

https://s3.console.aws.amazon.com/s3/buckets
https://us-east-1.console.aws.amazon.com/lambda/home?region=us-east-1#/functions
https://us-east-1.console.aws.amazon.com/apigateway/main/apis?region=us-east-1

参考

*1, https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/version-4-upgrade#s3-bucket-refactor

*2, https://docs.aws.amazon.com/ja_jp/cloud9/latest/user-guide/security-iam.html#auth-and-access-control-temporary-managed-credentials

コメントを残す

メールアドレスが公開されることはありません。