Find the Best Cosmetic Hospitals

Explore trusted cosmetic hospitals and make a confident choice for your transformation.

“Invest in yourself — your confidence is always worth it.”

Explore Cosmetic Hospitals

Start your journey today — compare options in one place.

Terraform Tutorials: How to do Loop / Iterate in Terraform?

Resources
Resources are the most important element in the Terraform language. Each resource block describes one or more infrastructure objects, such as virtual networks, compute instances, or higher-level components such as DNS records supported by providers.

Resources type
Each resource is associated with a single resource type, which determines the kind of infrastructure object it manages and what arguments and other attributes the resource supports.

Provider
Each resource type in turn belongs to a provider, which is a plugin for Terraform that offers a collection of resource types. A provider usually provides resources to manage a single cloud or on-premises infrastructure platform.

Resource Behavior by Meta-Arguments
Resource Behavior by Meta-Arguments, which can be used with any resource type to change the behavior of resources:

  • depends_on, for specifying hidden dependencies
  • count, for creating multiple resource instances according to a count
  • for_each, to create multiple instances according to a map, or set of strings
  • provider, for selecting a non-default provider configuration
    lifecycle, for lifecycle customizations
  • provisioner and connection, for taking extra actions after resource creation

count: which allows Multiple Resource Instances By Count

Out of these, count: which allows Multiple Resource Instances By Count and this Meta-Arguments can be used to Multiply resources which can be used as an alternative to Looping and Interators in Terraform.


resource "aws_instance" "example" {
  ami = "ami-2d39803a"
  instance_type = "t2.micro"
}

###### WRONG WAY ###### 
for i = 0; i < 3; i++ {
  resource "aws_instance" "example" {
    ami = "ami-2d39803a"
    instance_type = "t2.micro"
  }  
}

###### RIGHT WAY ###### 
resource "aws_instance" "example" {
  count = 3
  ami = "ami-2d39803a"
  instance_type = "t2.micro"
}Code language: PHP (php)

for_each: Multiple Resource Instances Defined By a Map, or Set of Strings.

If your resource instances are almost identical, count is appropriate. If some of their arguments need distinct values that can’t be directly derived from an integer, it’s safer to use for_each.

Before for_each was available, it was common to derive count from the length of a list and use count.index to look up the original list value:


variable "subnet_ids" {
  type = list(string)
}

resource "aws_instance" "server" {
  # Create one instance for each subnet
  count = length(var.subnet_ids)

  ami           = "ami-a1b2c3d4"
  instance_type = "t2.micro"
  subnet_id     = var.subnet_ids[count.index]

  tags {
    Name = "Server ${count.index}"
  }
}Code language: PHP (php)

The for_each meta-argument accepts a map or a set of strings, and creates an instance for each item in that map or set. Each instance has a distinct infrastructure object associated with it (as described above in Resource Behavior), and each is separately created, updated, or destroyed when the configuration is applied.


resource "azurerm_resource_group" "rg" {
  for_each = {
    a_group = "eastus"
    another_group = "westus2"
  }
  name     = each.key
  location = each.value
}
Code language: JavaScript (javascript)

More reading can be done here

https://www.terraform.io/docs/configuration/resources.html#for_each-multiple-resource-instances-defined-by-a-map-or-set-of-strings

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals
I’m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I have worked at <a href="https://www.cotocus.com/">Cotocus</a>. I share tech blog at <a href="https://www.devopsschool.com/">DevOps School</a>, travel stories at <a href="https://www.holidaylandmark.com/">Holiday Landmark</a>, stock market tips at <a href="https://www.stocksmantra.in/">Stocks Mantra</a>, health and fitness guidance at <a href="https://www.mymedicplus.com/">My Medic Plus</a>, product reviews at <a href="https://www.truereviewnow.com/">TrueReviewNow</a> , and SEO strategies at <a href="https://www.wizbrand.com/">Wizbrand.</a> Do you want to learn <a href="https://www.quantumuting.com/">Quantum Computing</a>? <strong>Please find my social handles as below;</strong> <a href="https://www.rajeshkumar.xyz/">Rajesh Kumar Personal Website</a> <a href="https://www.youtube.com/TheDevOpsSchool">Rajesh Kumar at YOUTUBE</a> <a href="https://www.instagram.com/rajeshkumarin">Rajesh Kumar at INSTAGRAM</a> <a href="https://x.com/RajeshKumarIn">Rajesh Kumar at X</a> <a href="https://www.facebook.com/RajeshKumarLog">Rajesh Kumar at FACEBOOK</a> <a href="https://www.linkedin.com/in/rajeshkumarin/">Rajesh Kumar at LINKEDIN</a> <a href="https://www.wizbrand.com/rajeshkumar">Rajesh Kumar at WIZBRAND</a> <a href="https://www.rajeshkumar.xyz/dailylogs">Rajesh Kumar DailyLogs</a>

Related Posts

Terraform Tutorials: Local Values using Local Block

What is local value in terraform? In Terraform, a locals block is used to define local variables within a module, allowing you to create reusable expressions and…

Read More

Terraform Tutorials: Module Complete Guide

A Terraform module is a collection of configuration files that encapsulate resources used together to achieve a specific outcome. Modules promote reusability, organization, and maintainability in infrastructure…

Read More

What is Terrafile?

Terrafile is a tool used to manage Terraform modules as dependencies. It simplifies the process of downloading and managing Terraform modules by automating the fetching of modules…

Read More

What is Terraform and use cases of Terraform?

What is Terraform? Terraform is a infrastructure as code (IaC) tool and open-source from HashiCorp. It empowers users to define and manage cloud infrastructure and on-premises resources…

Read More

What is HashiCorp Terraform and use cases of HashiCorp Terraform?

What is HashiCorp Terraform? HashiCorp Terraform is a leading infrastructure as code (IaC) tool, empowering you to define, provision, and manage your cloud and on-premises infrastructure in…

Read More

Terraform Tutorials: What is terraform.tfvars with example

What is terraform.tfvars? Terraform .tfvars files are used to store variable definitions. This allows you to externalize your variable definitions and makes it easier to manage them,…

Read More