New Terraform Tutorials on Count and For Each
Terraform provisions infrastructure with a declarative configuration language.
count
and for_each
allow you to provision multiple instances of infrastructure (either resources or entire modules) using a single block of configuration code.
» Learn to Use Count and For_Each By Example
Use both of these features through new hands-on tutorials on HashiCorp Learn.
- Use
count
to flexibly scale EC2 instances in a VPC. - Building on that example, use
for_each
to provision entire duplicate VPCs for multiple projects.
» Use Count to Provision Multiple Resources
When using count
, Terraform will replicate the given resource a specified number of times. The following example will provision two similar instances using the same block of configuration.
You can also use a variable to define the number of resources provisioned with count
, making the configuration even more flexible.
» Use For Each For More Flexible Configuration
Like count
, for_each
will provision multiple resources, but instead of using an integer to define the number of resources, for_each
uses a data structure, creating one copy of the given resource for each item in the data structure. This allows you to configure the individual resources in more complex ways. The following configuration will provision a VPC for each element in the map called project
, each with a configurable number of public and private subnets.
Together, these two features allow you to configure duplicate resources of the same type while maintaining the simplicity of Terraform’s declarative configuration language.
With the recent release of Terraform 0.13, Terraform supports both of these features with modules as well as resources. Try these and other 0.13 tutorials on HashiCorp Learn.
Sign up for the latest HashiCorp news
More blog posts like this one
New Terraform integrations with Crowdstrike, Datadog, JFrog, Red Hat, and more
12 new Terraform integrations from 9 partners provide more options to automate and secure cloud infrastructure management.
Terraform delivers launch-day support for Amazon S3 Tables, EKS Hybrid Nodes, and more at re:Invent
The Terraform provider for AWS now enables users to manage a variety of new services just announced at re:Invent.
HashiCorp at re:Invent 2024: Infrastructure Lifecycle Management with AWS
A recap of HashiCorp infrastructure news and developments on AWS from the past year, from a new provider launch to simplifying infrastructure provisioning and more.