While working with Terraform, I needed to deploy resources without relying on the count meta-argument. My variable was a list of objects, but using count resulted in index numbers being appended to the resource names. To avoid this, I opted to use the for_each argument to iterate over the list of objects. This approach allowed me to utilize an if statement within the for_each loop to filter the required objects based on the environment variable, and deploy only the specified resources.
provider "azurerm" { features {} subscription_id = "9exxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" } variable "resource_group" { type = list(object({ environment = string name = string location = string })) default = [{ environment = "dev" name = "dev_rg" location = "East US" }] } resource "azurerm_resource_group" "dev" { for_each = { for sa in var.resource_group : sa.name => sa if sa.environment == "dev" } name = each.value.name location = each.value.location } resource "azurerm_resource_group" "prod" { for_each = { for sa in var.resource_group : sa.name => sa if sa.environment == "prod" } name = each.value.name location = each.value.location }
Download this configuration terraform_foreach_list_of_object_example here or it is also available on github.com.
Below is the output of the above code implementation.
Useful Articles
Create storage account and Service Principal using PowerShell for Terraform Azure Backend
Unlocking TF State File on Azure backend with PowerShell and Terraform Force-Unlock Command
Terraform variable precedence and priority
Terraform filter map and list object with if condition in for_each loop examples
Terraform Azure function app with private endpoint and storage account
Terraform module Azure function app with private endpoint and storage account
Terraform passing different credentials to different subscriptions with provider alias
Terraform Azure provider alias passing credentials and configuration in module resources
Terraform Azure provider passing multiple alias environment and credentials in child module
Terraform variable multiple validation advanced blocks example
Terraform variable type list with for_each for loop examples
Terraform convert single string to list or set
Terraform workspaces with example
Terraform map of object for loop with if condition example
HashiCorp HCP Terraform Cloud backend configuration
Azure DevOps Enable creation of classic build release pipelines grayed out
Adding parameters in Azure DevOps pipelines examples Part 1