MoSheikh
MoSheikh

Reputation: 789

Terraform - flattening nested map

I currently have a terraform object declared as the following:

locals {
    x = {
        a = [
            {
                p0 = "j"
                p1 = "test-1"
                p2 = 0
            },
            {
                p0 = "k"
                p1 = "test-2"
                p2 = 0
            }
        ]
        b = [
            {
                p0 = "j"
                p1 = "test-1"
                p2 = 1
            },
            {
                p0 = "k"
                p1 = "test-3"
                p2 = 0
            }
        ]   
    }
}

What I want to do is to flatten the structure, but I can't figure out if this is possible in terraform. In my case, I know that p0 is going to be unique within its own array, so that I should be able to construct unique keys for each record. My desired output is the following:

locals {
    y = {
        a-j {
            p0 = "j"
            p1 = "test-1"
            p2 = 0
        }
        a-k {
            p0 = "k"
            p1 = "test-2"
            p2 = 0
        }
        b-j {
            p0 = "j"
            p1 = "test-1"
            p2 = 1
        }
        b-k {
            p0 = "k"
            p1 = "test-3"
            p2 = 0
        }
    }
}

I have got this to work by converting everything to a list, flattening it, and using count, but I'd like to preserve the keys in case the order changes later down the line to prevent deletion of resources unnessarily. Thanks for your help!

Upvotes: 2

Views: 12737

Answers (1)

Marcin
Marcin

Reputation: 238957

I think the following should satisfy your acquirement:

locals {

    x = {
        a = [
            {
                p0 = "j"
                p1 = "test-1"
                p2 = 0
            },
            {
                p0 = "k"
                p1 = "test-2"
                p2 = 0
            }
        ]
        b = [
            {
                p0 = "j"
                p1 = "test-1"
                p2 = 1
            },
            {
                p0 = "k"
                p1 = "test-3"
                p2 = 0
            }
        ]   
    }
    
    flat = merge([
        for k1, v1 in local.x:
        {
          for  v2 in v1: 
            "${k1}-${v2.p0}" => v2
        }
      ]...)  
    
}

which will result in flat being:

{
  "a-j" = {
    "p0" = "j"
    "p1" = "test-1"
    "p2" = 0
  }
  "a-k" = {
    "p0" = "k"
    "p1" = "test-2"
    "p2" = 0
  }
  "b-j" = {
    "p0" = "j"
    "p1" = "test-1"
    "p2" = 1
  }
  "b-k" = {
    "p0" = "k"
    "p1" = "test-3"
    "p2" = 0
  }
}

Upvotes: 11

Related Questions