首页 > 解决方案 > 使用 terraform 中的 for_each 表达式循环地图变量

问题描述

我有变量,我想在 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 值。但有些不对劲。你有什么建议我做错了吗?

谢谢!

标签: iterationterraform

解决方案


它不完全清楚是什么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
          }
        }
      ]

推荐阅读