Try() vs lookup() preference?

I understand that pre TF 0.12, lookup() was needed to be able to select an alternate value if a key is not present in a map. However, with the introduction of the more general try() in TF 0.12, we’ve had a few discussions about whether we should use one form over the other (we currently have a mix).

Is any general guidance on a preference between using:

lookup(somemap, "some-key", "alt-value")

vs:

try(somemap["some-key"], "alt-value")

I’m leaning more towards using try(), but curious what folks think and/or are doing here. Are there any cases where try() isn’t appropriate as a replacement for lookup()?

Hi @wenslayer,

try is indeed a more general form of lookup. If we didn’t already have the lookup function then I expect we wouldn’t add it now, since try has subsumed all of the use-cases for it. It exists in modern Terraform largely for backward compatibility with older modules.

I personally now always use try and never use lookup in new code. Honestly that is mostly a subjective decision on my part: I think try looks more readable because its first argument is an expression written in the normal way and so it’s easier to see what’s going on. It can also concisely test multiple levels of traversal all at once: try(foo.bar.baz, "other").

The docs do warn against overusing try with really complex expressions where there are many possible reasons for failure, but as a direct replacement for lookup it’s just fine and is what try was originally designed for.

1 Like