1
votes

Please excuse if this is a dumb question. I'm a terraform noob and trying to determine the best approach to meet an enterprise requirement for resource naming.

Our cloud governance team has determined a naming scheme for all resources where you have [region][resource_type][app_name][instance 0001-999][env] So, for instance we might have something like the following for vm's:

uw1vmmyapp001dev
uw1vmmyapp002dev
etc.

This is all well and good when deploying from scratch as I just use the {count.index} However, now I am trying to determine how to deploy additional resources and start from the previously deloyed resources (that weren't deployed by terraform). Is there a terraform standard for gathering the existing inventory, parsing the current values and starting your incrementing from the highest instance number? (I was using randoms but our cloud governance team squashed that quickly.)

I'm really doing a poor job with my wording. Hopefully this makes some sort of sense?

Oh, I'm using azurerm_virtual_machine

1

1 Answers

2
votes

It's going to be pretty difficult when there isn't any delimiting characters... it's just a shoved together string. If there was a delimiting character you could maybe use split to break up the string and find out the number portion. There also doesn't appear to be a data source equivalent of azurerm_virtual_machine to get the naming information anyway.

Given that you'd need to manually look up the name or id anyway to import information about current resources you could find the highest numbered VM then use something like the following to add additional VMs and increment the number:

${var.region}${var.resource_type}${var.appname}${format("%03d", count.index + var.last_num)}${var.env}

To test what this looks like you can look at this example:

variable "last_num" {
  default = 98
}

variable "region" {
  default = "uw"
}

variable "resource_type" {
  default = "vm"
}

variable "appname" {
  default = "myapp"
}

variable "env" {
  default = "dev"
}

resource "local_file" "foo" {
  count    = 3
  filename = "foo.text"
  content  = "${var.region}${var.resource_type}${var.appname}${format("%03d", count.index + 1 + var.last_num)}${var.env}"
}

This gives naming output like this:

  + local_file.foo[0]
      id:       <computed>
      content:  "uwvmmyapp099dev"
      filename: "foo.text"

  + local_file.foo[1]
      id:       <computed>
      content:  "uwvmmyapp100dev"
      filename: "foo.text"

  + local_file.foo[2]
      id:       <computed>
      content:  "uwvmmyapp101dev"
      filename: "foo.text"