Skip to main content
In this guide, you’ll learn how to provision multiple EC2 instances with the count and for_each meta-arguments in OpenTofu. Both approaches let you duplicate a single resource block, but differ in indexing and lifecycle behavior.

1. Using count

The count meta-argument accepts an integer and creates that many instances of a resource.
Run:
Then verify:

Dynamic count with length()

Instead of hardcoding an integer, drive count from a list:
Here, each instance tag is assigned by its count.index:
  • count.index = 0Name = "web1"
  • count.index = 1Name = "web2"
  • count.index = 2Name = "web3"
Removing or reordering items in the webservers list causes all subsequent resources to be reindexed. This can lead to unintended in-place updates instead of only removing the orphaned resource.
Example plan when deleting "web1":

2. Using for_each

The for_each meta-argument uses a set or map, giving each resource a stable key based on its value.
Run and list state:
If you remove "web1" from the set and run tofu plan, only that resource is destroyed:
This ensures stable resource addressing and prevents unnecessary updates.

Watch Video