How to conditionally add key value to Terraform map
This code will conditionally add or omit a netapp-cleaner block based on the prefix local variable using Terraform's merge and ternary operator.
This code will conditionally add or omit the netapp-cleaner block based on the prefix local variable. It uses Terraform’s merge() function combined with a ternary expression to include or exclude the extra map entry. When local.prefix matches the expected value, the additional block is merged into the map; otherwise, an empty map is merged, effectively omitting it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
locals {
prefix = "deaut"
raj = merge({
netapp-admin = {
member = "serviceAccount:raj",
role = "roles/netapp.admin"
},
netapp-user = {
member = "serviceAccount:jan",
role = "roles/netapp.user"
},
},
local.prefix == "xdeaut" ? {
netapp-cleaner = {
member = "serviceAccount:cleaner",
role = "roles/blaaaa"
}
}: {}
)
}
output "debug" {
value = local.raj
description = "debug"
}
This post is licensed under CC BY 4.0 by the author.