Interpolation within a variable rather than a string

I’m trying to do something similar to the following snippet using a for_each:

locals {
  remote = [
    "alpha",
    "bravo",
    "charlie"
  ]
}

resource "aws_security_group_rule" "sg_rule" {
  for_each = toset(local.remote)

  type                     = "ingress"
  from_port                = 1000
  to_port                  = 1000
  protocol                 = "tcp"
  source_security_group_id = var.${each.value}
  security_group_id        = "sg-123456789"
}

Terraform doesn’t like this, if I cast var.${each.value} to a string this obviously doesn’t work either. Is this kind of interpolation just not possible? I’ve had a look through the docs and can’t see anything helpful.

Should this be raised as a feature request?

Hi @dan-lewis-j,

What you have here is not valid syntax, as we cannot re-evaluate interpolated strings in the configuration language.

What one would normally do in this situation, is supply a map from which you could lookup the desired values like:

source_security_group_id = local.security_group_ids[each.value]

The other approach is usually to shape the data in some way in which resources can get all the necessary information from the for_each values alone:

locals {
  remote = {
    alpha = "source_id_alpha"
    bravo = "source_id_bravo"
  }
}

resource "aws_security_group_rule" "sg_rule" {
  for_each = local.remote
  source_security_group_id = each.value
...
}

Yeah, this is what I ended up doing. Was just curious if there was a better way.

Thanks!