For-each over module

Looking for advise as to the best way to handle this. I’m creating a module that creates a documentDB database instance, and want to to use for-each or count to support creating several DB instances from a structure like this in the terragrunt.hcl file. I’m not sure if nodes should be a list(map(string)) or do it as a map(map(string)

inputs = {
nodes = [
{
cluster_identifier = “foo”
master_username = “foo”
master_password = “insecure”
backup_rention_period = 30
preferred_backup_window = “07:00-09:00”
}
{
cluster_identifier = “bar”
master_username = “fooo”
master_password = “insecure”
backup_rention_period = 30
preferred_backup_window = “07:00-09:00”
}
]
}

On the module side, trying to do something like this:

for_each = var.nodes

cluster_identifier = each.value.cluster_identifier
master_username = each.value.master_username
master_password = each.value.master_password
backup_retention_period = each.value.backup_rention_period
preferred_backup_window = each.value.preferred_backup_window
skip_final_snapshot = true

This isn’t working. I’d appreciate and feedback on what approach should be done to support this, I can see several cases where this would be useful.

Hi @BrianW

Can you elaborate on “This isn’t working”? What error messages (if any) are you getting? As far as I know, this should work if you are using Terraform 0.13.

If you are using Terraform 0.13, my guess is that the issue is probably a type issue, where you are using a list of objects for the for_each argument instead of a map. See the official docs for more info on this.

Hope this helps!
- Yori

Thanks for responding, it was a type issue. I ended up using:
type = map(map(string)) which made things works with an input

nodes = {
prod = {
name = “oracle-prod”
instance_type = “cache.t3.medium”

}

One thing that doesn’t work, is having mixed types in the input, for example, I’d like to also have:

inputs
nodes = {
prod = {
name = “oracle-prod”
instance_type = “cache.t3.medium”
allowed_security_groups = [ “sg1”,“sg2”]
}}

but terraform errors with “The environment variable TF_VAR_nodes does not contain a valid value for
variable “nodes”: element “prod”: element “allowed_security_groups”: string
required.”

I’m assuming this is because of the map(map(string)) type.

If you don’t have any optional keys, you can use the object type to solve this:

type = map(object({
  name = string
  instance_type = string
  allowed_security_groups = list(string)
}))