Skip to content

Instantly share code, notes, and snippets.

@rtfpessoa
Last active December 8, 2020 17:50
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 rtfpessoa/e1be0706c3e4163d274db00108d84115 to your computer and use it in GitHub Desktop.
Save rtfpessoa/e1be0706c3e4163d274db00108d84115 to your computer and use it in GitHub Desktop.
Estimate Terraform Costs
#!/usr/bin/env bash
# Runs https://github.com/antonbabenko/terraform-cost-estimation with sanitization
#
# Depends on:
# - terraform cli >= 0.12
# - curl
# - jq >= 1.6
set -eo pipefail
function help {
echo "usage: $0 [MODE] [TERRAFORM-DIRECTORY]"
echo ""
echo " Mode (how to estimate costs)"
echo " plan - estimates the cost before a deployment"
echo " state - estimates the cost after a deployment"
}
MODE="state"
if [[ -n "$1" ]]
then
if [[ "$1" == "plan" || "$1" == "state" ]]
then
MODE="$1"
else
echo "Could not find mode with name '$1'"
help
exit 1
fi
fi
TERRAFORM_DIRECTORY="$(pwd)"
if [[ -n "$2" ]]
then
if [[ -d "$2" ]]
then
TERRAFORM_DIRECTORY="$2"
else
echo "Could not find directory with path '$2'"
help
exit 1
fi
fi
SCRIPT_DIRECTORY="$( cd "$( dirname "$0" )" && pwd )"
WORKDIR="$(mktemp -t -d estimate-costs-XXXXXX)"
TFPLAN="${WORKDIR}/plan.tfplan"
TFPLAN_JSON="${WORKDIR}/plan.json"
TFPLAN_JSON_SANITIZED="${WORKDIR}/plan-sanitized.json"
SANITIZATION_SCRIPT="${SCRIPT_DIRECTORY}/terraform.jq"
trap cleanup EXIT
cleanup() {
rm -rf ${WORKDIR}
}
if [ ! -f "${SANITIZATION_SCRIPT}" ]
then
echo "Downloading terraform sanitization script..."
SANITIZATION_SCRIPT="${WORKDIR}/terraform.jq"
curl -fsSL https://raw.githubusercontent.com/antonbabenko/terraform-cost-estimation/master/terraform.jq -o "${SANITIZATION_SCRIPT}"
fi
if [ "${MODE}" == "plan" ]
then
terraform -chdir="${TERRAFORM_DIRECTORY}" plan -out="${TFPLAN}" > /dev/null
terraform -chdir="${TERRAFORM_DIRECTORY}" show -json "${TFPLAN}" | jq > "${TFPLAN_JSON}"
elif [ "${MODE}" == "state" ]
then
terraform -chdir="${TERRAFORM_DIRECTORY}" state pull | jq > "${TFPLAN_JSON}"
else
echo "Could not find mode with name '$MODE'"
help
exit 1
fi
# Sanitize plan
cat "${TFPLAN_JSON}" | jq -cf ${SANITIZATION_SCRIPT} > "${TFPLAN_JSON_SANITIZED}"
# Check costs
cat "${TFPLAN_JSON_SANITIZED}" | curl -s -X POST -H "Content-Type: application/json" -d @- https://cost.modules.tf/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment