Terraform — Using Modules Multiple Times

Semih Üstündağ
1 min readJan 4, 2021

Imagine you need to create multiple instances with each different AMI, instance type, AZ etc. One way to achieve this is having multiple aws_instance resource with each different configuration. With this approach, you only write repetitive code which is not ideal. To not repeat ourselves, we can use for_each property.

To use for_each with modules, you need to have minimum version of Terraform 0.13

In our modules/ec2/main.tf file we have a simple instance definition. Instead of using hard-coded values, we will use parameters.

resource "aws_instance" "web_server" {
ami = var.ami_id
instance_type = var.instance_type
key_name = var.key_name
availability_zone = var.availability_zone
}

Now we need to define a map for configuration in the main variables.tf file.

variable config {
description = "Config for EC2 instances"
type = map
default = {
web1 = {
ami = "ami_id_1"
instance_type = "t2.medium"
key_name = "var.key_name"
availability_zone = "eu-west-1a"
},
web2 = {
ami = "ami_id_2"
instance_type = "t2.large"
key_name = "key_web2"
availability_zone = "eu-west-1b"
}

We can now use for_each object in our main.tf file. This way, we map each key to its value.

module "ec2" {
source = "./modules/ec2"

for_each = var.config

record = each.value.record
ami = each.value.ami
instance_type = each.value.instance_type
key_name = each.value.key_name
availability_zone = each.value.availability_zone
}

--

--