Terraform combine 2 variables into a new variable

后端 未结 1 481
暗喜
暗喜 2021-01-06 03:36

I want to automate deployments of Vmware VM\'s in an landscape with lots of portgroups. To be able to select the correct portgroup it would be best to enter 2 variables ten

相关标签:
1条回答
  • 2021-01-06 03:54

    Off the top of my head I can think of three different ways to merge the variables to use as a lookup key:

    variable "tenant" {}
    variable "environment" {}
    
    variable "vm_network" {
      default = {
        T1_PROD = "T1-PROD-network"
        T2_PROD = "T2-PROD-network"
        T1_TEST = "T1-TEST-network"
        T2_TEST = "T2-TEST-network"
      }
    }
    
    locals {
      tenant_environment = "${var.tenant}_${var.environment}"
    }
    
    output "local_network" {
      value = "${lookup(var.vm_network, local.tenant_environment)}"
    }
    
    output "format_network" {
      value = "${lookup(var.vm_network, format("%s_%s", var.tenant, var.environment))}"
    }
    
    output "lookup_network" {
      value = "${lookup(var.vm_network, "${var.tenant}_${var.environment}")}"
    }
    

    The first option uses locals to create a variable that is interpolated already and can be easily reused in multiple places which can't be done directly with variables in Terraform/HCL. This is generally the best way to do variable combination/interpolation in later versions of Terraform (they were introduced in Terraform 0.10.3).

    The second option uses the format function to create a string containing the tenant and environment variables.

    The last one is a little funny looking but is valid HCL. I'd probably shy away from using that syntax if possible.

    0 讨论(0)
提交回复
热议问题