问题描述
给出网址/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>"
}
解决方法
资源名称不能是动态的。
常见的解决方案是一次定义资源,然后使用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
作为变量传递,以允许进一步重用此资源定义。