Deploying Multiple Resources (AWS EC2 Instances) at Once with Terraform using Count and For_Each

By Łukasz Kallas
Picture of the author
Published on
terraform image

In this post, we’ll look at how to deploy multiple EC2 instances using Terraform’s count and for_each features. This is useful when you need to create a scalable and flexible infrastructure.

Deploying EC2 Instances with Count

Terraform's count is a simple way to create multiple resources with the same configuration. Here’s how you can use it:

variable "ec2_count" {
  default = 2
}

resource "aws_instance" "ec2_count" {
  count         = var.ec2_count
  ami           = var.ec2_ami
  instance_type = var.ec2_instance_type
  subnet_id     = aws_subnet.private_subnet_1.id
}

Deploying EC2 Instances with For_Each

for_each provides more control and allows you to define resources with different configurations or unique attributes. Here’s how to deploy instances using for_each:

variable "ec2_foreach" {
  default = {
    "instance1" = {
      "instance_type" = "t2.micro"
    }
    "instance2" = {
      "instance_type" = "t3.micro"
    }
  }
}

resource "aws_instance" "ec2_foreach" {
  for_each      = var.ec2_foreach
  ami           = var.ec2_ami
  instance_type = each.value.instance_type
  subnet_id     = aws_subnet.private_subnet_1.id
  tags = {
    Name = each.key
  }
}

Stay Tuned

Want to learn?
The best articles, links and news related to software development delivered once a week to your inbox.