Updated on 2023-12-13 GMT+08:00

count

By default, only one resource is configured for a resource block of Terraform. When multiple same resources need to be created, configuring multiple independent resource blocks is redundant and difficult to maintain. You can use the count or for_each arguments to manage multiple identical resources in the same resource block. A given resource block cannot use both count and for_each. Example:

Three identical EVS disks are created based on the preceding configurations. In many cases, the provider requires that some arguments for creating resources be unique. You can use the count.index attribute (an index value starting from 0) to distinguish the arguments.

}

Two VPCs (myvpc_0 and myvpc_1) with the same CIDR value are created based on the preceding configuration. To modify the CIDR value, you can declare a string list to store the CIDR values of different VPCs, and then use count.index to access the list elements.

variable "name_list" {
  type    = list(string)
  default = ["vpc_demo1", "vpc_demo2"]
}
variable "cidr_list" {
  type    = list(string)
  default = ["192.168.0.0/16", "172.16.0.0/16"]
}

  count = 2
  name  = var.name_list[count.index]
  cidr  = var.cidr_list[count.index]
}

An index is required to access a resource created using count. The format is <Resource type>.<Name>[Index].

> huaweicloud_vpc.vpcs[0]

# ID for accessing the first VPC
> huaweicloud_vpc.vpcs[0].id

# ID for accessing all VPCs
> huaweicloud_vpc.vpcs[*].id