When using Terraform with Git, it's common to associate a Terraform workspace with a specific Git branch. This allows you to manage different environments and configurations for each branch.
Here's a general workflow:
- Create a new Git branch: Create a new branch from the main branch, e.g.,
git branch dev
. - Create a new Terraform workspace: Run
terraform workspace new dev
to create a new workspace named "dev". - Switch to the new Terraform workspace: Run
terraform workspace select dev
to switch to the "dev" workspace. - Make changes and commit to the Git branch: Make changes to your infrastructure configuration files and commit them to the "dev" branch using
git add
andgit commit
. - Apply the changes to the Terraform workspace: Run
terraform apply
to apply the changes to the "dev" workspace. - Repeat for other branches: Create new workspaces for other branches, e.g.,
terraform workspace new prod
, and switch to them usingterraform workspace select prod
.
Associating Git branches with Terraform workspaces
To associate a Git branch with a Terraform workspace, you can use a naming convention, such as:
dev
branch ->dev
workspacemain
branch ->prod
workspace
Alternatively, you can use a more explicit approach by creating a file, e.g., .gitignore
, with a rule that associates the workspace name with the Git branch name.
Example
Assuming you have a Git repository with main
and dev
branches, and you want to create a new Terraform workspace for the dev
branch:
git branch dev
(create a new branch)terraform workspace new dev
(create a new workspace)terraform workspace select dev
(switch to the new workspace)- Make changes and commit to the
dev
branch terraform apply
(apply the changes to thedev
workspace)
When switching between branches, you can use terraform workspace select
to switch to the corresponding workspace. For example, when switching to the main
branch, you can run terraform workspace select prod
to switch to the prod
workspace.