1

I am still getting used to using Terraform and have the following question.

I have an array in a TFVARS file; extproviders = [ "production" , "support" ]

i am using thisto call a module

module userpoolclientN {
   count = length(var.extproviders)
   source =  "../modules/cognito"
   basename = var.extproviders[count.index]
}

what i would like to do is create a new array that attaches 'odd' 'even' to each variable. I dont want the user to input this as the extproviders is used elsewhere in the code.

extproviders_new = [ "production_odd" ,"production_even" , "support_odd", "support_even" ]


module userpoolclientN {
   count = length(var.extproviders_new)
   source =  "../modules/cognito"
   basename = var.extproviders_new[count.index]
}

I am still learning Terraform, understand i cant use a for loop to accomplish this. Is there another way?

1
  • Would you consider updating the usage to for_each so that the for expression can be used directly as the module argument (also could then remove basename argument)? It would simplify and stabilize the usage and answer. Commented Dec 21, 2022 at 15:41

1 Answer 1

3

Using for and foreach :

variable "extproviders" {
  default = ["production", "support"]
}

locals {
  extproviders_new  = flatten([ for e in var.extproviders : tolist(["${e}odd","${e}even"])])
}


module userpoolclientN {
   for_each = toset(local.extproviders_new)
   source =  "../modules/cognito"
   basename = each.value
}

Explaining the locals :

For each element on the input list returns a list made of that element + odd suffix and element + even suffix. Then flatten those list into a single one

flatten() will transform multilevel lists into a single one

[for] will returns a list containing two lists

"${e}odd" and "${e}even" is a simple string concatenation

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.