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

时间:2019-06-27 03:43:01

标签: 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"]
}

然后我想将这些来源合并到这样的模板中:

#!/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列表,跟踪索引(例如Python中的enumerate()或Ruby中的each.with_index
  • 从mount_points列表中获取相应的元素
  • 将其添加到生成的地图中。

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

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

目前在Terraform中可以进行这种数据转换吗?如果不可能的话,首选的替代实现是什么?

1 个答案:

答案 0 :(得分:0)

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


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的支持。