Can terraform providers generate implicit output variables?

Viewed 236

Is it possible for a custom terraform provider to generate an output variable implicitly, i.e. without the terraform user defining an output variable in their .tf file?

A bit more context -- we have a system that invokes user's terraform scripts, and wants to detect the existence of a resource. Is it possible to determine if a resource is used or not without having to parse the user's terraform? The thought was the provider associated with this resource could some how publish its existence via an output variable, or produce some external side-effect.

1 Answers

The answer to this depends a little on what you mean by a resource "existing". Based on your reference to module outputs I think you may intend it to mean that one or more instances of the resource are recorded in the Terraform state. If that's true, you can execute terraform show -json to get a JSON representation of what's currently recorded in the state.

In that JSON output you can iterate over the resources array in a module to see all of the resource instances in it. Each one will have an address property giving the resource instance address in the usual Terraform syntax, like aws_instance.example[0].


If you instead mean whether something exists in the configuration, independently of whether it has already been created and recorded in the state, there is not currently any built-in way to get that answer without parsing the Terraform configuration itself.

HashiCorp has a helper library terraform-config-inspect which has associated with it a little tool that can produce a JSON representation of the inspect result; using that would at least avoid you having to re-implement HCL decoding, but you may need to keep upgrading to newer verions of that library as the Terraform language evolves in future.

That library is what the Terraform Registry uses to extract metadata about modules, for example. One key advantage of it, compared to the parsing/decoding that Terraform itself does, is that it attempts to support all versions of the Terraform language since Terraform 0.10 so that the registry can extract metadata for modules regardless of which version of Terraform they are written for. However, it can only help with backward compatibility, because that library can't predict what new features may be added to the language later.

Related