【问题标题】:Dynamically create sub collection for api gateway resource为api网关资源动态创建子集合
【发布时间】:2020-12-27 17:38:00
【问题描述】:

给定网址/customers/{customerId}/accounts/customers/{customerId}/accounts/{accountId}

是否可以动态创建资源?

我不想有重复的代码。我打算使用某种地图或列表来管理它。有没有可能?

示例(硬代码):

resource "aws_api_gateway_resource" "customers" {
  rest_api_id = "${aws_api_gateway_rest_api.my-api.id}"
  parent_id = "${aws_api_gateway_rest_api.my-api.root_resource_id}"
  path_part = "customers"
}

resource "aws_api_gateway_resource" "single-customer" {
  rest_api_id = "${aws_api_gateway_rest_api.my-api.id}"
  parent_id = "${aws_api_gateway_resource.customers.id}"
  path_part = "{customerId}"
}

resource "aws_api_gateway_resource" "customers-accounts" {
  rest_api_id = "${aws_api_gateway_rest_api.my-api.id}"
  parent_id = "${aws_api_gateway_resource.single-customer.id}"
  path_part = "accounts"
}

//----
// GET
//----
resource "aws_api_gateway_method" "get-customers-accounts" {
  rest_api_id = "${aws_api_gateway_rest_api.my-api.id}"
  resource_id = "${aws_api_gateway_resource.customers-accounts.id}"
  http_method = "GET"
  authorization = "NONE"
}

类似这样的:

resource "aws_api_gateway_resource" "var.resource.name" {
  rest_api_id = "${aws_api_gateway_rest_api.my-api.id}"
  parent_id = "${aws_api_gateway_rest_api.<previous resource id or root id if is root>}"
  path_part = "<current value>"
}

【问题讨论】:

  • 您在那里使用 HCL1 语法。你能确认你需要一个 0.11 兼容的答案(并且还用terraform0.11 标记问​​题)还是用 HCL2 语法替换语法?
  • @ydaetskcoR 我只是举个例子。我正在使用 0.12

标签: amazon-web-services terraform terraform0.12+


【解决方案1】:

资源名称不能是动态的。

一种常见的解决方案是定义一次资源并使用count 变量基于列表动态创建多个实例,例如(未经测试,示例代码与您提供的 HCL1 语法相同):

locals {
    list_of_maps = [{
        "api_id" = "some_id",
        etc...
    },{
        "api_id" = "some_id",
        etc...
    }]
}

resource "aws_api_gateway_resource" "gateway" {
    // will create a resource for every element inside list_of_maps 
    count = "${count(local.list_of_maps)}"

    // every iteration will take the corresponding map and pull variables from it using "lookup" 
    rest_api_id = "${lookup(element(local.list_of_maps, count.index), "api_id")}"

    etc...
}

您还可以将上面的资源包装在 module 中,并将 list_of_maps 作为变量传递,从而允许进一步重用此资源定义。

【讨论】:

  • Hmmmm.. 但 parent_id 取决于之前的 aws_api_gateway_resource. gateway.id。如果我们这样做,我们怎么能得到它?
猜你喜欢
  • 2020-03-10
  • 1970-01-01
  • 2012-03-22
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多