在 Terraform 0.12 中合并两个地图以创建第三个地图

Ale*_*vey 6 terraform terraform0.12+

我需要在 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"]
}
Run Code Online (Sandbox Code Playgroud)

然后我想将这些源组合到一个模板中,如下所示:

#!/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}
Run Code Online (Sandbox Code Playgroud)

其中merged包含组合数据。

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

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

  • 迭代 ebs_block_devices 列表,跟踪索引(就像enumerate()在 Python 或each.with_indexRuby 中一样)
  • 从mount_points列表中获取对应的元素
  • 将它们添加到生成的地图中。

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

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

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

Ale*_*vey 4

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


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]})
  ]
}
Run Code Online (Sandbox Code Playgroud)

感谢 HashiCorp 的支持。