あめがえるのITブログ

頑張りすぎない。ほどほどに頑張るブログ。

TerraformでAPI GatewayとLambdaの構成を作成してみた

やること

terraformでAPI Gateway+Lambdaの構成を作成する。

構成

ブラウザ ⇒ APIGateway ⇒ Lambda(Python)

実践

1.Pythonコード作成

# vi lambda_function.py
import json

def lambda_handler(event, context):
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }
# zip lambda_function.py


2.環境構築
2-1.terraformコード作成

# vi main.tf
provider "aws" {
  region = "ap-northeast-1"
}

## Lambda関数
resource "aws_lambda_function" "example" {
  function_name = "example_lambda_function"
  runtime       = "python3.8"
  handler       = "lambda_function.lambda_handler"

  filename = "lambda_function.zip"

  role = aws_iam_role.lambda_exec.arn
}

## Lambdaロール
resource "aws_iam_role" "lambda_exec" {
  name = "lambda_exec_role"

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

## APIGateway
resource "aws_api_gateway_rest_api" "example" {
  name        = "ExampleAPI"
  description = "Example API"
}

resource "aws_api_gateway_resource" "example" {
  rest_api_id = aws_api_gateway_rest_api.example.id
  parent_id   = aws_api_gateway_rest_api.example.root_resource_id
  path_part   = "examplepath"
}

resource "aws_api_gateway_method" "example" {
  rest_api_id   = aws_api_gateway_rest_api.example.id
  resource_id   = aws_api_gateway_resource.example.id
  http_method   = "GET"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "example" {
  rest_api_id = aws_api_gateway_rest_api.example.id
  resource_id = aws_api_gateway_resource.example.id
  http_method = aws_api_gateway_method.example.http_method

  integration_http_method = "POST"
  type                    = "AWS_PROXY"
  uri                     = aws_lambda_function.example.invoke_arn
}

resource "aws_api_gateway_deployment" "example" {
  depends_on = [aws_api_gateway_integration.example]

  rest_api_id = aws_api_gateway_rest_api.example.id
  stage_name  = "test"
}

resource "aws_lambda_permission" "api_gateway" {
  statement_id  = "AllowAPIGatewayInvoke"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.example.function_name
  principal     = "apigateway.amazonaws.com"

  source_arn = "${aws_api_gateway_rest_api.example.execution_arn}/*/*/*"
}

2-2.terraform実行

# terraform plan
# terraform apply


3.動作確認
3-1.接続URL確認
[API Gateway] - 作成されたAPIを押下

[ステージ]を押下

[test]横の+を展開

[GET]を押下し、[URLを呼び出す]のURLを確認


3-2.接続確認
ブラウザでアクセスし、[Hello from Lambda!]が表示されることを確認

ついでにCurlコマンドでも確認

# curl https://bw9jnqmaxa.execute-api.ap-northeast-1.amazonaws.com/test/examplepath
StatusCode        : 200
StatusDescription : OK
Content           : "Hello from Lambda!"
RawContent        : HTTP/1.1 200 OK
                    Connection: keep-alive
                    x-amzn-RequestId: 2553b9b7-6d98-4e54-a1db-fddd38eaf553
                    x-amz-apigw-id: NgMdaE4ktjMEIyw=
                    X-Amzn-Trace-Id: Root=1-653cc122-611f384b1e9780c6624df265;Sample 
                    d=0;l...
Forms             : {}
Headers           : {[Connection, keep-alive], [x-amzn-RequestId, 2553b9b7-6d98-4e54 
                    -a1db-fddd38eaf553], [x-amz-apigw-id, NgMdaE4ktjMEIyw=], [X-Amzn 
                    -Trace-Id, Root=1-653cc122-611f384b1e9780c6624df265;Sampled=0;li 
                    neage=f3c5689d:0]...}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 20



感想

terraformは扱いやすくてよいねー(´Д`)