Terraform - CosmosDB 的变量名称

Terraform - Variable name for CosmosDB

我正在使用 Terraform 在 Azure 中创建资源并将文件拆分为 main.tfvariables.tfterraform.tfvars

为了有一个标准的命名约定,我在命名资源时遵循以下过程。

前缀环境资源名称

例如,在main.tf中我创建如下:

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

变量将在variables.tf中声明,terraform.tfvars将包含

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

并且在执行 Terraform 时,我将创建资源名称为“sample-dev-rg

这在我创建其他资源或将代码部署到其他环境时会派上用场。因为我只需要单独修改 tfvars。

另一个例子:

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

我的问题是:

如果您使用的是 Terraform 0.13 及更高版本,则可以对构成资源名称的每个变量使用 regex validation,并确保其中 none 使用 special/unusual 个字符。这是一个示例 prefix 变量,它只能使用 A-Z、a-z、0-9 和 - 字符:

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."
  }
}

要创建类似 sampledevcosmosdbnameprefixenvironmentdbname)的内容,您可以像这样将多个插值并排放置 - 没有分隔需要:

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