Does terraform support looking up a value from a json file using the result of a lookup from another json file?

Viewed 1034

I have one environment specific json file e.g. prod.json that looks like this:

{
"subscription": "xxxxxx",
"tshirt_size": "large",
"env_prefix": "prod"

}

I have another global.json file that looks like this:

{
"tshirtsizes": {
    "small": {
        "vmcount": 1,
        "cpucount": 2,
        "memory": 4098
    },
    "medium": {
        "vmcount": 2,
        "cpucount": 2,
        "memory": 8196
    },
    "large": {
        "vmcount": 4,
        "cpucount": 2,
        "memory": 8196
    }

}

}

My terraform configuration needs to know the number of cpu's to use when creating a new vm resource. I want to use the 'tshirt-size' value from prod.json ('large') to lookup the appropriate 'cpucount' value from global.json. For example if I try this:

locals {
tshirtsize = jsondecode(file("prod.json")).tshirt_size
cpucount = jsondecode(file("global.json")).tshirtsizes.${tshirtsize}.cpucount

}

I get the following error:

    Error: Invalid character
  on main.tf line 30, in locals:
  30:   cpucount = jsondecode(file("global.json")).tshirtsizes${tshirtsize}.cpucount
This character is not used within the language

Error: Invalid attribute name
  on main.tf line 30, in locals:
  30:   cpucount = jsondecode(file("global.json")).tshirtsizes${tshirtsize}.cpucount
An attribute name is required after a dot.

Clearly trying to use interpolation like this is not supported (also tried in the resource itself). Does anyone know how this could be achieved? thanks

1 Answers

What you are doing tshirtsizes.${tshirtsize}.cpucount that is not valid syntax.
Here is how you do it:

variable "prod" {
  default = <<EOF
{
"subscription": "xxxxxx",
"tshirt_size": "large",
"env_prefix": "prod"
}
EOF
}

variable "global" {
  default = <<EOF
{
  "tshirtsizes": {
    "small": { "cpucount": 1 },
    "medium": { "cpucount": 2 },
    "large": { "cpucount": 3 }
  }
}
EOF
}

locals {
    tshirtsize = jsondecode(var.prod).tshirt_size
    cpucount   = jsondecode(var.global).tshirtsizes[local.tshirtsize].cpucount
}

output "cpucount" {
    value = local.cpucount
}


Related