Trying to implement for_each in module, just get an error

Hello

So I have started to explore Terraform.
And so far Im able to spin up some vms in Azure.

Now I am looking at the for_each option, in the module section.
I have tried to implement this in my exising code, but just get an error.
So, I found a example , and tried that:

module "bucket" {
  for_each = toset(["assets", "media"])
  source   = "./modules/architect"
  name     = "${each.key}_bucket"
}

Alsto here I get the same error:

Error: Unsupported argument

on main.tf line 4, in module “bucket”:
4: name = “${each.key}_bucket”

An argument named “name” is not expected here.

What is wrong here, am i missingg somthing?

Hi @nafstad,

This error message means that there’s no variable "name" block declared in the ./modules/architect module, and so therefore Terraform doesn’t expect to find an argument called name in that module block.

The for_each part of this seems to be working as you wanted, at least as far as I understand what you wanted, so I think you could get past this error by adding a new variable declaration to your child module to accept the name you are passing in:

variable "name" {
  type = string
}

Elsewhere in that child module you can then use var.name to refer to the string that’ll be either "assets_bucket" or "media_bucket" depending on which instance of the module is being evaluated.

1 Like

Hello,

Thanks, that was just what I as missing :slight_smile: