Dynamically changing the resource name

i am using terraform 0.12 version and i am creating multiple instances on the vmware cloud but i would like to differentiate between my instance via resource name.

something like we do in packer name= “vm-name{timestamp}” to make the names different from each other.

How are you creating multiple instances? If they are as separate resource blocks, then you can just name them separately.

If you are using for_each, then the each.key will be the name…

locals {
  collection = {
    first = 1
    second = 2
  }
}
resource "some_resource" "collection" {
  for_each = local.collection
}

will produce:

some_resource.collection["first"]
some_resource.collection["second"]

A more concrete example:

locals {
  dashboards = {
    "ASG-Overview" = {
      file = "ec2-asg-cloudwatch-dashboard.json.template"
      template_parameters = {
        vertical_annotations = file(format("clusters/%s/%s/annotations.json", var.cluster, var.environment))
        asgs                 = [for v in local.asgs : v if v.max_instances > 0]
      }
    }
    "Payments-Overview" = {
      file = "payments-cloudwatch-dashboard.json"
    }
    "Email-Overview" = {
      file = "ses-cloudwatch-dashboard.json"
    }
  }
}

resource "aws_cloudwatch_dashboard" "dashboards" {
  for_each = local.dashboards

  dashboard_name = each.key
  dashboard_body = contains(keys(each.value), "template_parameters") ? templatefile(each.value.file, each.value.template_parameters) : file(each.value.file)
}

produces:

aws_cloudwatch_dashboard.dashboards["ASG-Overview"]
aws_cloudwatch_dashboard.dashboards["Payments-Overview"]
aws_cloudwatch_dashboard.dashboards["Email-Overview"]

You can also use count and that will create multiple resources with the index being the “name” part …

some_resource.collection["0"]
some_resource.collection["1"]

I’ve had issues with this if the set is edited in some way or refers to locals and you’re using the count.index … things get destroyed/recreated because of the change in the index position.