使用 Terraform 为 AWS API 网关启用 CloudWatch 日志

Enable CloudWatch logs for AWS API Gateway using Terraform

我正在使用 OpenAPI 3.0 规范来部署 AWS API 网关。我无法弄清楚如何为部署启用云监视日志。

这是地形代码:

data "template_file" "test_api_swagger" {
  template = file(var.api_spec_path)

  vars = {
    //ommitted  
  }
}

resource "aws_api_gateway_rest_api" "test_api_gateway" {
  name        = "test_backend_api_gateway"
  description = "API Gateway for some x"
  body        = data.template_file.test_api_swagger.rendered

  endpoint_configuration {
    types = ["REGIONAL"]
  }
}

resource "aws_api_gateway_deployment" "test_lambda_gateway" {
  rest_api_id = aws_api_gateway_rest_api.test_api_gateway.id
  stage_name  = var.env
}

我检查了 Amazon OpenAPI 扩展,none 似乎有这个选项。我看到的唯一方法是使用 api_gateway_method_settings,在这种情况下我不能使用它。

我认为 Terraform 不支持它。我目前在创建部署后使用 terraform provisioner 到 运行 aws cli 命令,如下例所示:

The example that I'm providing is to enable XRay tracing. You'll need to research the correct path and value to be used for CloudWatch logs. You can find more information in the docs.

resource "aws_api_gateway_deployment" "test_lambda_gateway" {
  rest_api_id = aws_api_gateway_rest_api.test_api_gateway.id
  stage_name  = var.env

  provisioner "local-exec" {
    command = "aws apigateway update-stage --region ${data.aws_region.current.name} --rest-api-id ${aws_api_gateway_rest_api.test_api_gateway.id} --stage-name ${var.env} --patch-operations op=replace,path=/tracingEnabled,value=true"
  }

}

您只需在 Terraform 模板中引用 aws 数据提供程序:

data "aws_region" "current" {}

即使您使用 OpenAPI 导入创建网关,您仍然可以使用 api_gateway_method_settings 来引用阶段,前提是您正在使用推荐的阶段。参见 AWS documentation。您只需按照示例在 method_path 上注明“*/*”即可。

resource "aws_api_gateway_stage" "example" {
  deployment_id = aws_api_gateway_deployment.test_lambda_gateway.id
  rest_api_id   = aws_api_gateway_rest_api.test_api_gateway.id
  stage_name    = "example"
}

resource "aws_api_gateway_method_settings" "all" {
  rest_api_id = aws_api_gateway_rest_api.test_api_gateway.id
  stage_name  = aws_api_gateway_stage.example.stage_name
  method_path = "*/*"

  settings {
    logging_level   = "INFO"
  }
}

这应该在网关上为所有具有 INFO 级别日志记录的请求设置日志记录,就像您在舞台上的控制台中完成的一样。