Kaushik Vijayakumar
Kaushik Vijayakumar

Reputation: 835

Dynamic map creation in terraform

I have a map passed as variable

dummy = {
  1 = {
    instances = {
      "ip1" = {
        a = "earth"
        b = "hi"
        c = 1
      }
      "ip2" = {
        a = "world"
        b = "hello"
        c = 2
      }
      "ip3" = {
        a = "planet"
        b = "hey"
        c = 3
      }
    }
  }
}

Now I want construct a map as follows

value = {
  "ip1" = {
    b = "hi"
    c = 1
  }
  "ip2" = {
    b = "hello"
    c = 2
  }
  "ip3" = {
    b = "hey"
    c = 3
  }
}

I tried using for loops but nothing seems to work out The following is what I have tried since

_meta = {
  for instance in var.dummy.1.instances:
    (instance.key) = {
      b = instance.value.b
      c = instance.value.c
    }
}

But it says I cant access the key with for iteration variable

Upvotes: 2

Views: 4826

Answers (1)

Alain O'Dea
Alain O'Dea

Reputation: 21716

_meta = {
  for key, instance in var.dummy.1.instances:
    key => {
      b = instance.b
      c = instance.c
    }
}

A for expression is a bit different from a for_each. You don't get key or value variables in a for expression and you can explicitly pull whole entries from the map as I've shown above using key, value in map as the expression form.

You also need to use a fat arrow => operator between the key and value of the generated map entries.

Upvotes: 5

Related Questions