1
votes

I'm using Terraform to create the resources in Azure and have split the files as main.tf, variables.tf and terraform.tfvars

In order to have a standard naming convention, I'm following the process below when naming the resources.

prefix-environment-resourcename

For example, in main.tf I'm creating it as below:

resource "azurerm_resource_group" "rg" {
name     = "${var.prefix}-${var.environment}-${var.resource_group_name}" 
location = "westus"
}

The variables will be declared in variables.tf and the terraform.tfvars will contain

prefix = "sample"
environment = "dev"
resource_group_name = "rg"

and when the Terraform is executed, I'll get the resource name created as "sample-dev-rg"

This will come in handy when I'm creating other resources or deploy the code to other environments. Since I just need to modify the tfvars alone.

Another example:

resource "azurerm_app_service" "example" {
  name  = "${var.prefix}-${var.environment_name}-${var.appservice_name}"
}

My issue is:

  • How do I use the logic above for CosmosDb? I need the name in the main.tf to be created without special characters.
  • How do I create something like this: sampledevcosmosdbname
1

1 Answers

1
votes

If you're using Terraform 0.13 and above, you can make use of regex validation for each of the variables that make up your resource names, and ensure that none of them use special/unusual characters. Here's an example prefix variable that can only use A-Z, a-z, 0-9, and - characters:

variable "prefix" {
  type        = string
  description = "Prefix ID"

  validation {
    condition     = can(regex("^[A-Za-z0-9-]*$", var.prefix))
    error_message = "The prefix cannot use special characters."
  }
}

To create something like sampledevcosmosdbname (prefix, environment, dbname), you can just place several interpolations next to one another like so - no separation is needed:

resource "azurerm_cosmosdb_sql_database" "example" {
   ...
   name = "${var.prefix}${var.environment}${var.dbname}"
}