terraform

Variables within variables


First off - apologies - I’m extremely new (3 hours in!) to using terraform.

I am looking to try and use the value of a variable inside the declaration of another variable.

Below is my code - what am I doing wrong?

variables.tf:

variable "EnvironmentName" {
    type = "string"
}
variable "tags" {
    type = "map"
    default = {
        Environment = "${var.EnvironmentName}"
        CostCentre = "C1234"
        Project = "TerraformTest"
        Department = "Systems"
    }
}

Variables-dev.tfvars:

EnvShortName = "Dev"
EnvironmentName = "Development1"
#Location
Location = "westeurope"

main.tf:

resource “azurerm_resource_group” “TestAppRG” {
    name = “EUW-RGs-${var.EnvShortName}”
    location = “${var.Location}”
    tags = “${var.tags}”
}

I am getting the following error:

Error: Variables not allowed on variables.tf line 18, in variable
“tags”: 18: Environment = “${var.EnvironmentName}”
Variables may not be used here.

I understand that the error message is fairly self explanatory and it is probably my approach that is wrong - but how do I use a variable in the definition of another variable map? is this even possible?

I will be standing up multiple resources - so want the tags to be built as a map and be passed into each resource - but I also want to recycle the map with other tfvars files to deploy multiple instances for different teams to work on.


Solution

  • Terraform does not support variables inside a variable. If you want to generate a value based on two or more variables then you can try Terraform locals.

    You can define the locals like this:

    locals {
      tags = {
        Environment = "${var.EnvironmentName}"
        CostCentre  = "C1234"
        Project     = "TerraformTest"
        Department  = "Systems"
      }
    }
    

    And then you can access them using local.tags:

    resource “azurerm_resource_group” “TestAppRG” {
      name     = “EUW-RGs-${var.EnvShortName}”
      location = “${var.Location}”
      tags     = “${local.tags}”
    }