Create Multiple Azure Resources With Terraform For-Each Statement

This blog post will learn how to 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

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
 }

Parts of this blog post was first published on our sister site https://www.ntweekly.com

Leave a comment

Your email address will not be published. Required fields are marked *