Terraform flatten function example

Simple flatten Terraform function example and it’s usage in various Terraform blocks.

Feb 1, 2023

Simple flatten Terraform function example and it’s usage in various Terraform blocks.

Declare a local map

Local map variable with nested list of data.

locals {
  domains = {
    "example.com" = {
      enable = true,
      subdomains = [
        "mail.example.com",
        "email.example.com",
        "smtp.example.com"
      ]
    },
    "www.example.com" = {
      enable = false,
      subdomains = [
        "mail.www.example.com",
        "smtp.www.example.com"
      ]
    }
  }
}

output "original" {
  value = local.domains
}

Use flatten function

Using for loops, convert the local variable into a list of name value pairs.

output "flatmap" {
  value = flatten([
    for domain, obj in local.domains : [
      for subdomain in obj.subdomains : {
        zone      = domain
        subdomain = subdomain
        enabled = obj.enable
      }
    ]
  ])
}

Run terraform plan and you will see a flat map structure along with original map.

Terraform output

Changes to Outputs:
  + flatmap  = [
      + {
          + enabled   = true
          + subdomain = "mail.example.com"
          + zone      = "example.com"
        },
      + {
          + enabled   = true
          + subdomain = "email.example.com"
          + zone      = "example.com"
        },
      + {
          + enabled   = true
          + subdomain = "smtp.example.com"
          + zone      = "example.com"
        },
      + {
          + enabled   = false
          + subdomain = "mail.www.example.com"
          + zone      = "www.example.com"
        },
      + {
          + enabled   = false
          + subdomain = "smtp.www.example.com"
          + zone      = "www.example.com"
        },
    ]
  + original = {
      + "example.com"     = {
          + enable     = true
          + subdomains = [
              + "mail.example.com",
              + "email.example.com",
              + "smtp.example.com",
            ]
        }
      + "www.example.com" = {
          + enable     = false
          + subdomains = [
              + "mail.www.example.com",
              + "smtp.www.example.com",
            ]
        }
    }

Tags

CodetipsTerraform