Create Multiple Azure Resources With Terraform using For-Each Statement

In this blog post, I will show you how I create three Azure resource groups using Terraform in a single configuration block with the for-each statement.

For-Each

In Terraform we can use the for-each statement to create multiple resources using a set of strings or a map as you will see below.

Configuration Block

Take a look at the configuration below, where I am creating three resource groups with the following names (RG001, RG002, RG003) and three different regions.

terraform {
   required_providers {
     azurerm = {
       source = "hashicorp/azurerm"
       version = ">= 2.26"
     }
   }
 }
   provider "azurerm" {
    features {}
 }
 resource "azurerm_resource_group" "rg" {
   for_each = {
     rg001 = "westus"
     rg002 = "westus2"
     rg003 = "eastus"
   }
   name     = each.key
   location = each.value
 }