terraformaws-api-gateway

terraform aws api gateway configure method throttling per each api key


I want to configure usage plan, api key and method like below.

Basically one aws api gateway has 10 methods, i want to configure different rate for each resource

usage plan     api key    Resource  Method  Rate (requests per second)
usage plan1    apiKey1    /a        POST    1 qps
usage plan1    apiKey1    /b        POST    2 qps
usage plan2    apiKey2    /a        POST    4 qps
usage plan2    apiKey2    /b        POST    6 qps

But in aws_api_gateway_usage_plan i can only find usage plan setting for stage.

What terraform resource can i use to configure usage plan

I want to achieve below feature Configure Method Throttling

enter image description here


Solution

  • After checking, i think until now, terraform does not support this feature.

    However there is workaround by using aws cli commend.

    Refer to this link:

    https://github.com/terraform-providers/terraform-provider-aws/issues/5901

    I quoted the work around here

    variable "method_throttling" {
      type        = "list"
      description = "example method throttling"
      default     = [
        "\\\"/<RESOURCE1>/<METHOD1>\\\":{\\\"rateLimit\\\":400,\\\"burstLimit\\\":150}",
        "\\\"/<RESOURCE2>/<METHOD2>\\\":{\\\"rateLimit\\\":1000,\\\"burstLimit\\\":303}"
      ]
    }
    
    # locals
    locals {
      # Delimiter for later usage
      delimiter      = "'"
    
      # Base aws cli command
      base_command   = "aws apigateway update-usage-plan --usage-plan-id ${aws_api_gateway_usage_plan.usage_plan.id} --patch-operations op"
    
      # Later aws cli command
      base_path      = "path=/apiStages/${var.api_gateway_rest_api_id}:${var.api_gateway_stage_name}/throttle,value"
    
      # Join method throttling variable to string
      methods_string = "${local.delimiter}\"{${join(",", var.method_throttling)}}\"${local.delimiter}"
    }
    
    resource "null_resource" "method_throttling" {
      count = "${length(var.method_throttling) != 0 ? 1 : 0}"
    
      # create method throttling
      provisioner "local-exec" {
        when       = "create"
        command    = "${local.base_command}=add,${local.base_path}=${local.methods_string}"
        on_failure = "continue"
      }
    
      # edit method throttling
      provisioner "local-exec" {
        command = "${local.base_command}=replace,${local.base_path}=${local.methods_string}"
        on_failure = "fail"
      }  
    
      # delete method throttling
      provisioner "local-exec" {
        when    = "destroy"
        command = "${local.base_command}=remove,${local.base_path}="    
        on_failure = "fail"
      }
    
      triggers = {
        usage_plan_change  = "${aws_api_gateway_usage_plan.usage_plan.id}"
        methods_change     = "${local.methods_string}"
      }
    
      depends_on = [
        "aws_api_gateway_usage_plan.usage_plan"
      ]
    }