Getting stuck with complex object manipulation

Very new to Terraform and getting stuck extracting output values to be used as input to another AWS resource I’m building.

I have the follow variable that is populated by the output value from a module.
So this works fine - I just need to get the “scope_name” values as a list of strings. Any help will be greatly appreciated.

My variable contents look like this:

ResourceServerScopes = [
{
“scope_description” = “AGENT_APP Role”
“scope_name” = “AGENT_APP”
},
{
“scope_description” = “BACKEND Role”
“scope_name” = “BACKEND”
},
{
“scope_description” = “SELPAL_APP Role”
“scope_name” = “SELPAL_APP”
},
{
“scope_description” = “STEWARD_BANK Role”
“scope_name” = “STEWARD_BANK”
},
]

Hi @kappaj2,

I’m not sure I fully understand the context for your question, but it sounds like you have a child module with a variable declaration like this:

variable "ResourceServerScopes" {
  type = list(object({
    scope_name        = string
    scope_description = string
  }))
}

…and inside that module you want to transform that value into a list of the values from scope_name.

If I’ve understood that correctly, then you can use splat expressions as a concise way to express this common sort of transform:

var.ResourceServerScopes[*].scope_name

As mentioned in the documentation, this special [*] syntax is a shorthand for the more general for expression language feature, so the above is equivalent to the following:

[for s in var.ResourceServerScopes : s.scope_name]

Hopefully that’s the result you were looking for!


While it doesn’t affect the result, please note that idiomatic Terraform style is to name all Terraform-specific identifiers such as variable names in lower case with underscores separating words, like this:

variable "resource_server_scopes" {
  type = list(object({
    scope_name        = string
    scope_description = string
  }))
}

Following that naming scheme isn’t required, but it will make your module fit in better with the names used in the official Terraform providers and with any third-party modules you might use elsewhere in your configuration.

1 Like

Thank you very much for the answer. Going to have a look at it right now.
Also thank you for the naming convention - old Java naming habit. Will update my templates accordingly.

@apparentlymart
Works like a dream . Thank you for taking the time to help with such a detailed explanation. Really appreciate!