terraform icon indicating copy to clipboard operation
terraform copied to clipboard

command/fmt: Make implicit provider requirements explicit

Open apparentlymart opened this issue 1 year ago • 0 comments

Ever since Terraform v0.13 we've been recommending that module authors be explicit about which providers their modules are intended to work with, but we retained some heuristics for detecting undeclared dependencies on official providers for backward compatibility with modules intended for Terraform v0.12 and earlier.

In the intervening years we've found that those heuristics have caused a lot of confusion, because Terraform tends not to be clear about what guesses it is making but then returns confusing error messages that only make sense if you are already an expert on Terraform's compatibility heuristics. These have been some of the most frequently asked questions about Terraform in community forums over the years.

In an attempt to make these rules easier to understand, terraform fmt will now run the same heuristics and then generate explicit declarations reflecting what it detected. This makes it explicit that it's good style to declare your dependencies explicitly, and also gives new users a clearer signal about what Terraform is guessing so that they have a better chance of learning what they might need to change if Terraform's guesses were not correct.

This is the first instance of terraform fmt making use of global information about the module it's working within. Since this command isn't always used with whole module directories, this is a "best effort" sort of thing where it'll only generate these when run in a way that allows the module analysis to work. In all other cases it'll just deal with the normal localized formatting rules as before.


Taken alone this will generate a hashicorp/-prefixed source address for any provider that seems implied by the heuristics, even if there isn't actually a provider of the inferred name in that namespace.

I propose that we follow this up with another attempt at https://github.com/hashicorp/terraform/pull/32365, which would constrain the backward-compatibility heuristic to only apply to providers that already exist in the hashicorp/ namespace at the time of first releasing that change.

If any new providers are published in that namespace later then they would need to be explicitly declared. In return for that, we get to return a better error message whenever we find a a reference to an undeclared provider that isn't on the hard-coded allowlist, and so the new behavior in this PR would effectively only apply for that fixed set of older providers that we must continue to infer automatically for backward-compatibility reasons. Therefore terraform fmt would never generate a new entry for an official provider that doesn't exist.

apparentlymart avatar Jun 26 '24 01:06 apparentlymart