terraformoracle-cloud-infrastructure

Simplify an expression that makes nested calls to coalesce


I am new to Terraform and looking at a code like this one wondering if it could be simplified:

  compartment_id = length(coalesce(data.oci_identity_compartments.compartment, [])) > 0 ? (
     length(coalesce(data.oci_identity_compartments.compartment[0].compartments, [])) > 0 ? (
       data.oci_identity_compartments.compartment[0].compartments[0].id) : null) : null

Is there a way to write this expression more elegantly?


Solution

  • You can use the try function to make the expression significantly more concise (note documentation also states the function is intended for your use case).

    compartment_id = try(data.oci_identity_compartments.compartment[0].compartments[0].id, null)