0
votes

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.


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\""
1

1 Answers

1
votes

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