This article I will show the example of Terraform looping map of object variable type and using if condition to filter the map key value. In this demo I provided a map of object inside users variable. Following inside the locals variable, I am using logic for loop over map of objects and if condition to filter value of is_admin to get the desired output as shown in the below code.
Next I am using output block to show the filtered objects.
variable "users" { type = map(object({ is_admin = bool testattr = string })) default = { "name" = { is_admin = true testattr = "kiman" } } } locals { admin_users = { for name, user in var.users : name => user if user.is_admin } regular_users = { for name, user in var.users : name => user if !user.is_admin } } output "admin_users" { value = local.admin_users } output "regular_users" { value = local.regular_users }
Download this code Terraform map loop and if condition here or it is also available on github.com.
In the below terminal output as it can be seen it is filtering the is_admin value if true.
terraform apply --auto-approve Changes to Outputs: + admin_users = { + name = { + is_admin = true + testattr = "kiman" } } + regular_users = {} You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure. Apply complete! Resources: 0 added, 0 changed, 0 destroyed. Outputs: admin_users = { "name" = { "is_admin" = true "testattr" = "kiman" } } regular_users = {}
Useful Articles
Terraform refactoring moved block example
Terraform create Azure Virtual Machines from map of objects
Terraform variable validation example
Configure Azure Storage Account Blob as Terraform backend to store tfstate file Examples of most used general purpose terraform functions
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