在 Terraform 中,如何在请求路径中指定带有变量的 API 网关端点?

In Terraform, how do you specify an API Gateway endpoint with a variable in the request path?

在 AWS API 网关中,我有一个定义为 /users/{userId}/someAction 的端点,我正在尝试使用 terraform

重新创建它

我会像这样开始拥有某种链接的 gateway_resource 链...

resource "aws_api_gateway_resource" "Users" {
  rest_api_id = "${var.rest_api_id}" 
  parent_id = "${var.parent_id}" 
  path_part = "users"
}

//{userId} here?

resource "aws_api_gateway_resource" "SomeAction" {
  rest_api_id = "${var.rest_api_id}" 
  parent_id = "${aws_api_gateway_resource.UserIdReference.id}"
  path_part = "someAction"
}

然后我在其中定义 aws_api_gateway_method 和其他所有内容。

如何在 Terraform 中定义此端点? Terraform 文档和示例不涵盖此用例。

您需要定义一个resource,其path_part是您要使用的参数:

// List
resource "aws_api_gateway_resource" "accounts" {
    rest_api_id = var.gateway_id
    parent_id   = aws_api_gateway_resource.finance.id
    path_part   = "accounts"
}

// Unit
resource "aws_api_gateway_resource" "account" {
  rest_api_id = var.gateway_id
  parent_id   = aws_api_gateway_resource.accounts.id
  path_part   = "{accountId}"
}

然后创建method启用路径参数:

resource "aws_api_gateway_method" "get-account" {
  rest_api_id   = var.gateway_id
  resource_id   = var.resource_id
  http_method   = "GET"
  authorization = "NONE"

  request_parameters = {
    "method.request.path.accountId" = true
  }
}

最后您可以在 integration:

中成功创建映射
resource "aws_api_gateway_integration" "get-account-integration" {
    rest_api_id             = var.gateway_id
    resource_id             = var.resource_id
    http_method             = aws_api_gateway_method.get-account.http_method
    type                    = "HTTP"
    integration_http_method = "GET"
    uri                     = "/integration/accounts/{id}"
    passthrough_behavior    = "WHEN_NO_MATCH"

    request_parameters = {
        "integration.request.path.id" = "method.request.path.accountId"
    }
}

该方法需要存在 - 并启用参数 - 以便集成映射起作用。