Skip to content

Instantly share code, notes, and snippets.

@carlessanagustin
Last active March 13, 2024 12:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlessanagustin/fdb2304d2f3cd6e14f9f5112222c4abd to your computer and use it in GitHub Desktop.
Save carlessanagustin/fdb2304d2f3cd6e14f9f5112222c4abd to your computer and use it in GitHub Desktop.
Terraform nested loop
  • In <filename>.tf:
variable "users" {
  default = [
    {
      name       = "user1"
      databases  =  ["db1","db2"]
      password   = "change_me"
      privileges = ["CONNECT","CREATE","TEMPORARY"]
    },
    {
      name       = "user2"
      databases  =  ["db1","db3"]
      password   = "change_me"
      privileges = ["CONNECT","CREATE"]
    }
  ]
}

locals {
  db_grants = var.users == null ? [] : flatten([
    for index1,value1 in var.users : [
      for index2,value2 in value1.databases : {
        name       = value1.name
        database   = value2
        privileges = value1.privileges
      }
    ]
  ])
}
  • In Terraform console:
> local.db_grants
tolist([
  {
    "database" = "db1"
    "name" = "user1"
    "privileges" = tolist([
      "CONNECT",
      "CREATE",
      "TEMPORARY",
    ])
  },
  {
    "database" = "db2"
    "name" = "user1"
    "privileges" = tolist([
      "CONNECT",
      "CREATE",
      "TEMPORARY",
    ])
  },
  {
    "database" = "db1"
    "name" = "user2"
    "privileges" = tolist([
      "CONNECT",
      "CREATE",
    ])
  },
  {
    "database" = "db3"
    "name" = "user2"
    "privileges" = tolist([
      "CONNECT",
      "CREATE",
    ])
  },
])

more: https://blog.boltops.com/2020/10/06/terraform-hcl-nested-loops

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment