5

我需要在 Terraform 0.12 中对输入数据进行一些复杂的合并。我不知道这是否可能,但也许我只是做错了什么。

我有两个变量:

variable "ebs_block_device" {
  description = "Additional EBS block devices to attach to the instance"
  type        = list(map(string))
  default     = [
    {
      device_name = "/dev/sdg"
      volume_size = 5
      volume_type = "gp2"
      delete_on_termination = false
    },
    {
      device_name = "/dev/sdh"
      volume_size = 5
      volume_type = "gp2"
      delete_on_termination = false
    }
  ]
}

variable "mount_point" {
  description = "Mount point to use"
  type = list(string)
  default = ["/data", "/home"]
}

然后我想在这样的模板中组合这些源:

#!/usr/bin/env bash
%{for e in merged ~}
mkfs -t xfs ${e.device_name}
mkdir -p ${e.mount_point}
mount ${e.device_name} ${e.mount_point}
%{endfor}

哪里merged将包含组合数据。

模板语言似乎只支持简单的 for 循环,因此在那里进行合并似乎是不可能的。

因此,我假设数据处理需要在 DSL 中进行。但是,我需要这样做:

  • 遍历 ebs_block_devices 列表,跟踪索引(如enumerate()在 Python 或each.with_indexRuby 中)
  • 从 mount_points 列表中获取对应的元素
  • 将这些添加到生成的地图中。

具体来说,我的问题是似乎没有任何等效的 Pythonenumerate函数,这使我无法跟踪索引。如果有,我想我可以做这样的事情:

merged = [for index, x in enumerate(var.ebs_block_device): {
  merge(x, {mount_point => var.mount_point[index]})
}]

我现在尝试在 Terraform 中进行的这种数据转换是否可行?如果不可能,首选的替代实现是什么?

4

1 回答 1

3

事实证明,这实际上是可能的:


variable "ebs_block_device" {
  description = "Additional EBS block devices to attach to the instance"
  type        = list(map(string))
  default     = [
    {
      device_name = "/dev/sdg"
      volume_size = 5
      volume_type = "gp2"
      delete_on_termination = false
    },
    {
      device_name = "/dev/sdh"
      volume_size = 5
      volume_type = "gp2"
      delete_on_termination = false
    }
  ]
}

variable "mount_point" {
  description = "Mount point to use"
  type = list(string)
  default = ["/data", "/home"]
}

output "merged" {
  value = [
    for index, x in var.ebs_block_device:
    merge(x, {"mount_point" = var.mount_point[index]})
  ]
}

感谢 HashiCorp 的支持。

于 2019-06-30T15:21:12.547 回答