UPD: added multiple stage support

This commit is contained in:
xpk 2024-03-04 14:12:59 +08:00
parent cd170c0f78
commit 8b63c15654
Signed by: xpk
GPG Key ID: CD4FF6793F09AB86
3 changed files with 49 additions and 7 deletions

View File

@ -9,8 +9,21 @@ module "apigw" {
lambda-archive-file = "${path.module}/lambda_function.zip"
name = "ken2026-test"
path_part = "hello"
stage-name = "dev"
lambda-main-function-name = "main"
stages = {
"dev" : {
"description" : "Dev stage"
"variables" : {
"var1" : "foo"
}
}
"prd" : {
"description" : "Prd stage"
"variables" : {
"var1" : "bar"
}
}
}
}
/*

View File

@ -65,15 +65,38 @@ resource "aws_api_gateway_deployment" "apigw-deployment" {
}
resource "aws_api_gateway_stage" "apigw-stage" {
for_each = var.stages
depends_on = [aws_cloudwatch_log_group.this]
deployment_id = aws_api_gateway_deployment.apigw-deployment.id
rest_api_id = aws_api_gateway_rest_api.api.id
stage_name = var.stage-name
stage_name = each.key
description = each.value["description"]
variables = each.value["variables"]
access_log_settings {
destination_arn = aws_cloudwatch_log_group.this[each.key].arn
# https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html
format = jsonencode({
"requestId" : "$context.requestId",
"extendedRequestId" : "$context.extendedRequestId",
"ip" : "$context.identity.sourceIp",
"caller" : "$context.identity.caller",
"user" : "$context.identity.user",
"requestTime" : "$context.requestTime",
"httpMethod" : "$context.httpMethod",
"resourcePath" : "$context.resourcePath",
"status" : "$context.status",
"protocol" : "$context.protocol",
"responseLength" : "$context.responseLength"
}
)
}
}
resource "aws_api_gateway_method_settings" "apigw-method-settings" {
for_each = aws_api_gateway_stage.apigw-stage
rest_api_id = aws_api_gateway_rest_api.api.id
stage_name = aws_api_gateway_stage.apigw-stage.stage_name
stage_name = each.value.stage_name
method_path = "*/*"
settings {
@ -84,7 +107,8 @@ resource "aws_api_gateway_method_settings" "apigw-method-settings" {
# Cloudwatch log group path: API-Gateway-Execution-Logs_{rest-api-id}/{stage_name}
resource "aws_cloudwatch_log_group" "this" {
name = "API-Gateway-Execution-Logs_${aws_api_gateway_rest_api.api.id}/${var.stage-name}"
for_each = var.stages
name = "API-Gateway-Execution-Logs_${aws_api_gateway_rest_api.api.id}/${each.key}"
retention_in_days = var.cloudwatchlog-retention
kms_key_id = var.cwl-cmk-key-id
}

View File

@ -13,9 +13,14 @@ variable "path_part" {
description = "Last path segment of this API resource"
}
variable "stage-name" {
type = string
description = "Apigateway stage name"
#variable "stage-name" {
# type = string
# description = "Apigateway stage name"
#}
variable stages {
type = map
description = "apigateway stages"
}
variable "lambda-archive-file" {