Is using try function in output block legal?

output "vpc_arn" {
  description = "The ARN of the VPC"
  value       = try(aws_vpc.this.arn, "")

is it allowed to use try function in output block for all outputs in terraform??

The try function can be used in any expression, so it is valid in an output. Your example however has a first argument of aws_vpc.this.arn which cannot fail, so it’s not clear what you are intending to do.

Perhaps explain a bit what brought about this question?

My senior developer told me to use try function in all output blocks in file. But, I argued that this is not a best practice. So, he asked me reason for it. That is I reached out to this forum.

Hi @kishan,

I think generally any advice like “never do this” or “always do that” is incomplete advice. I assume that your colleague has a reason for giving this advice, but the best way to find that reason would be to ask that colleague to explain.

I’m sorry I don’t have anything more definite to answer. As @jbardin said, the specific example you shared is not actually achieving anything because the expression aws_vpc.this.arn cannot fail dynamically at runtime: it is either statically valid or not, depending on whether there is a resource "aws_vpc" "this" declared in this module, and if there isn’t then this expression would fail validation despite the try because Terraform knows in that case that successful evaluation is impossible.

It might be useful to use try in some other situations that can fail dynamically at runtime, so I think asking your colleague to clarify their advice will hopefully give a better understanding of when try is useful.

Of course if you would like to discuss any additional advice you learn from you colleague on this subject then we could do that, but I think asking them directly to clarify what they suggested is the best next step.