Get output value based on a variable

I have outputs in a module like:

ap_ACCOUNT_REGION_vpc, ap_ACCOUNT_eks_REGION_subnets

so in my code I’m trying to do:

vpc_id                         = module.ap-globals.ap_"${var.account}"_"${var.region}"_vpc
subnet_ids                     = module.ap-globals.ap_"${var.account}"_eks_"${var.region}"_subnets

But it’s not working.
Any suggestions on formatting this?

The source module for ap-globals doesn’t do anything other then have outputs of static ids.

Error is:

│ Error: Missing newline after argument
│
│   on eks.tf line 22, in module "eks":
│   22:   vpc_id                         = module.ap-globals.ap_"${var.account}"_"${var.region}"_vpc
│
│ An argument definition must end with a newline.

Hi @cdenneen,

You cannot interpolate references in Terraform, so there is no way to fix the formatting and make this work.

I can’t say exactly what your alternatives are without seeing the module call and output configuration, but the general idea would be to access the data via a map based on a string key.

If for example the module were expanded using for_each with the same values you are building as instance keys, then you would access the module instances using a string template for the key like so:

module.ap-globals["ap_${var.account}_${var.region}_vpc"]

The same technique would be applied if this is a single module and the outputs values are maps, you can only interpolate into a string to use as a map key, you cannot interpolate directly into a reference.

1 Like