For-Each in Modules

In this section I will create an example module and use for-each in it.

Let's start by creating a file with the name ssm-parameter\variables.tf,

variable "name" {}
variable "value" {}

Then a file with the name ssm-parameter\ssm-parameter.tf,

resource "aws_ssm_parameter" "parameter" {
  name  = var.name
  type  = "String"
  value = var.value
}

In here, the ssm_parameter resource expects name and a value to be available in variables. Our target is to provide these to this module using a for-each loop. Because iterating over a list of key values is much easier than repeating multiple times.

Next a file with the name ssm-parameter\outputs.tf,

output "arn" {
  value = aws_ssm_parameter.parameter.arn
}

Then let's create a file with the name provider.tf in our project root to consume the module we just created,

provider "aws" {
  region = "eu-west-1"
}

Finally a file with the name parameters.tf,

In here, we first define a some static locals. Inside the module "parameters" we iterate over each local key value and pass that value to our other module 'ssm-parameter'.

Last updated

Was this helpful?