Provider Best Practices

An overview of some tips and tricks for Terraform providers.

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 init warning message

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.

Terraform creates a special file that is used to record the version of all of the providers used

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:

main.tf file of our Terraform providers project example

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.

This code requires the following environment variables to execute:
access_key_id
Not Specified...
secret_access_key
Not Specified...
Terminal 1
Terminal

Click to Connect...

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.

Providers in Detail
More Than One Instance of the Same Provider
Mark as Completed
Report an Issue