I have this code:
output "output_value" {
value = (
data.oci_identity_compartments.compartment[0].compartments[0].id if
length(data.oci_identity_compartments.compartment) > 0 &&
length(data.oci_identity_compartments.compartment[0].compartments) > 0
else null
)
description = "This is the output value"
)
terraform fmt
gives me this error:
│ Error: Unbalanced parentheses
│
│ on path/to/my.tf line 16, in output "compartment_id":
│ 15: value = (
│ 16: data.oci_identity_compartments.compartment[0].compartments[0].id if
│
│ Expected a closing parenthesis to terminate the expression.
╵
╷
│ Error: Argument or block definition required
│
│ on path/to/my.tf line 17, in output "compartment_id":
│ 17: length(data.oci_identity_compartments.compartment) > 0 &&
│
│ An argument or block definition is required here. To set an argument, use the equals sign "=" to introduce the argument value.
╵
╷
│ Error: Argument or block definition required
│
│ on path/to/my.tf line 18, in output "compartment_id":
│ 18: length(data.oci_identity_compartments.compartment[0].compartments) > 0
│
│ An argument or block definition is required here. To set an argument, use the equals sign "=" to introduce the argument value.
╵
╷
│ Error: Invalid block definition
│
│ on path/to/my.tf line 19, in output "compartment_id":
│ 19: else null
│ 20: )
│
│ A block definition must have block content delimited by "{" and "}", starting on the same line as the block header.
How should I write this instead?
I haven't tested the following snippet, but your expression might be simplified by using the try function:
output "output_value" {
value = try(
data.oci_identity_compartments.compartment[0].compartments[0].id,
null
)
description = "This is the output value"
)
Explanation:
try
evaluates all of its argument expressions in turn and returns the result of the first one that does not produce any errors.