Need five servers with the same configuration, or an IAM policy attachment only when a feature is enabled? Put `count` on a Terraform resource or module block. Its integer value tells Terraform how many instances to create: `5` creates five, while `0` creates none. section 4.8.1 section 4.1.5
Launch a requested number of servers
Declare a numeric `instance_count` input, validate that it is a nonnegative whole number, and set `count = var.instance_count` on `aws_instance`. Inside that resource block, use `count.index` in each Name tag. The index starts at zero, so a prefix such as `example` gives successive instances distinct names. Put `count` on the calling module instead if you want multiple instances of the entire module; put it on the resource when only that resource should multiply. section 4.1.3
Listing 4.7 Session manager
variable "enable_systems_manager" {
type = bool
description = "When enabled the Systems Manager IAM Policy will be
attached to the instance."
default = false
}
resource "aws_iam_role_policy_attachment" "ssm_attach" { #1
count = var.enable_systems_manager ? 1 : 0 #2
role = aws_iam_role.main.name
policy_arn = data.aws_iam_policy.ssm_arn.arn
}
#1 This resource will only create an attachment if enable_systems_manager is true.
#2 The count meta parameter lets us define how many resources to create. We switch between one and zero.
The session-manager configuration shows a boolean input converted to `1` or `0`, creating an IAM policy attachment only when the feature is enabled. section 4.1.5
Account for these behaviors when using `count`:
- `count.index` is available only inside the block that declares `count`. Outside it, access a counted resource or module by index, such as `aws_instance.main[0]`, or iterate over its instances. section 4.8.1 section 4.8.3
- A block can use `count` or `for_each`, not both. Use `count` when a number or a simple on/off choice expresses the requirement. section 4.8 section 4.8.1
- Terraform must know the count during planning to build its resource graph. A resource attribute available only after apply cannot determine it; an unavailable value causes a planning error. section 5.7.5
When a count depends on a value computed from a resource, look for an input that expresses the same decision. For example, decide whether to create an elastic IP from the supplied domain variable rather than from a DNS record resource attribute. This keeps the decision available when Terraform plans the instances, without splitting deployment into batches. section 5.7.5 section 4.8.4
