terraform - 在 Terraform 0.12 中合并两张 map 以创建第三张 map

标签 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列表中获取对应的元素
  • 将这些添加到结果 map 中。

  • 具体来说,我的问题是似乎没有任何等效于 Python 的 enumerate函数,这会阻止我跟踪索引。如果有,我想我可以做这样的事情:

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

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

    最佳答案

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

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

    关于terraform - 在 Terraform 0.12 中合并两张 map 以创建第三张 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56783589/

    相关文章:

    azure - 使用 Terraform 在 Azure Stack Edge 中部署 VM

    file - ansible 查找的替代方法,因为它总是在 localhost 上查找文件

    azure - Terraform with Azure - 强制资源的唯一名称的问题

    google-cloud-platform - 为 terraform 设置 gcs 后端的问题

    google-cloud-platform - Terraform 和 GCS : how to create a multi zone LB

    terraform - 如何忽略列表中的值?

    azure - Terraform 12 中的动态数据源

    Terraform DigitalOcean for_each 包含项目和 DNS 记录

    terraform:根据键过滤 map 列表

    terraform - 提供程序provider.terraform不支持​​资源类型“terraform_remote_state