Skip to content

Instantly share code, notes, and snippets.

@k-k
Last active September 2, 2020 17:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k-k/0585ef25dd132862f1522e99d0e9eaab to your computer and use it in GitHub Desktop.
Save k-k/0585ef25dd132862f1522e99d0e9eaab to your computer and use it in GitHub Desktop.
Bash function to shorten interactions with Terraform Workspaces from the command line.
## The commands for working with terraform workspaces can be a little verbose, this just makes it easier to interact
## with the workspaces commands. It relies on `getops`, @see: https://wiki.bash-hackers.org/howto/getopts_tutorial
##
## This function can be added to your .bashrc or .zshrc.
tfw() {
# when no workspace is given, it's expected we're listing
if [ -z "$1" ]; then
terraform workspace list
return $?
fi
# check for options
while getopts ":d:" opt; do
case $opt in
# delete flag specified, delete the given workspace
d)
terraform workspace delete "$OPTARG"
return $?
;;
:)
echo "Option -${OPTARG} requires a workspace name to delete." >&2
return 1
;;
esac
done
# Either select or create the workspace (this becomes idempotent)
terraform workspace select "$1" 2> /dev/null || terraform workspace new "$1"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment