Review API Gateway CloudWatch log delivery

Check CloudWatch delivery and retention for the API Gateway log type you use.

Description

Standard REST API execution logs use API-Gateway-Execution-Logs_{rest-api-id}/{stage_name}. To manage that group with Terraform, match the deployed API ID and stage name. Access logs use the destination set in access_log_settings.destination_arn.

Potential impact

If the names differ, the group Terraform manages will not contain that stage’s execution errors. Its retention policy can also apply to the wrong group.

Remediation

Enable standard execution logging and grant API Gateway CloudWatch Logs delivery permissions. If the group already exists, import it into Terraform before setting retention and read access. Send a test request that produces an event at the configured level. For ERROR, use a test request that produces a processing error. Check for the event in the expected group. For access logs, set a separate destination ARN and format.

Examples

The excerpts show only how to name the standard execution log group. Other API and stage settings, logging enablement, and delivery permissions are omitted.

Before

hcl
variable "stage_name" {
  default = "example"
  type    = string
}

variable "stage_names" {
  default = "examples"
  type    = string
}

resource "aws_api_gateway_rest_api" "example" {
  # ... other configuration ...
}

resource "aws_api_gateway_stage" "example" {
  depends_on = [aws_cloudwatch_log_group.example]

  stage_name = var.stage_name
  # ... other configuration ...
}

resource "aws_cloudwatch_log_group" "example" {
  name              = "API-Gateway-Execution-Logs_${aws_api_gateway_rest_api.example.id}/${var.stage_names}"
  retention_in_days = 7
}

After

hcl
variable "stage_name" {
  default = "example"
  type    = string
}

resource "aws_api_gateway_rest_api" "example" {
  # ... other configuration ...
}

resource "aws_api_gateway_stage" "example" {
  depends_on = [aws_cloudwatch_log_group.example]

  stage_name = var.stage_name
  # ... other configuration ...
}

resource "aws_cloudwatch_log_group" "example" {
  name              = "API-Gateway-Execution-Logs_${aws_api_gateway_rest_api.example.id}/${var.stage_name}"
  retention_in_days = 7
}

With the defaults, the stage is example but the original group name ends in examples. The revision uses var.stage_name in both places and retains logs for seven days.

References