Dennis
Dennis

Reputation: 81

Concatenate two variables into another string

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 tenant and environment. These 2 variables are used for CMDB registration and deployment purposes.

For the deployment the variables need to be combined in to 1 new variable to pick the correct portgroup. Due to interpolation syntax it seems to be impossible to use 2 combined variables in the lookup.

How can I combine 2 variables to 1 in Terraform?

I also tried to make a local file with the correct string, but that file needs to exist before the script starts, terraform plan gives a error message that the file doesn't exist.

variable "tenant" {
  description = "tenant: T1 or T2"
}

variable "environment" {
  description = "environment: PROD or TEST"
}

variable "vm_network" {
  description = "network the VM will be provisioned with"
  type = "map"
  default = {
    T1_PROD = "T1-PROD-network"
    T2_PROD = "T2-PROD-network"
    T1_TEST = "T1-TEST-network"
    T2_TEST = "T2-TEST-network"
  }
}

data "vsphere_network" "network" {
  name          = "${lookup(var.vm_network, tenant_environment)}"
  datacenter_id = "${data.vsphere_datacenter.dc.id}"
}

Upvotes: 8

Views: 25904

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56997

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.

Upvotes: 9

Related Questions