Terraform - AWS API Gateway - Swagger


locals {
  api_resources = {
    products = {
      parent_path = "/"
      path        = "products"
      http_method = "GET"
    },
    "products/{product_id}" = {
      parent_path = "products"
      path        = "{product_id}"
      http_method = "GET"
    },
    orders = {
      parent_path = "/"
      path        = "orders"
      http_method = "GET"
    }
  }
}

resource "aws_lambda_function" "mock_lambda" {
  filename         = "lambda_function_payload.zip"
  function_name    = "mock_lambda"
  role             = aws_iam_role.lambda_exec.arn
  handler          = "index.handler"
  source_code_hash = filebase64sha256("lambda_function_payload.zip")
  runtime          = "nodejs18.x"
}

resource "aws_iam_role" "lambda_exec" {
  name = "lambda_exec_role"

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

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

resource "aws_apigatewayv2_api" "api_gateway_api" {
  name          = "${var.application}-api-gateway-${var.environment}"
  protocol_type = "HTTP"
  description   = "API Gateway for Google Merchant Center ${var.application}"
}

resource "aws_apigatewayv2_stage" "api_gateway_stage" {
  api_id      = aws_apigatewayv2_api.api_gateway_api.id
  name        = var.environment
  auto_deploy = true
}

resource "aws_apigatewayv2_route" "routes" {
  for_each   = local.api_resources
  api_id     = aws_apigatewayv2_api.api_gateway_api.id
  route_key  = "${each.value.http_method} /${each.value.path}"
  target     = "integrations/${aws_apigatewayv2_integration.integrations[each.key].id}"
  depends_on = [aws_apigatewayv2_integration.integrations]
}

resource "aws_apigatewayv2_integration" "integrations" {
  for_each               = local.api_resources
  api_id                 = aws_apigatewayv2_api.api_gateway_api.id
  integration_type       = "AWS_PROXY"
  integration_uri        = aws_lambda_function.mock_lambda.invoke_arn
  payload_format_version = "2.0"
  depends_on             = [aws_lambda_function.mock_lambda]
}