count
Use the count meta-argument to create multiple instances of a resource or module from a single block.
Overview
By default, a resource block provisions one infrastructure object, and a module block instantiates one copy of its child configuration. To provision multiple similar objects without duplicating blocks, use the count or for_each meta-argument.
count accepts a non-negative integer. When present in a resource or module block, Terraform creates that many independent instances — each provisioned, updated, and destroyed separately. The simplest way to replicate nearly identical infrastructure is count: server clusters, matched storage buckets, or uniform network components.
Note that the same resource or module block cannot use count and for_each at the same time.
Syntax
count is a meta-argument defined by Terraform and is supported by all resource types and modules.
Its value must be a whole number known before Terraform contacts any remote API. Each instance gets a unique infrastructure object that is created, updated, and destroyed independently.
Usage
resource "alicloud_instance" "server" {
count = 4 # Create four similar ECS instances.
instance_name = "server-${count.index}"
instance_type = "ecs.s6-c1m2.small"
image_id = "aliyun_2_1903_x64_20G_alibase_20230523.vhd"
vswitch_id = "vsw-abc123456"
security_groups = ["sg-abc123456"]
tags = {
Name = "Server ${count.index}"
}
}
Tip: Setcountto0or1to toggle a resource on or off based on a condition — for example,count = var.create_slb ? 1 : 0. See Create resources based on conditions for a full example.
count object
Inside a block that uses count, expressions can reference the count object. It exposes one attribute:
count.index: The zero-based index of the current instance (0, 1, 2, ...).
Use expressions in the count argument
count supports numeric expressions, but the resulting value must be known before Terraform performs any remote resource operations. This means count cannot reference attributes determined during apply — such as unique IDs generated by a remote API when an object is first created.
Reference instances
When count is set, Terraform distinguishes between the block itself and the individual instances it creates. Instances are addressed by zero-based index.
Use
<TYPE>.<NAME>ormodule.<NAME>to reference the entire resource block. Example:alicloud_instance.server.Use
<TYPE>.<NAME>[<INDEX>]ormodule.<NAME>[<INDEX>]to reference a single instance. Examples:alicloud_instance.server[0]andalicloud_instance.server[1].
Resources and modules without count or for_each are referenced by name alone, with no index.
When child module instances output values or display UI elements, each module address is prefixed with module.<NAME>[<KEY>]. Modules without count or for_each use a plain module.<NAME> address.
Note that in a nested provisioner or connection block, the current resource instance is referenced by a special self object, instead of the entire resource block.
Examples
Create multiple ECS instances
resource "alicloud_instance" "web_servers" {
count = 3
instance_name = "web-server-${count.index + 1}"
instance_type = "ecs.s6-c1m2.small"
image_id = "aliyun_2_1903_x64_20G_alibase_20230523.vhd"
vswitch_id = "vsw-abc123456"
security_groups = ["sg-abc123456"]
system_disk_category = "cloud_efficiency"
system_disk_size = 40
tags = {
Name = "WebServer-${count.index + 1}"
Role = "web"
Stage = "production"
}
}
Create multiple OSS buckets
variable "bucket_names" {
description = "List of bucket name prefixes"
type = list(string)
default = ["logs", "backups", "configs"]
}
resource "alicloud_oss_bucket" "buckets" {
count = length(var.bucket_names)
bucket = "${var.bucket_names[count.index]}-${random_id.suffix.hex}"
acl = "private"
tags = {
Name = var.bucket_names[count.index]
Environment = "Production"
}
}
resource "random_id" "suffix" {
byte_length = 4
}
Create resources based on conditions
Set count to 0 or 1 using a conditional expression to make a resource optional:
variable "create_slb" {
description = "Whether to create SLB"
type = bool
default = true
}
resource "alicloud_slb_load_balancer" "app" {
# Create the resource only when create_slb is set to true.
count = var.create_slb ? 1 : 0
load_balancer_name = "app-lb"
address_type = "internet"
load_balancer_spec = "slb.s2.small"
tags = {
Name = "ApplicationLB"
}
}
Use count in a module
variable "enable_high_availability" {
description = "Whether to deploy in high availability mode with multiple zones"
type = bool
default = false
}
module "primary_zone" {
source = "./modules/zone_deployment"
zone_id = "cn-hangzhou-h"
# Other configurations.
}
module "secondary_zone" {
source = "./modules/zone_deployment"
# The resource is deployed in the second zone only when high availability is enabled.
count = var.enable_high_availability ? 1 : 0
zone_id = "cn-hangzhou-i"
# Other configurations.
}
How to choose between count and for_each
Use count when instances are nearly identical and their differences can be expressed as an integer index. Use for_each when instances need distinct values that cannot be derived from an integer.
A common pattern before for_each was available: derive the count from a list length and use count.index to look up each value.
variable "vswitch_ids" {
type = list(string)
}
resource "alicloud_instance" "server" {
# Create an instance for each vSwitch.
count = length(var.vswitch_ids)
instance_name = "server-${count.index + 1}"
instance_type = "ecs.s6-c1m2.small"
image_id = "aliyun_2_1903_x64_20G_alibase_20230523.vhd"
vswitch_id = var.vswitch_ids[count.index]
tags = {
Name = "Server ${count.index + 1}"
}
}
This pattern has a known limitation: instances are identified by index, not by the string values in the list. If you remove an element from the middle of the list, every instance after that position detects a change in its vswitch_id value — causing more resource replacements than intended. for_each avoids this by keying instances on the actual string values.
Best practices
Use variables for count values — avoid hardcoding integers. Use input variables so that the number of instances can be adjusted without modifying the resource block.
Use
for_eachfor non-identical instances — if instances need distinct attribute values that cannot be derived from an integer index,for_eachis the safer choice.Prefer
for_eachfor list-driven resources — index-based addressing causes unexpected replacements when list elements are inserted or removed. Keyed addressing withfor_eacheliminates this churn.Review the plan before applying — when changing
count, runterraform planto confirm which instances will be added, changed, or destroyed before applying.-
Understand instance dependencies — resources created with
countshare the same configuration block. A dependency on one instance applies to all instances from that block.This topic is developed based on the Terraform document The count Meta-Argument . You can read the Terraform document for more details.