简体   繁体   English

使用 terraform 中的 for_each 表达式循环 map 变量

[英]Looping over map variable using for_each expression in terraform

I have variable that I want to iterate over using for_each in terraform to create multiple instances of submodule - node_groups, which is part of eks module.我有变量,我想在 terraform 中使用 for_each 进行迭代,以创建子模块的多个实例 - node_groups,它是 eks 模块的一部分。 This is my variable:这是我的变量:

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"
    }
  }
}  

And this is my node_groups submodule, which is part of module eks.这是我的 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
          }
        }

When I run terraform plan I am getting following error:当我运行 terraform 计划时,我收到以下错误:

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.

My intention obviously is to get eks_kube_system and eks_jenkins_build values from the map variable with each.key reference.我的意图显然是使用 each.key 引用从 map 变量中获取 eks_kube_system 和 eks_jenkins_build 值。 But something is wrong.但有些不对劲。 Do you have advice what I am doing wrong?你有什么建议我做错了吗?

Thank you!谢谢!

Its not exactly clear what node_groups is as it is not defined in your question, but assuming that it is a list of maps, then the code should be:它不完全清楚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
          }
        }
      ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM