Embracing the Messiness in Search of Epic Solutions

Terraform: Handling Errors with try(…)

PROBLEM

Given the following output block:-

output "subnet_uc1" {
  description = "Subnets in `us-central1` region for all 3 products"
  value = {
    artifactory = module.subnet_uc1_artifactory.subnets.name
    xray        = module.subnet_uc1_xray.subnets.name
    mc          = module.subnet_uc1_mc.subnets.name
  }
}

Sometimes, during an apply or destroy, we may get this error:-

Error: Attempt to get attribute from null value

  on outputs.tf line 40, in output "subnet_uc1":
  40:     artifactory = module.subnet_uc1_artifactory.subnets.name
    |----------------
    | module.subnet_uc1_artifactory.subnets is null

This value is null, so it does not have any attributes.

Error: Attempt to get attribute from null value

  on outputs.tf line 41, in output "subnet_uc1":
  41:     xray        = module.subnet_uc1_xray.subnets.name
    |----------------
    | module.subnet_uc1_xray.subnets is null

This value is null, so it does not have any attributes.

Error: Attempt to get attribute from null value

  on outputs.tf line 42, in output "subnet_uc1":
  42:     mc          = module.subnet_uc1_mc.subnets.name
    |----------------
    | module.subnet_uc1_mc.subnets is null

This value is null, so it does not have any attributes.

One way to fix this is to do conditional expressions like this, but it’s not pretty:-

output "subnet_uc1" {
  description = "Subnets in `us-central1` region for all 3 products"
  value = {
    artifactory = module.subnet_uc1_artifactory.subnets != null ? module.subnet_uc1_artifactory.subnets.name: ""
    xray        = module.subnet_uc1_xray.subnets != null ?module.subnet_uc1_xray.subnets.name: ""
    mc          = module.subnet_uc1_mc.subnets != null ? module.subnet_uc1_mc.subnets.name: ""
  }
}

SOLUTION

Since Terraform v0.12.20, we can solve this with try and achieve the same outcome:-

output "subnet_uc1" {
  description = "Subnets in `us-central1` region for all 3 products"
  value = {
    artifactory = try(module.subnet_uc1_artifactory.subnets.name, "")
    xray        = try(module.subnet_uc1_xray.subnets.name, "")
    mc          = try(module.subnet_uc1_mc.subnets.name, "")
  }
}

Tags:

Comments

Leave a Reply