Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 635
MoSheikh Avatar asked Oct 26 '25 03:10

MoSheikh


1 Answers

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
  }
}
like image 64
Marcin Avatar answered Oct 28 '25 02:10

Marcin