代码之家  ›  专栏  ›  技术社区  ›  opticyclic

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

  •  0
  • opticyclic  · 技术社区  · 7 年前

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

    错误:不允许使用变量

    关于变量。tf第9行,变量“resource_group_name”中:9:
    default=“${var.prefix}-terraform-dev_rg”

    这里不能使用变量。

    这意味着我最终会复制我的 变量。tf 当我尝试创建资源组的名称时。

    有没有避免重复变量值的好方法?

    变量。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"
    }
    

    主要的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
    }
    

    /防火墙/变量。tf

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

    /防火墙/主。tf

    # Create a virtual network for the firewall
    resource "azurerm_virtual_network" "firewall-vnet" {
      name = "${var.prefix}-waf-vnet"
      address_space = ["10.0.0.0/16"]
      resource_group_name = var.resource_group_name
      location            = var.resource_group_location
    }
    
    0 回复  |  直到 7 年前
        1
  •  3
  •   RyanKim    7 年前

    尝试使用本地值, 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
    }