在 Terraform 中引用以变量命名的资源 [英] Referring to resources named with variables in Terraform
问题描述
我正在尝试在 Terraform 中创建一个模块,该模块可以使用不同的变量输入多次实例化.在模块中,当资源名称依赖于输入变量时,如何引用资源?我正在尝试通过括号语法 ("${aws_ecs_task_definition[var.name].arn}"
) 来实现,但我只是猜到了.
I'm trying to create a module in Terraform that can be instantiated multiple times with different variable inputs. Within the module, how do I reference resources when their names depend on an input variable? I'm trying to do it via the bracket syntax ("${aws_ecs_task_definition[var.name].arn}"
) but I just guessed at that.
(警告:我可能会以完全错误的方式处理这个问题)
(Caveat: I might be going about this in completely the wrong way)
这是我模块的(简化的)main.tf
文件:
Here's my module's (simplified) main.tf
file:
variable "name" {}
resource "aws_ecs_service" "${var.name}" {
name = "${var.name}_service"
cluster = ""
task_definition = "${aws_ecs_task_definition[var.name].arn}"
desired_count = 1
}
resource "aws_ecs_task_definition" "${var.name}" {
family = "ecs-family-${var.name}"
container_definitions = "${template_file[var.name].rendered}"
}
resource "template_file" "${var.name}_task" {
template = "${file("task-definition.json")}"
vars {
name = "${var.name}"
}
}
我收到以下错误:
Error loading Terraform: Error downloading modules: module foo: Error loading .terraform/modules/af13a92c4edda294822b341862422ba5/main.tf: Error reading config for aws_ecs_service[${var.name}]: parse error: syntax error
推荐答案
我从根本上误解了模块的工作原理.
I was fundamentally misunderstanding how modules worked.
Terraform 不支持在资源名称中插值(参见 relevant issues),但在我的情况下这并不重要,因为模块的每个实例的资源都是在实例的命名空间中.我担心资源名称冲突,但模块系统已经处理了.
Terraform does not support interpolation in resource names (see the relevant issues), but that doesn't matter in my case, because the resources of each instance of a module are in the instance's namespace. I was worried about resource names colliding, but the module system already handles that.
这篇关于在 Terraform 中引用以变量命名的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!