2 min read | by Jordi Prats
When using HCL, if we want to access an element within a map we can use the usual index access present on many other languages. By using the lookup function we can do exactly that but providing a default value in case there's no such key.
Let's assume we want to use a the following map:
{"a"="A", "b"="B"}
We can create a .tf file on an empty directory for terraform console to use it:
$ mkdir /tmp/tftest; cd /tmp/tftest; echo 'variable "map" { default = {"a"="A", "b"="B"} }' > var.tf $ terraform console > var.map { "a" = "A" "b" = "B" }
If we want to access any element on the map we can use the following syntax:
$ terraform console > var.map["a"] "A"
However, if the key is not defined it would return an error:
> var.map["z"] ╷ │ Error: Invalid index │ │ on <console-input> line 1: │ (source code not available) │ │ The given key does not identify an element in this collection value. ╵
With the lookup() function we are telling it to retrieve a given key (second argument) from the map (first argument) or return a default value (third argument)
> lookup(var.map, "a", "notfound") "A" > lookup(var.map, "z", "notfound") "notfound"
That's quite similar of what we could achieve using the try function:
> try(var.map["a"], "notfound") "A" > try(var.map["z"], "notfound") "notfound"
Choosing between the two feels like personal choice though.
Posted on 18/03/2022