Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Terraform for_each loop on map example

This article is a second part a post Hashicorp Terraform dynamic block for_each loop with example, In earlier script I used dynamic block to loop using for_each. This script will use same for_each loop without any block inside resource, instead I am using each.value to get the looping information. This is how the below script looks like and it is smaller and easier one than the dynamic block. I have two files main.tf and variable.tf. Here I am testing creating Resource Groups with for_each loop for demo.

#main.tf - for_each example
# Configure the Microsoft Azure Provider
provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "example_rg" {
  for_each = var.rgs
  name     = each.value["name"]
  location = each.value["location"]
  tags     = each.value["tags"]
} 

#variable.tf - for_each example
variable "rgs" {
  type = map(object({
    name     = string
    location = string
    tags     = map(string)
  }))
  default = {
    "first" = {
      name     = "first_rg"
      location = "west us"
      tags = {
        "owner"    = "vcloud-lab.com"
        "downtime" = "afternoon"
      }
    }
    "second" = {
      name     = "second_rg"
      location = "east us"
      tags = {
        "owner"    = "vJanvi"
        "downtime" = "morning"
      }
    }
  }
}
 

Note: You can also use each.key for key related items.

Login to azure with az login. First step is to initialize the backend, download the required provider plugin and verify basic scripts with terraform init.

az login

The default web browser has been opened at https://login.microsoftonline.com/common/oauth2/authorize. Please continue the login in the web browser. If no web browser is available or if the web browser fails to open, use device code flow with `az login --use-device-code`.
You have logged in. Now let us find all the subscriptions to which you have access...
The following tenants require Multi-Factor Authentication (MFA). Use 'az login --tenant TENANT_ID' to explicitly login to a tenant.
a59fb284-02ec-4a72-a79a-4a6b6105ab9d 'vcloud-lab.com'
[
  {
    "cloudName": "AzureCloud",
    "homeTenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "id": "9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "isDefault": true,
    "managedByTenants": [],
    "name": "Sponsership-by-Microsoft",
    "state": "Enabled",
    "tenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "user": {
      "name": "[email protected]",
      "type": "user"
    }
  }
]

terraform init

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/azurerm...
- Installing hashicorp/azurerm v2.77.0...
- Installed hashicorp/azurerm v2.77.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

Next validate tf files and properly format the script (indentation, spacing etc). Run a plan to verify there are no errors and it will create resources, In my case there are no errors and it will create two Resource Groups.

└ $ terraform validate
Success! The configuration is valid.

└ $ terraform fmt

└ $ terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
  + create

Terraform will perform the following actions:

  # azurerm_resource_group.example_rg["first"] will be created
  + resource "azurerm_resource_group" "example_rg" {
      + id       = (known after apply)
      + location = "westus"
      + name     = "first_rg"
      + tags     = {
          + "downtime" = "afternoon"
          + "owner"    = "vcloud-lab.com"
        }
    }

  # azurerm_resource_group.example_rg["second"] will be created
  + resource "azurerm_resource_group" "example_rg" {
      + id       = (known after apply)
      + location = "eastus"
      + name     = "second_rg"
      + tags     = {
          + "downtime" = "morning"
          + "owner"    = "vJanvi"
        }
    }

Plan: 2 to add, 0 to change, 0 to destroy.

────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run  
"terraform apply" now.

This is the last phase, apply terraform configuration, once configuration applied I see 2 resource groups are created successfully with provided configuration (location and tags).

└ $ terraform apply -auto-approve


Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # azurerm_resource_group.example_rg["first"] will be created
  + resource "azurerm_resource_group" "example_rg" {
      + id       = (known after apply)
      + location = "westus"
      + name     = "first_rg"
      + tags     = {
          + "downtime" = "afternoon"
          + "owner"    = "vcloud-lab.com"
        }
    }

  # azurerm_resource_group.example_rg["second"] will be created
  + resource "azurerm_resource_group" "example_rg" {
      + id       = (known after apply)
      + location = "eastus"
      + name     = "second_rg"
      + tags     = {
          + "downtime" = "morning"
          + "owner"    = "vJanvi"
        }
    }

Plan: 2 to add, 0 to change, 0 to destroy.
azurerm_resource_group.example_rg["first"]: Creating...
azurerm_resource_group.example_rg["second"]: Creating...
azurerm_resource_group.example_rg["second"]: Creation complete after 3s [id=/subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/second_rg]
azurerm_resource_group.example_rg["first"]: Creation complete after 3s [id=/subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/first_rg]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Useful Articles
Create an Azure App registrations in Azure Active Directory using PowerShell & AzureCLI
Get started and configure with certificate-based authentication in Azure
Create a Virtual machine on Microsoft Azure
PowerShell List All Azure Resverations
Powershell get the list of Azure Reservations Virtual Machines instances
Get the list Azure Reservation Catalog with PowerShell and AzureCLI
Azure automation account DSC for On-Premise Virtual Machine on boarding
Azure Powershell : Operation returned an invalid status code 'BadRequest'
Get Azure virtual machine backup reports using Powershell



This post first appeared on Tales From Real IT System Administrators World And Non-production Environment, please read the originial post: here

Share the post

Terraform for_each loop on map example

×

Subscribe to Tales From Real It System Administrators World And Non-production Environment

Get updates delivered right to your inbox!

Thank you for your subscription

×