Created
June 4, 2017 16:07
-
-
Save robmorgan/662c6883908c2e9dd9c8a5db690562ed to your computer and use it in GitHub Desktop.
Terraform Multi Env Wrapper
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
#!/bin/bash | |
# This script acts as a wrapper to Terraform. | |
# Is Terraform available? | |
hash terraform 2>/dev/null || { echo >&2 "I require Terraform but it's not installed or in your path. Aborting."; exit 1; } | |
# All of the args are mandatory. | |
if [ $# -lt 3 ]; then | |
echo "Incorrect usage." | |
echo "$ ./tf-wrapper.sh plan production ami-XXXYYYZZ" | |
echo "$ ./tf-wrapper.sh apply staging ami-XXXYYYZZ" | |
exit 1 | |
fi | |
# Pre-flight check is good, let's continue. | |
BUCKET="somebucket-ops-tfstate" | |
ACTION=$1 | |
ENV=$2 | |
AMI=$3 | |
# Be verbose and bail on errors. | |
set -ex | |
# Nab the latest tfstate. | |
aws s3 sync --exclude="*" --include="terraform.tfstate" "s3://${BUCKET}/tfstate/${ENV}/" ./ | |
# Run TF; if this errors out we need to keep going. | |
if [[ $ACTION == "import" || $ACTION == "untaint" || $ACTION == "taint" || $ACTION == "state" ]]; then | |
set +e | |
shift 3 | |
terraform $ACTION "$@" | |
EXIT_CODE=$? | |
else | |
set +e | |
terraform $ACTION -var "environment=${ENV}" \ | |
-var "aws_access_key=${AWS_ACCESS_KEY_ID}" \ | |
-var "aws_secret_key=${AWS_SECRET_ACCESS_KEY}" \ | |
-var "ecs_ami=${AMI}" \ | |
ops/terraform | |
EXIT_CODE=$? | |
fi | |
set -e | |
# Upload tfstate to S3. | |
aws s3 sync --exclude="*" --include="terraform.tfstate" ./ "s3://${BUCKET}/tfstate/${ENV}/" | |
exit $EXIT_CODE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment