Iterators
Iterators let you loop over a collection of values. You can use them to create multiple resources of the same type based on dynamic data that is only known at runtime.
When to Use Iterators
Use iterators when you need to reference dynamic data that is not known until after Terraform applies a configuration. For example, instance IDs that cloud providers assign on creation.
When data is static or you know the values before synthesizing your code, we recommend using loops in your preferred programming language.
Define Iterators
Import the TerraformIterator
class and call the .fromList()
or .fromMap()
static method. Then use the forEach
property to pass the iterator to a resource, data source, or module. This lets you use the iterator in attributes.
The following example uses an iterator to create a unique name for each new S3 bucket.
You cannot access the index of items when iterating over lists. This is because CDKTF implicitly converts lists to sets when iterating over them, but Terraform requires sets for iteration. This behavior prevents Terraform from accidentally deleting and recreating resources when their indices change. If you need an index, use an escape hatch with the count.index
property.
Using Iterators on Complex Types
The iterator also exposes methods to access nested attributes. The following example uses the getString
and getStringMap
methods to access the name
and tags
attributes of each list item.
Using Iterators for List Attributes
You can also use iterators to create a list of objects based on each item in a list and assign the result as a value to a property of a resource. This is equivalent to using Array.map
in TypeScript and using dynamic blocks in a Terraform HCL configuration.
Use iterators for list attributes if the length of the list is not known before deploying. Otherwise, use native functions that are available in your language (e.g., Array.map
in TypeScript).
The following examples use an iterator to create a team containing each member of an organization.
Using Count
You can also use the TerraformCount
class to achieve the equivalent of setting count
on resources in HCL Terraform. Refer to the Terraform docs for more information on the count meta argument.
This is useful when there's a numeric value that is only known at runtime that affects the amount of resources that should be created and those resources are almost identical. For most cases, however, Iterators are preferred over count
. Refer to the Terraform docs for the underlying reasons.
The following examples use TerraformCount
to create a specific amount of instances that is defined via a Terraform variable.