【问题标题】:How to render terraform data when using a count使用计数时如何渲染地形数据
【发布时间】:2021-12-09 03:18:38
【问题描述】:

我使用计数来创建应由 AWS 步骤函数执行的多个 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 时,将弹出错误。 解决方法如下。

【问题讨论】:

    标签: terraform terraform-provider-aws terraform-template-file


    【解决方案1】:

    通过这样做,将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 的内容元素就像一个循环来呈现我使用不同文件名创建的每个 task_definition 以避免重复。

    希望这有帮助:)

    【讨论】:

    猜你喜欢
    • 2021-10-18
    • 2020-03-10
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 2021-03-11
    • 2022-10-08
    相关资源
    最近更新 更多