【问题标题】:Looping over map variable using for_each expression in terraform使用 terraform 中的 for_each 表达式循环地图变量
【发布时间】:2021-05-19 15:51:30
【问题描述】:

我有一个变量,我想在 terraform 中使用 for_each 进行迭代,以创建子模块的多个实例 - node_groups,它是 eks 模块的一部分。这是我的变量:

variable "frame_platform_eks_node_groups" {
  type = map
  default = {
    eks_kube_system = {
      desired_capacity = 1,
      max_capacity     = 5,
      min_capacity     = 1,
      instance_type    = ["m5.large"],
      k8s_label        = "eks_kube_system",
      additional_tags  = "eks_kube_system_node"
    },
    eks_jenkins_build = {
      desired_capacity = 1,
      max_capacity     = 10,
      min_capacity     = 1,
      instance_type    = ["m5.large"],
      k8s_label        = "eks_jenkins_build",
      additional_tags  = "eks_jenkins_build_node"
    }
  }
}  

这是我的 node_groups 子模块,它是模块 eks 的一部分。

module "eks" {
    ...
    node_groups = {
        for_each = var.frame_platform_eks_node_groups
        each.key = {
          desired_capacity = each.value.desired_capacity
          max_capacity     = each.value.max_capacity
          min_capacity     = each.value.min_capacity
    
          instance_types = each.value.instance_type
          k8s_labels = {
            Name = each.value.k8s_label
          }
          additional_tags = {
            ExtraTag = each.value.additional_tags
          }
        }

当我运行 terraform plan 时,出现以下错误:

15: each.key = {

If this expression is intended to be a reference, wrap it in parentheses. If
it’s instead intended as a literal name containing periods, wrap it in quotes
to create a string literal.

我的意图显然是使用 each.key 引用从 map 变量中获取 eks_kube_system 和 eks_jenkins_build 值。但有些不对劲。你有什么建议我做错了吗?

谢谢!

【问题讨论】:

  • 我实际上并没有设法做到这一点。找到了一些解决方法。
  • 到底是什么问题?

标签: iteration terraform


【解决方案1】:

不清楚node_groups 是什么,因为它没有在您的问题中定义,但假设它是一个地图列表,那么代码应该是:

module "eks" {
    ...
    node_groups = [
          for k,v in var.frame_platform_eks_node_groups:
          {
          desired_capacity = v.desired_capacity
          max_capacity     = v.max_capacity
          min_capacity     = v.min_capacity
    
          instance_types = v.instance_type
          k8s_labels = {
            Name = v.k8s_label
          }
          additional_tags = {
            ExtraTag = v.additional_tags
          }
        }
      ]

【讨论】:

    猜你喜欢
    • 2020-11-01
    • 2021-01-17
    • 2021-11-25
    • 1970-01-01
    • 2021-10-04
    • 2021-10-06
    • 2020-10-22
    • 2021-01-18
    • 2021-05-25
    相关资源
    最近更新 更多