简体   繁体   中英

Enable CloudWatch logs for AWS API Gateway using Terraform

I am using OpenAPI 3.0 spec to deploy an AWS API Gateway. I am not able to figure out how to enable cloud watch logs for the deployment.

Here is the terraform code:

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
}

I checked Amazon OpenAPI extensions and none seem to have this option. Only way I see is using api_gateway_method_settings which I cannot use in this case.

I think that it is not supported in terraform. I'm currently using terraform provisioner to run aws cli command after the deployment is created, like in the example below:

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"
  }

}

You just need to make a reference to the aws data provider in your terraform template:

data "aws_region" "current" {}

Even though you're creating the gateway with OpenAPI import, you can still use api_gateway_method_settings to reference the stage, assuming you're using a stage as recommended. See AWS documentation . You would just indicate "*/*" on the method_path as per the example.

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"
  }
}

This should set up the logging on the gateway for all requests with INFO level logging as if you had done it in the console on the stage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM