Skip to content

Instantly share code, notes, and snippets.

@xinau
Created May 20, 2020 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xinau/096073d3d6187eb01ceed58c2bd33089 to your computer and use it in GitHub Desktop.
Save xinau/096073d3d6187eb01ceed58c2bd33089 to your computer and use it in GitHub Desktop.
terraform init wrapper - backend switch and environment name export.
#!/usr/bin/env bash
#
# This script is used for configuring terraform and it's remote state backend
# for a specific environment. This is done by sourcing a backend config in the
# `dev` folder under the git root directory. Note that the backend config file
# name needs to end with a `.hcl` extension and the file basename is used as
# the environment name provided. It also sets a `TF_VAR_envname` with the
# environment name as value.
#
# For distinguishing the different environments the script also sets `PS1`.
#
# To unset the current environment the user can call the exported
# `deactivate` function.
#
# Usage: `source tfinit.sh <envname>`
deactivate() {
PS1="$_OLD_PS1"
export PS1
unset _OLD_PS1
unset TF_VAR_envname
unset TF_DATA_DIR
unset -f deactivate
}
usage="Usage: source ${BASH_SOURCE:-$0} <envname> [--empty]"
if [[ "${BASH_SOURCE-}" = "$0" ]]; then
echo "$usage" >&2
exit 1
fi
if (( $# > 2 )); then
echo "${usage}" >&2
return 1
fi
envname="$1"
export TF_VAR_envname="${envname}"
export TF_DATA_DIR=".terraform-${envname}"
if [[ "$2" = "--empty" ]]; then
terraform init
else
backendconfig="$(git rev-parse --show-toplevel)/env/${envname}.hcl"
terraform init -reconfigure -backend-config "${backendconfig}"
fi
if [[ "$?" -ne 0 ]]; then
return "$?"
fi
export _OLD_PS1="${_OLD_PS1:=$PS1}"
export PS1="(${envname})${_OLD_PS1}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment