Skip to content

Instantly share code, notes, and snippets.

@fionn
Last active September 7, 2021 06:17
Show Gist options
  • Save fionn/1aad03f826b3a96faaa1bb7df7fd1991 to your computer and use it in GitHub Desktop.
Save fionn/1aad03f826b3a96faaa1bb7df7fd1991 to your computer and use it in GitHub Desktop.
Move or rename a Terraform workspace
#!/bin/bash
# Move the current workspace to the given name, along with all associated state.
# Deals with the special case default workspace in the least surprising way.
set -euo pipefail
export TF_INPUT=0
export TF_IN_AUTOMATION=1
function create_backup_state {
local -r source="$1"
local -r backup="$(mktemp -d)/$source.$(date +%s).tfstate"
terraform state pull > "$backup"
echo "$backup"
}
function main {
local -r source="$(terraform workspace show)"
local -r target="$1"
[[ "$source" == "$target" ]] && echo "Already on that workspace" && exit 1
local -r backup=$(create_backup_state "$source")
echo "Backed up state to $backup"
# Create new workspace and copy state.
# This puts us in the target workspace.
if [[ "$target" != default ]]; then
terraform workspace new -state="$backup" "$target"
else
terraform workspace "select" default
terraform state push -force "$backup"
fi
# Delete original workspace and state.
if [[ "$source" == default ]]; then
export TF_WORKSPACE=default
terraform state list | xargs terraform state rm
unset TF_WORKSPACE
else
terraform workspace delete -force "$source"
fi
}
main "$1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment