簡體   English   中英

使用 Terraform 為 AWS API 網關啟用 CloudWatch 日志

[英]Enable CloudWatch logs for AWS API Gateway using Terraform

我正在使用 OpenAPI 3.0 規范部署 AWS API 網關。 我無法弄清楚如何為部署啟用雲監視日志。

這是 terraform 代碼:

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 。

我認為 terraform 不支持它。 我目前正在使用terraform 配置程序在創建部署后運行 aws cli 命令,如下例所示:

我提供的示例是啟用 XRay 跟蹤。 您需要研究用於 CloudWatch 日志的正確路徑和值。 您可以在文檔中找到更多信息。

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 文檔 根據示例,您只需在 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 級別日志記錄的請求設置日志記錄,就像您在舞台上的控制台中完成的一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM