seafre
seafre

Reputation: 97

Terraform interpolation of locals map with key defined in a variable

Terraform interpolation of locals map with key defined in a variable

Objective: Define preset sizing labels in variable, provisioning of resources uses preset values from locals map variable


var "define_size" {
  description = "Select either small, medium, large"
  default = "large"
}


locals {

  small = {
    volume_gb = 1
    volume_count = 1
  }

  medium = {
    volume_gb = 20
    volume_count = 5
  }

  large = {
    volume_gb = 500
    volume_count = 10
  }

}


resource "aws_ebs_volume" "example" {
  availability_zone = var.availability_zone
  size              = ??????
}

Attempts:

Upvotes: 2

Views: 5804

Answers (2)

Minh Chau
Minh Chau

Reputation: 111

Thanks @Luk2302 for the answer, I was also looking this. I cannot comment so I create another answer. For my case, I read a list from json file, and then depend on the env, it will get the correct value.

power.json

[
  {
    "name": "a",
    "power": {
      "dev" : 1,
      "sit" : 2,
      "uat" : 3,
      "prod" : 4
    }
  }
]

In the tf file, I use as below

locals {
  power = jsondecode(file("power.json"))
}

resource "aws_example" "power" {
  count = length(local.power.*.name)
  power = local.power[count.index].power[var.env]
}

Depending on the input var.env, the "power" will have value 1, 2, 3, or 4

Upvotes: 0

luk2302
luk2302

Reputation: 57184

If you want key-based access you should make the locals definition something that works with keys, e.g. a map:

locals {
  sizes = {
    small = {
      volume_gb = 1
      volume_count = 1
    }
    medium = {
      volume_gb = 20
      volume_count = 5
    }
    large = {
      volume_gb = 500
      volume_count = 10
    }
  }
}

and then access that using local.sizes[var.define_size].volume_gb

Upvotes: 4

Related Questions