skip to Main Content

I use Terraform to create VMs with names based on count.index. I would like to create tags where the keys are dynamically based on count.index. I just couldn’t get it working.

For VM01, tag should be "PatchCycle01 = centos" & for VM02, it should be "PatchCycle02 = centos".

  tags = {
    PatchCycle${format("%02d", count.index + 1)} = "CentOS"
  }

I tried the above code but it didn’t work. Any suggestions?

2

Answers


  1. The key needs to be built with a string template like this:

    tags = {
      "PatchCycle${format("%02d", count.index + 1)}" = "CentOS"
    }
    

    If you are using something earier than Terraform 0.12, you will have to use the map function which is deprecated now:

    tags = "${map(
      "PatchCycle${format("%02d", count.index + 1)}", "CentOS"}"
    )
    
    Login or Signup to reply.
  2. You just need to properly quote the left hand side (the key of the map) for this to work:

    locals {
      foo = "foo"
    
      map_test = {
        "PatchCycle${local.foo}" = "foo"
      }
    }
    
    output "foo" {
      value = local.map_test
    }
    

    Applying the above outputs the following:

    foo = {
      "PatchCyclefoo" = "foo"
    }
    

    So for your example you would do something like this:

      tags = {
        "PatchCycle${format("%02d", count.index + 1)}" = "CentOS"
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search