main.tf 2.77 KB
# 创建 REST API Gateway
resource "aws_api_gateway_rest_api" "user_management" {
  name        = var.api_name
  description = "API Gateway for Spring Boot User Management Application"

  endpoint_configuration {
    types = ["REGIONAL"]
  }
}

# 创建代理资源,捕获所有路径
resource "aws_api_gateway_resource" "proxy" {
  rest_api_id = aws_api_gateway_rest_api.user_management.id
  parent_id   = aws_api_gateway_rest_api.user_management.root_resource_id
  path_part   = "{proxy+}"
}

# 为代理资源创建 ANY 方法(捕获所有HTTP方法)
resource "aws_api_gateway_method" "proxy" {
  rest_api_id   = aws_api_gateway_rest_api.user_management.id
  resource_id   = aws_api_gateway_resource.proxy.id
  http_method   = "ANY"
  authorization = "NONE"

  request_parameters = {
    "method.request.path.proxy" = true
  }
}

# 为根路径创建方法
resource "aws_api_gateway_method" "root" {
  rest_api_id   = aws_api_gateway_rest_api.user_management.id
  resource_id   = aws_api_gateway_rest_api.user_management.root_resource_id
  http_method   = "ANY"
  authorization = "NONE"
}

# 创建与 K8s NLB 的集成 - 代理路径
resource "aws_api_gateway_integration" "k8s_integration" {
  rest_api_id = aws_api_gateway_rest_api.user_management.id
  resource_id = aws_api_gateway_resource.proxy.id
  http_method = aws_api_gateway_method.proxy.http_method

  integration_http_method = "ANY"
  type                    = "HTTP_PROXY"
  uri                     = "http://${var.nlb_url}/{proxy}"

  request_parameters = {
    "integration.request.path.proxy" = "method.request.path.proxy"
  }
}

# 创建与 K8s NLB 的集成 - 根路径
resource "aws_api_gateway_integration" "root_integration" {
  rest_api_id = aws_api_gateway_rest_api.user_management.id
  resource_id = aws_api_gateway_rest_api.user_management.root_resource_id
  http_method = aws_api_gateway_method.root.http_method

  integration_http_method = "ANY"
  type                    = "HTTP_PROXY"
  uri                     = "http://${var.nlb_url}/"
}

# 创建部署
resource "aws_api_gateway_deployment" "deployment" {
  depends_on = [
    aws_api_gateway_integration.k8s_integration,
    aws_api_gateway_integration.root_integration
  ]

  rest_api_id = aws_api_gateway_rest_api.user_management.id

  triggers = {
    redeployment = sha1(jsonencode([
      aws_api_gateway_resource.proxy.id,
      aws_api_gateway_method.proxy.id,
      aws_api_gateway_method.root.id,
      aws_api_gateway_integration.k8s_integration.id,
      aws_api_gateway_integration.root_integration.id
    ]))
  }

  lifecycle {
    create_before_destroy = true
  }
}

# 创建阶段
resource "aws_api_gateway_stage" "prod" {
  deployment_id = aws_api_gateway_deployment.deployment.id
  rest_api_id   = aws_api_gateway_rest_api.user_management.id
  stage_name    = var.stage_name
}