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 devto create a new workspace named "dev". - Switch to the new Terraform workspace: Run
terraform workspace select devto 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 addandgit commit. - Apply the changes to the Terraform workspace: Run
terraform applyto 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:
devbranch ->devworkspacemainbranch ->prodworkspace
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
devbranch terraform apply(apply the changes to thedevworkspace)
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.
Forgot to create new branch before making changes?
No worries! This is a common mistake and easily fixable. Here's how to move your commits to a new branch:
🔧 Fix: Move Commits to New Branch
Option 1: Create Branch from Current State (Recommended)
That's it! Your commits are now on a feature branch.
Option 2: If You Already Pushed to
mainIf you already pushed commits to
mainand want to move them:--force-with-leaseif you're the only one working onmainor have coordinated with your team!Option 3: Soft Reset (Keep Changes Uncommitted)
If you want to uncommit everything and start fresh:
✅ Recommended Approach for Your Situation
EXAMPLE: If you've made some commits already but haven't push any, I recommend Option 1:
🎯 After Creating the Branch
Now you can:
Create PR from the new branch:
feat/prometheus-metricsmainContinue working:
📝 Summary
The easiest fix:
Then create your PR from this new branch! All your commits are preserved.