Terraform: Conditionally use if a key is present under a map otherwise use default value

Created on 14 Jul 2019  路  5Comments  路  Source: hashicorp/terraform

Current Terraform Version

...

Use-cases

Attempted Solutions

Proposal


Usually other languages has feature ifdefined(var.key) to check if the variable is defined.

References

Something like is present in many languages e.g.
if (typeof variable !== 'undefined')

config enhancement

Most helpful comment

It can be done like this:

key_exists = contains(keys(map), key)

All 5 comments

The lookup() function supports this:

lookup(map, key, default)

how about nested maps?

``` access_points = {
marketing = {
posix_user = {
gid = "1000"
uid = "1000"
secondary_gids = "0755"
},
creation_info = {
gid = "1000"
uid = "1000"
permissions = "0755"
}
}
data = {
posix_user = {
gid = "1000"
uid = "1000"
permissions = "0755"
}
}
}


creation_info {
  owner_gid     = lookup(var.access_points[each.key], "creation_info", null) == null ? null : lookup(var.access_points[each.key]["creation_info"], "gid", null)
  owner_uid     = lookup(var.access_points[each.key], "creation_info", null) == null ? null : lookup(var.access_points[each.key]["creation_info"], "uid", null)
  permissions   = lookup(var.access_points[each.key], "creation_info", null) == null ? null : lookup(var.access_points[each.key]["creation_info"], "permissions", null)
}

```

I am trying to test for 'creation_info' before I attempt to use keys in 'creation_info'. I keep getting errors nesting lookup.

The only option I've found to get a binary result with lookup looks ugly:

key_exists = lookup(map, key, default) != default

Is there a better way?

not that I know of.

It can be done like this:

key_exists = contains(keys(map), key)
Was this page helpful?
0 / 5 - 0 ratings