Miroslav
Miroslav

Reputation: 81

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. 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.

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:

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. But something is wrong. Do you have advice what I am doing wrong?

Thank you!

Upvotes: 0

Views: 2694

Answers (1)

Marcin
Marcin

Reputation: 238209

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:

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

Upvotes: 1

Related Questions