Skip to content

Instantly share code, notes, and snippets.

@pizofreude
Created April 16, 2025 18:24
Show Gist options
  • Save pizofreude/2152ecf5d7948ce7a046adc30676b123 to your computer and use it in GitHub Desktop.
Save pizofreude/2152ecf5d7948ce7a046adc30676b123 to your computer and use it in GitHub Desktop.
Git and Terraform Workspace Workflow. All things git & terraform.

Git and Terraform Workspace Workflow

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:

  1. Create a new Git branch: Create a new branch from the main branch, e.g., git branch dev.
  2. Create a new Terraform workspace: Run terraform workspace new dev to create a new workspace named "dev".
  3. Switch to the new Terraform workspace: Run terraform workspace select dev to switch to the "dev" workspace.
  4. 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 and git commit.
  5. Apply the changes to the Terraform workspace: Run terraform apply to apply the changes to the "dev" workspace.
  6. Repeat for other branches: Create new workspaces for other branches, e.g., terraform workspace new prod, and switch to them using terraform 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 workspace
  • main 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:

  1. git branch dev (create a new branch)
  2. terraform workspace new dev (create a new workspace)
  3. terraform workspace select dev (switch to the new workspace)
  4. Make changes and commit to the dev branch
  5. terraform apply (apply the changes to the dev 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment