【问题标题】:Enable CloudWatch logs for AWS API Gateway using Terraform使用 Terraform 为 AWS API Gateway 启用 CloudWatch 日志
【发布时间】:2020-10-25 09:53:55
【问题描述】:

我正在使用 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 扩展,但似乎没有一个具有此选项。我看到的唯一方法是使用在这种情况下我无法使用的 api_gateway_method_settings。

【问题讨论】:

    标签: amazon-web-services terraform aws-api-gateway terraform-provider-aws


    【解决方案1】:

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

    我提供的示例是启用 XRay 跟踪。您需要研究用于 CloudWatch 日志的正确路径和值。您可以在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" {}
    

    【讨论】:

    • 您好,我可以使用aws_api_gateway_deployment 来启用 cloudwatch 日志记录和 X 射线的 stepfunction 吗?
    【解决方案2】:

    即使您使用 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 级别日志记录的请求设置日志记录,就像您在舞台上的控制台中完成一样。

    【讨论】:

    猜你喜欢
    • 2017-10-10
    • 2020-05-27
    • 2019-07-25
    • 2020-05-13
    • 2019-02-08
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 2021-02-08
    相关资源
    最近更新 更多