terraform for_each

Terraform for_each example to create multiple resources

Terraform for_each will allow you create multiple resources without having to define multiple resource blocks. As your infrastructure as code starts to grow, it can become difficult to follow along with what’s going on.

In this article I have a terraform for_each example to show you how to create multiple azure resources. The resources we will be creating are:

  • A pair of azure resource groups
  • 2 separate virtual networks that will reside in both resource groups
terraform for_each method

How to create azure resource groups in terraform

To create multiple azure resource groups in terraform you can separate out each resource into a separate terraform block.

resource "azurerm_resource_group" "resourcegroup1" {
  name = "test"
  location = "eastus"
  
}

resource "azurerm_resource_group" "resourcegroup1" {
  name = "dev"
  location = "eastus"
  
}

resource "azurerm_resource_group" "resourcegroup1" {
  name = "staging"
  location = "eastus"
  
}

Now this way can be used to create 3 different resources groups in the eastus region. As your code starts to grow and get more complex it may be more beneficial to try and keep some sections more cleaner.

This is where the terraform for_each example comes into play.

How to use terraform for_each

The for_each meta-argument produces an object for each item in a map or set of strings that it accepts. When the configuration is implemented, each instance’s associated infrastructure object is a unique entity that is created, modified, or deleted independently.

When creating 3 resource groups in azure like above using for_each you would set it up like this:

resource "azurerm_resource_group" "homelabrg" {
  for_each = {
    "rsg1" = {name = "homelabdev", location = "eastus"}
    "rsg2" = {name = "homelabtest", location = "eastus"}
    "rsg3" = {name = "homelabstaging", location = "eastus"}
  }
  name     = each.value.name
  location = each.value.location
}

This essentially provides a more cleaner code setup.

Conclusion

We configured a simple way to create an azure resource group without having to use multiple resource blocks. This can be used with other resources in terraform. When using terraform locals remember that the values must be known.

Comments are closed.