Skip to content

Commit b3c1b13

Browse files
committed
Add nested maps example
1 parent 578c833 commit b3c1b13

File tree

3 files changed

+86
-0
lines changed

3 files changed

+86
-0
lines changed

traversing-nested-maps/.tool-versions

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
terraform 1.0.5

traversing-nested-maps/README.md

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Traversing Nested Maps
2+
3+
Terraform [used to use splat expressions](https://www.terraform.io/docs/language/expressions/splat.html#splat-expressions-with-maps) for this stuff (and I wish they still worked), but now this is all done with [`for` expressions](https://www.terraform.io/docs/language/expressions/for.html).
4+
5+
Using [your example code as a guide](https://github.com/RulerOf/terraform-code-examples/traversing-nested-maps/main.tf), it's pretty straightforward to select the structure of the map where the `address_space` lists are the first element down, like this:
6+
7+
> local.subscriptions.MySecondSubcription.VirtualNetworks
8+
{
9+
"vNet1" = {
10+
"address_space" = [
11+
"10.20.0.0/24",
12+
"192.168.3.0/24",
13+
]
14+
}
15+
"vNet2" = {
16+
"address_space" = [
17+
"10.30.0.0/24",
18+
"192.168.4.0/24",
19+
]
20+
}
21+
}
22+
23+
Now, using the `for` expression, we can cherry pick the `address_space` into a list by iterating over that level of the map like this:
24+
25+
> [ for net in local.subscriptions.MySecondSubcription.VirtualNetworks : net.address_space ]
26+
[
27+
[
28+
"10.20.0.0/24",
29+
"192.168.3.0/24",
30+
],
31+
[
32+
"10.30.0.0/24",
33+
"192.168.4.0/24",
34+
],
35+
]
36+
37+
If the subdivided lists aren't helpful, you can [`flatten()`](https://www.terraform.io/docs/language/functions/flatten.html) the output:
38+
39+
> flatten([ for net in local.subscriptions.MySecondSubcription.VirtualNetworks : net.address_space ])
40+
[
41+
"10.20.0.0/24",
42+
"192.168.3.0/24",
43+
"10.30.0.0/24",
44+
"192.168.4.0/24",
45+
]
46+
47+
### Credits
48+
49+
Inspired by the question in [this Reddit thread](https://www.reddit.com/r/Terraform/comments/pms32s/deeply_nested_maps_help/).

traversing-nested-maps/main.tf

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
locals {
2+
subscriptions = {
3+
"MyFirstSubscription" = {
4+
"VirtualNetworks" = {
5+
"vNet1" = {
6+
"address_space" = [
7+
"10.0.0.0/24",
8+
"192.168.0.0/24",
9+
]
10+
}
11+
"vNet2" = {
12+
"address_space" = [
13+
"10.10.0.0/24",
14+
"192.168.1.0/24",
15+
]
16+
}
17+
}
18+
}
19+
"MySecondSubcription" = {
20+
"VirtualNetworks" = {
21+
"vNet1" = {
22+
"address_space" = [
23+
"10.20.0.0/24",
24+
"192.168.3.0/24",
25+
]
26+
}
27+
"vNet2" = {
28+
"address_space" = [
29+
"10.30.0.0/24",
30+
"192.168.4.0/24",
31+
]
32+
}
33+
}
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)