0
0
TerraformHow-ToBeginner · 4 min read

How to Create Multiple Resources in Terraform Easily

To create multiple resources in Terraform, define multiple resource blocks or use for_each or count to loop over a list or map. This lets you efficiently manage many similar resources with less code.
📐

Syntax

Terraform creates resources using resource blocks. To create many similar resources, use count or for_each inside the resource block.

Parts explained:

  • resource: Defines the resource type and name.
  • count: Number of instances to create (simple list).
  • for_each: Loop over a map or set for named instances.
  • name: Unique identifier for each resource instance.
terraform
resource "aws_instance" "example" {
  count = 3

  ami           = "ami-12345678"
  instance_type = "t2.micro"
  tags = {
    Name = "example-${count.index}"
  }
}
💻

Example

This example creates three AWS EC2 instances using count. Each instance gets a unique name with its index.

terraform
provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "example" {
  count = 3

  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "example-instance-${count.index}"
  }
}
Output
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
⚠️

Common Pitfalls

Common mistakes when creating multiple resources include:

  • Using count with complex maps, which can cause confusion with indexes.
  • Not using unique names or keys, leading to resource conflicts.
  • Mixing count and for_each incorrectly.

Use for_each when you want to create resources with meaningful keys.

terraform
/* Wrong: Using count with map keys (causes errors) */
resource "aws_instance" "wrong" {
  count = length(var.instances)

  ami           = var.instances[count.index].ami
  instance_type = var.instances[count.index].type
}

/* Right: Using for_each with map keys */
resource "aws_instance" "right" {
  for_each = var.instances

  ami           = each.value.ami
  instance_type = each.value.type
}
📊

Quick Reference

FeatureUse CaseExample
resource blockCreate single resourceresource "aws_s3_bucket" "bucket" {}
countCreate multiple similar resources by numbercount = 3
for_eachCreate multiple resources with keysfor_each = {a=1, b=2}
count.indexIndex for count instances"name-${count.index}"
each.key / each.valueAccess keys and values in for_eachami = each.value.ami

Key Takeaways

Use multiple resource blocks or loops like count and for_each to create many resources.
Use count for simple repeated resources and for_each for keyed collections.
Always give unique names or keys to avoid conflicts.
Avoid mixing count and for_each in the same resource block.
Test your configuration with terraform plan before applying.