xyz1234
xyz1234

Reputation: 119

Store "Provider" and "Terraform" version in separate TF file?

Currently, I have to define the Terraform version and Provider version in each of my Terraform templates.

I would like to have a file outside of my Terraform templates where I can define the Provider version and Terraform version to use for every template in the directory structure.

I've looked at using an overrides file (https://www.terraform.io/docs/configuration/override.html), but it appears I'd have to define the whole Terraform/Provider block from each template within the override.tf file. I'd really like to just be able to tell Terraform to look at (pseudo-file) versions.tf, for example, to get the necessary versions for every template.

So something like this would be the desired (simplified) directory structure:

 terraform
     ├── dev
     │   └── main.tf
     ├── prod
     │   └── main.tf
     ├── stg
     │   └── main.tf
     └── versions.tf

Right now there would need to be only one Provider version and one Terraform version defined in versions.tf

Is it possible to pass Provider/Terraform version into templates in this way?

Upvotes: 4

Views: 3044

Answers (1)

Esteban Garcia
Esteban Garcia

Reputation: 2283

If you don't want to use Terraform Workspaces then create a symlink in each subdirectory pointing to the versions.tf file.

For example, if your structure is:

terraform
     ├── dev
     │   └── main.tf
     ├── prod
     │   └── main.tf
     ├── stg
     │   └── main.tf
     └── versions.tf

And you want each subdirectory (dev, prod, stg) to point to the versions.tf file on the root terraform directory, create a symlink in each subdirectory:

ln -sf terraform/versions.tf terraform/dev/versions.tf
ln -sf terraform/versions.tf terraform/prod/versions.tf
ln -sf terraform/versions.tf terraform/stg/versions.tf

Your final structure would be:

terraform
     ├── dev
     │   └── main.tf
     │   └── versions.tf -> ../versions.tf
     ├── prod
     │   └── main.tf
     │   └── versions.tf -> ../versions.tf
     ├── stg
     │   └── main.tf
     │   └── versions.tf -> ../versions.tf
     └── versions.tf

Using Terraform Workspaces, instead of having a sub-directory for each "environment" you're using so have a single directory like:

terraform
     ├── main.tf
     └── versions.tf

And a workspace per environment which you create by doing:

terraform workspace new dev

You then use terraform interpolation to do something different depending on which environment you are working on, terraform states are also stored separately per workspace.

So if you want to work on the dev environment you switch to that one:

terraform workspace select dev

Upvotes: 4

Related Questions