Using terraform try function to retrieve optional values on maps

2 min read

It's common practice to use a map in terraform to configure resources. If we want to use a map with optional values we can make use of the try() function

Let's us the following map as an example:

  config = {
    namespaces = ["namespace1", "namespace2"]


We can access use the objects as follows:

resource "kubernetes_namespace" "ns" {
  for_each = var.config.namespaces


If we don't want to force the user of this module to specify the list of namespace, we can set a default value using the try function:

resource "kubernetes_namespace" "ns" {
  for_each = try(var.config.namespaces, ["namespace1", "namespace2"])


The try function evaluates its arguments, returning the first one that does not produce any errors. So, if we use a variable that might not exists together with some values, the try function will return the variable's values if it exists or the values we are setting otherwise. Effectively like setting some default value for this variable

Posted on 02/07/2021