When to use count and when to use for_each in Terraform, why removing an item from a count list destroys the wrong resources, the plan-time rule for for_each keys, how to convert count to for_each without recreating anything, and how resources declared in application code avoid index addressing.

count and for_each both turn one resource block into many, and in a small config the choice looks like style. It stops being style when someone deletes the second entry from a list of five queues and the plan wants to destroy three of them, since count addresses instances by position and every later index moved up by one.
This guide compares the two, with the plan-time rule for for_each and a safe conversion.
Both are meta-arguments that work on resources and, since Terraform 0.13, on modules, and a single block can use one or the other but not both. The count docs themselves point to for_each when instances are not almost identical.
Here is a list of queues created with count:
variable "queues" {
default = ["emails", "invoices", "exports", "webhooks"]
}
resource "aws_sqs_queue" "jobs" {
count = length(var.queues)
name = "acme-${var.queues[count.index]}"
}
State records the queues as jobs[0] to jobs[3]. Remove "invoices" from the list, and jobs[1] is now exports and jobs[2] is webhooks. SQS queue names cannot be changed in place, so the plan replaces jobs[1] and jobs[2] and destroys jobs[3], which deletes the messages waiting in the exports and webhooks queues along with the one you meant to drop. The same happens to any resource whose name or identity depends on the list position, and the plan output only shows it if you read every line.
With for_each, the key is the address, so the same change touches one queue:
variable "queues" {
type = map(object({
visibility_timeout = number
}))
default = {
emails = { visibility_timeout = 30 }
invoices = { visibility_timeout = 120 }
exports = { visibility_timeout = 900 }
webhooks = { visibility_timeout = 60 }
}
}
resource "aws_sqs_queue" "jobs" {
for_each = var.queues
name = "acme-${each.key}"
visibility_timeout_seconds = each.value.visibility_timeout
}
Removing invoices from the map plans one destroy, aws_sqs_queue.jobs["invoices"], and the other three keep their addresses. The map also gives each queue its own settings without a parallel list of timeouts that has to stay in the same order, which is where count configs usually grow their second bug. Other resources reference an instance by key, such as aws_sqs_queue.jobs["exports"].arn, which reads better in review than an index.
count is the simplest way to make a resource optional. A boolean variable turns it into zero or one instance, and references use [0] or one() to read it:
resource "aws_cloudwatch_metric_alarm" "dlq_depth" {
count = var.enable_alarms ? 1 : 0
alarm_name = "acme-dlq-not-empty"
namespace = "AWS/SQS"
metric_name = "ApproximateNumberOfMessagesVisible"
dimensions = { QueueName = aws_sqs_queue.dlq.name }
statistic = "Maximum"
period = 300
evaluation_periods = 1
threshold = 0
comparison_operator = "GreaterThanThreshold"
}
output "dlq_alarm_arn" {
value = one(aws_cloudwatch_metric_alarm.dlq_depth[*].arn)
}
It also fits a fixed number of interchangeable copies, such as three identical worker instances behind a load balancer, where it does not matter which one is [2]. Once the copies get names, per-copy settings or a list that people edit, switch to for_each.
Terraform needs the full set of instance addresses during plan to compare them with state, so the keys of a for_each cannot depend on values that only exist after apply. Passing a set of generated IDs, such as toset(aws_subnet.private[*].id) in the same run that creates the subnets, fails with "The for_each value depends on resource attributes that cannot be determined until apply", as the for_each docs describe.
The fix is to key by something you chose and keep the computed value inside the map:
locals {
azs = ["eu-central-1a", "eu-central-1b"]
}
resource "aws_subnet" "private" {
for_each = toset(local.azs)
vpc_id = aws_vpc.main.id
availability_zone = each.key
cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 4, index(local.azs, each.key))
}
resource "aws_route_table_association" "private" {
for_each = aws_subnet.private
subnet_id = each.value.id
route_table_id = aws_route_table.private.id
}
The second resource iterates over the first resource's instances, whose keys are the availability zone names from local.azs, so the keys are known even though the subnet IDs are not. Sets passed to for_each must be sets of strings, and lists need toset() first, which also removes duplicates silently.
Changing count to for_each changes every instance address, so on its own the plan destroys jobs[0] and creates jobs["emails"]. A moved block per instance tells Terraform that the old address and the new one are the same object:
moved {
from = aws_sqs_queue.jobs[0]
to = aws_sqs_queue.jobs["emails"]
}
moved {
from = aws_sqs_queue.jobs[1]
to = aws_sqs_queue.jobs["invoices"]
}
moved {
from = aws_sqs_queue.jobs[2]
to = aws_sqs_queue.jobs["exports"]
}
moved {
from = aws_sqs_queue.jobs[3]
to = aws_sqs_queue.jobs["webhooks"]
}
Run terraform plan and check that it reports four moves and zero changes before you apply. Keep the blocks in the config until every workspace and every consumer of a shared module has applied them, as the moved block guide covers in more detail. On Terraform versions before 1.1, the same result takes one terraform state mv per instance, run by hand against each state.
Encore brings infrastructure from code, and each queue, database or bucket is a declaration in the service that uses it, identified by the name you give it. Topics and buckets must be declared as package level variables and cannot be created inside functions or loops, so there is no index for a resource to shift to, and removing one is a deleted declaration that shows up in the diff of the file that used it.

Run in your terminal to get started locally.
The four job queues from the Terraform example become topics with their own subscription settings, the equivalent of the per-key visibility timeouts in the map:
// jobs/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("jobs");
Each topic is declared once, by name:
// jobs/topics.ts
import { Topic, Subscription } from "encore.dev/pubsub";
import log from "encore.dev/log";
interface Job {
jobID: string;
payload: Record<string, string>;
}
export const emailJobs = new Topic<Job>("emails", { deliveryGuarantee: "at-least-once" });
export const exportJobs = new Topic<Job>("exports", { deliveryGuarantee: "at-least-once" });
export const webhookJobs = new Topic<Job>("webhooks", { deliveryGuarantee: "at-least-once" });
const _emails = new Subscription(emailJobs, "send-email", {
ackDeadline: "30s",
handler: async (job) => {
log.info("sending email", { jobID: job.jobID });
},
});
const _exports = new Subscription(exportJobs, "build-export", {
ackDeadline: "15m",
maxConcurrency: 2,
handler: async (job) => {
log.info("building export", { jobID: job.jobID });
},
});
const _webhooks = new Subscription(webhookJobs, "deliver-webhook", {
ackDeadline: "1m",
retryPolicy: { maxRetries: 10 },
handler: async (job) => {
log.info("delivering webhook", { jobID: job.jobID });
},
});
The invoices queue that was removed in the Terraform example is not declared, and the other three keep their names. On deploy to AWS, Encore provisions an SNS topic for each topic and an SQS queue with a dead-letter queue for each subscription, and an IAM role for the service, or a service account on GCP, as the AWS infrastructure docs describe. For removed stateful resources, the managing infrastructure docs state that Encore never deletes databases, buckets or queues unless they are unused and a user has confirmed the deletion. encore run runs the topics and subscriptions locally, so a handler can be tested before deploying.
When the instances are per tenant or per customer, a resource per key is usually the wrong shape in either tool. One bucket with a key prefix per tenant, or one topic with a tenant field in the message, scales to new tenants with no infrastructure change at all.
An agent asked to add a "reports" queue writes one more Topic and Subscription in the same file and tests it with encore run, with no map variable or address to keep in sync.
Best fit: Teams whose for_each maps mostly hold application queues and buckets, and who want those declared next to the handlers with each one named in the code.
count for optional resources (var.enabled ? 1 : 0) and truly identical copies.for_each with a map when instances have names or their own settings.for_each by values known at plan time, and keep computed attributes in the map values.count resources with one moved block per index, and check for zero changes.count.count creates a number of copies addressed by index, such as aws_sqs_queue.jobs[0], while for_each creates one instance per key of a map or set, such as aws_sqs_queue.jobs["emails"]. With for_each, adding or removing one key only touches that instance, and with count, removing an item from the middle shifts every later index.
Use count for a resource that is either created or not, with count = var.enabled ? 1 : 0, and for truly identical copies where the index has no meaning. Use for_each whenever each instance has its own name or settings.
for_each keys must be known during plan, so they cannot come from an attribute that only exists after apply, such as a generated ID. Build the keys from input variables or static values, and put the computed attributes in the map values instead.
Change the resource to for_each and add a moved block for each existing index, for example from = aws_sqs_queue.jobs[0] and to = aws_sqs_queue.jobs["emails"]. Terraform 1.1 and later then updates the state addresses instead of planning a destroy and create.
Yes. Encore deploys topics and buckets declared in application code to your own AWS or GCP account, with each resource named in the service. Shared foundations such as a VPC can stay in Terraform.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.