Created
September 17, 2019 07:55
-
-
Save christhomas/ea90cc55502a3f804f0b6a8e59d05e60 to your computer and use it in GitHub Desktop.
How to use the terraform workspace command to keep multiple state configurations without clashing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# usage: chris-terraform ... (any terraform command you want) | |
role=XYZ | |
credentials=(`aws sts assume-role --role-arn "${role}" --role-session-name terraform --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' --output text`) | |
AWS_ACCESS_KEY_ID=${credentials[0]} | |
AWS_SECRET_ACCESS_KEY=${credentials[1]} | |
AWS_SESSION_TOKEN=${credentials[2]} | |
AWS_SECURITY_TOKEN=${credentials[2]} | |
env_file=${PWD}/.terraform/environment | |
TF_ENV=() | |
[ ! -z "${TF_LOG}" ] && TF_ENV[0]="--env TF_LOG=${TF_LOG}" | |
[ ! -z "${TF_WORKSPACE}" ] && TF_ENV[1]="--env TF_WORKSPACE=${TF_WORKSPACE}" | |
[ -f "${env_file}" ] && TF_ENV[2]="--env TF_DATA_DIR=.terraform/$(cat ${env_file})" | |
# if using workspace command, then remove the TF_DATA_DIR env var | |
[ "$1" == "workspace" ] && TF_ENV[2]= | |
docker run ${INTERACTIVE} ${TF_ENV[@]} \ | |
--env AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID} \ | |
--env AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY} \ | |
--env AWS_SESSION_TOKEN=${AWS_SESSION_TOKEN} \ | |
--env AWS_SECURITY_TOKEN=${AWS_SECURITY_TOKEN} \ | |
--network backbone \ | |
-v ${PWD}:/app:consistent \ | |
-w /app \ | |
hashicorp/terraform:light $@ | |
# Usage: | |
# | |
# chris-terraform workspace new localstack | |
# chris-terraform init terraform/localstack <- this directory contains all the terraform files for localstack) | |
# | |
# chris-terraform workspace new staging | |
# chris-terraform init terraform/staging <- again, for staging |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment