terraform

Null values in a map


I have this code:

module "mod1" {
  source = "./modules/mod1"
}

module "mod2" {
  source = "./modules/mod2"
}

output "output_map" {
  value = {
    "key1" = module.mod1.output_value
    "key2" = module.mod2.output_value
  }
}

When mod2 returns a null value, the printed value of output_map only shows key1 and its value. Is this an expected behavior? I was hoping to get a map with two keys, with the second key having a null value.


Solution

  • What you have returned in this output value is technically an object-typed value, rather than a map.

    I believe what's happened here is that the UI layer of Terraform is trying to be terse by following the usual convention that in null represents the absence of a value, and so it's choosing to hide the null attribute rather than show it as null.

    That is technically a misleading way to present it when it's an output value, but it would be a correct assumption for the values inside a resource block because for resources null is how Terraform represents an optional attribute that hasn't been set; that isn't actually true for an output value. Therefore I think you've encountered a small bug in Terraform CLI's presentation of output values.

    You could confirm my theory above by asking Terraform to return the output values in machine-readable JSON format instead of human-oriented format:

    terraform output -json
    

    I expect that in the JSON output you will find "key2":null in the JSON object representing that output value. If so, that would confirm that the attribute is present but the UI is choosing to hide it from you because it's null.