Skip to main content
Knowledge Base

Using for_each to call a module multiple times

Answer

So I am a little bit confused on using for_each with terragrunt, as there appears to be some documentation regarding it, but much of it is not really relevant for terragrunt as it's implied to be used for terraform. So, for example, if I wanted to create multiple ec2 instances using terragrunt, I would have to create a separate directory for each instance and within that directory would be a terragrunt.hcl file ``` ├── environments │ ├── dev │ │ ├── instance01 | | | └────terragrunt.hcl │ │ ├── instance02 | | | └────terragrunt.hcl │ │ ├── instance03 | | | └────terragrunt.hcl ``` This works but is not the most efficient. So onto for_each... I tried the following code in to see if I can use for_each to create multiple instances within the same terragrunt.hcl file, but it won't work. ``` locals { environment_vars = read_terragrunt_config(find_in_parent_folders("env.hcl")) env = local.environment_vars.locals.environment project_vars = read_terragrunt_config(find_in_parent_folders("project.hcl")) project = local.project_vars.locals.project_name application = local.project_vars.locals.application_name } include { path = find_in_parent_folders() } terraform { source = "git::https://github.com/terraform-aws-modules/terraform-aws-ec2-instance.git?ref=v4.0.0" for_each = toset(["one", "two", "three"]) } inputs = { name = "${local.project}-${local.application}-${local.env}-${each.key}" . . . ``` The aws module above does support using for_each. So, is the only way to use for_each with terragrunt at the moment is to write a local wrapper module which then calls the underlying was module multiple times, and reference the local module in your terragrunt.hcl file? Anton Babenko has a video doing similar here. https://www.youtube.com/watch?v=j4qoL0B-yIY Code here https://github.com/terraform-aws-modules/terraform-aws-s3-bucket/tree/master/wrappers#usage-with-terragrunt Or is there some other way I can call a module multiple times from within a terragrunt.hcl file? --- <ins datetime="2022-05-11T18:08:59Z"> <p><a href="https://support.gruntwork.io/hc/requests/108579">Tracked in ticket #108579</a></p> </ins>

This is unfortunately not supported in `terragrunt`. The only way to do this is to create a `terraform` module that implements the `for_each` call on the module, and have Terragrunt call that root Terraform module. Anton's example is actually using [a wrapper script](https://gist.github.com/antonbabenko/d77f8cf8bf891e589a6b5b0ab0e773ae) that generates this wrapper Terraform module that implements the `for_each` call.