如何在使用计数时呈现地形数据



我正在使用计数来创建多个AWS task_definition,这些task_definition应该由AWS步进函数执行。task_definition需要一个data "template_file" "task_definition" {节来填充模板数据。然后我需要一次呈现多个定义的模板数据,我被一个错误阻止了,看起来像这样:

The "count" value depends on resource attributes that cannot be determined until apply, so Terraform cannot predict how many instances will be created. To work around this, use the -target argument to first apply only the resources that the for_each depends on.

初始代码:

data "template_file" "task_definition" {
count    = length(var.task_container_command)
template = file("./configs/file.json")
vars = {
task = module.ecs[count.index].task_definition
}
}
module "step_function" {
count  = length(var.task_container_command)
source = "path"
region                    = var.region
name                      = "${var.step_function_name}-${count.index}"
definition_file           = data.template_file.task_definition.rendered
}

这里的要点是我不能渲染task_definition,因为这些在应用之前还不被terraform知道。我也不能使用-target参数,因为我想在代码中进行更改,而不是在部署管道中进行更改。这意味着当您尝试在definition_file上执行terraform plan时,错误将弹出。解决方案如下。

这样做可以将count的使用与.rendered参数解耦:

data "template_file" "task_definition" {
count    = length(var.task_container_command)
template = file("./configs/file.json")
vars = {
task = module.ecs[count.index].task_definition
}
}
resource "local_file" "foo" {
count    = length(var.task_container_command)
content  = element(data.template_file.task_definition.*.rendered, count.index)
filename = "task-definition-${count.index}"
}
module "step_function" {
count  = length(var.task_container_command)
source = "path"
region                    = var.region
name                      = "${var.step_function_name}-${count.index}"
definition_file           = local_file.foo[count.index].filename
}

现在您的数据呈现在名为"foo"的资源中。然后传递给step_function模块,这样terraform plan已经知道变量内部的内容。foo的content元素的作用就像一个循环来呈现我使用不同文件名创建的每个task_definition,以避免重复。

希望对你有所帮助:)

最新更新