Reputation: 97
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:
size = local.$var.define_size.volume_gb
. Obvious bad syntax results in "Error: Invalid character." and "Error: Invalid attribute name" referring to the $ character.size = local.${var.define_size}.volume_gb
. Obvious bad syntax results in "Error: Invalid character." and "Error: Invalid attribute name" referring to the $ character.size = "${local[var.define_size].volume_gb}"
. "Error: Invalid reference. A reference to a resource type must be followed by at least one attribute access, specifying the resource name."size = tostring("local.${var.define_size}.volume_gb")
this renders correctly but as a string and not a resource reference "local.large.volume_gb"
format("%#v",tostring("local.${var.define_size}.volume_gb"))
this renders partially correctly but as string with escape characters and not resource "\"local.large.volume_gb\""
Upvotes: 2
Views: 5804
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
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