如何避免在Terraform中重复变量?

时间:2019-07-19 20:33:08

标签: terraform

Terraform不允许您在变量文件中插入变量,否则会出现错误:

  

错误:不允许使用变量

     

在variables.tf第9行中,在变量“ resource_group_name”中:9:
  默认=“ $ {var.prefix} -terraform-dev_rg”

     

此处可能不使用变量。

这意味着当我尝试为资源组创建名称时,我最终会在 variables.tf 文件中复制前缀的值。

是否有解决此问题的好方法,以避免重复变量的值?

variables.tf

getDestination()

main.tf

variable "prefix" {
  description = "The prefix used for all resources in this plan"
  default     = "terraform-dev"
}

variable resource_group_name {
  type = "string"
  default = "terraform-dev_rg"
}

variable resource_group_location {
  type = "string"
  default = "eastus"
}

./ firewall / variables.tf

# Configure the Microsoft Azure Provider
provider "azurerm" {
  version         = "=1.28.0"
}

# Create a resource group
resource "azurerm_resource_group" "resource-group" {
  name     = var.resource_group_name
  location = var.resource_group_location
}

#Create an application gateway with web app firewall
module "firewall" {
  source                  = "./firewall"
  resource_group_name     = var.resource_group_name
  resource_group_location = var.resource_group_location
}

./ firewall / main.tf

#Passed down from the root variables.tf
variable "prefix" {}
variable "resource_group_name" {}
variable "resource_group_location" {}

1 个答案:

答案 0 :(得分:2)

尝试使用本地值, https://www.terraform.io/docs/configuration/locals.html

variable "prefix" {
  description = "The prefix used for all resources in this plan"
  default     = "terraform-dev"
}

variable resource_group_location {
  type    = "string"
  default = "eastus"
}

locals {
  resource_group_name = "${var.prefix}_rg"
}

resource "azurerm_resource_group" "resource-group" {
  name     = local.resource_group_name
  location = var.resource_group_location
}