Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Terraform for_each loop on map example

This article is a second part of a post Hashicorp Terraform dynamic block for_each loop with example, In earlier script I used dynamic block with using for_each loop. In This script I will use same for_each loop without any block inside resource, instead I am using each.value to get the looped information. This is how the below script looks like and it is smaller and easier one than the dynamic block. I have for your reference have two files main.tf and variable.tf. Here I am testing creating multiple Resource Groups within single variable using for_each loop for demo, values from map dictionary are fetched with values with key pair.

#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"]           #each.value.name
  location = each.value["location"]       #each.value.location
  tags     = each.value["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.

Download Terraform for_each script here or it is also available on github.com.

Microsoft azure terraform terraform map of object for_each loop on map hashtable example demo create resource group for_each each value foreach-object dyanamic.png

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.

terraform init initializing the backend initializing the backend pluging provider hashicorp azurerm aws plan devops configuration tf files tfvars variable main.png

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": "janvi@vcloud-lab.com",
      "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.

Microsoft Powershell terraform variable environment terraform validate hashcorp fmt format code terraform plan provider azurerm features id tags name azurerm_resoruce_group.png

└ $ 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 create resources azurerm_resource_group subscription sponsership apply complete destroy devops hashicorp language tf main variable tage map for_each object.png

└ $ 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

Go Back

Comment

Blog Search

Page Views

6069215

Follow me on Blogarama