mdawar.dev

A blog about programming, Web development, Open Source, Linux and DevOps.

Install Multiple Terraform Versions Using tfenv

tfenv is a version manager for Terraform, it provides a simple interface for installing and managing multiple versions easily just like nvm for Node.js.

Install tfenv

Using Homebrew

bash
$brew install tfenv

Manual Installation

1. Clone the Git repository
bash
$# Clone the repo to ~/.tfenv
$# Truncate the history to the last commit (--depth=1)
$git clone --depth=1 https://github.com/tfutils/tfenv.git ~/.tfenv
2. Add the ~/.tfenv/bin directory to the $PATH environment variable

Add this line to ~/.bash_profile or ~/.bashrc files:

bash
export PATH="$HOME/.tfenv/bin:$PATH"

Or create symlinks for the scripts in ~/.tfenv/bin into a path that’s already added to the $PATH:

bash
$sudo ln -s ~/.tfenv/bin/* /usr/local/bin
3. Update tfenv

To update the tfenv version:

bash
$git -C ~/.tfenv pull

Usage

Check the installed tfenv version:

bash
$tfenv --version

List all the installable versions:

bash
$tfenv list-remote

Install the latest Terraform version:

bash
$tfenv install latest

Install a specific Terraform version:

bash
$# tfenv install <version>
$tfenv install 1.2.9

Uninstall a specific Terraform version:

bash
$# tfenv install <version>
$tfenv uninstall 1.2.9

List all the installed Terraform versions:

bash
$tfenv list

Set a default Terraform version:

bash
$# tfenv use <version>
$tfenv use 1.2.9

Switch Between Terraform Versions:

bash
$# tfenv use <version>
$tfenv use 0.13.0

Manage Projects Using Different Terraform Versions

We can manage multiple projects that require a different Terraform version using a special file named .terraform-version.

Create a .terraform-version file in the current directory with the current Terraform version:

bash
$tfenv pin

Use the Terraform version specified in .terraform-version:

bash
$tfenv use

We can also set the TFENV_TERRAFORM_VERSION environment variable which overrides the value in .terraform-version when switching the Terraform version using tfenv use.

Uninstall tfenv

Remove the export line from ~/.bash_profile or ~/.bashrc files:

bash
export PATH="$HOME/.tfenv/bin:$PATH"

Or remove the symlinks of the files in ~/.tfenv/bin/* if you used this method:

bash
$sudo rm /usr/local/bin/tfenv
$sudo rm /usr/local/bin/terraform

Then remove the tfenv repository:

bash
$rm -rf ~/.tfenv