Provider Best Practices
An overview of some tips and tricks for Terraform providers.
We'll cover the following
When you ran terraform init
, Terraform downloaded the latest versions of all of the providers that
you used in your project. You may have noticed the warning message that Terraform printed out:
Terraform creates a special file that is used to record the version of all of the providers used.
This is so that when terraform init
is run again (potentially on another machine), Terraform can select exactly the same versions of the providers that were used when the project was first to run. This is important for repeatability.
It can be useful to control the version of the provider that Terraform selects when init
is first run. For example, some of your code may only work with v3 of a provider because there is
a breaking change in v4. By committing the .terraform.lock.hcl
file as suggested in the message, you will guarantee that the version of the provider you used when you set up this project will always be used.
Terraform project example#
If you want to instruct Terraform to select a certain version of a provider when it first initializes (in case there is no lock file present) we can use a special terraform block to configure the version for the AWS provider.
Let’s see an example of this:
In the Terraform block above, we have defined a required_providers
block. This required provider block allows us to specify extra properties for each of the providers we are using in the project.
Under required providers, we open an AWS block. There, we specify a version constraint for the AWS provider.
Running the project#
Clicking the terminal will run terraform init
. When prompted, enter yes to run the project.
The version
constraint ∼> 3.46
is used by Terraform when there is no .terraform.lock.hcl
present. This
constraint means that any version greater than or equal to 3.46
but less than 4.0
is allowed. In
normal operation, you should not need to worry about version constraints as long as you commit the
lock file.