Skip to content

Instantly share code, notes, and snippets.

@needleshaped
Forked from kitos9112/get-terraform.sh
Last active May 20, 2021 14:22
Show Gist options
  • Save needleshaped/0022791d1d4d4dc56ecfcce69083a248 to your computer and use it in GitHub Desktop.
Save needleshaped/0022791d1d4d4dc56ecfcce69083a248 to your computer and use it in GitHub Desktop.
Bash script that automatically updates to latest version of Terraform and TFlint
#!/bin/bash
###########################################################################
# Update or install latest terraform/tflint binary versions, if existing version differ or is absent
# https://gist.github.com/needleshaped/0022791d1d4d4dc56ecfcce69083a248
##########################################################################
# Arguments and parameters
INSTALL_DIR="${1:-$HOME/bin}"
SUDO= # empty or "sudo"
# Checks
REGEX="^PATH=.*\K$INSTALL_DIR(?=.*)"
if [[ $(env | grep -oP "${REGEX}") != "$INSTALL_DIR" ]]; then
echo "Looks like your install directory $INSTALL_DIR is not in your PATH. Make sure you export it"
fi
main_() {
echo "Checking versions and installing, if necessary"
INSTALLED_VERSION=$("$INSTALL_DIR"/terraform --version | grep -Poie '\d+.\d+.\d+')
LATEST_VERSION=$(curl -s https://api.github.com/repos/hashicorp/terraform/releases/latest | grep -oP '"tag_name": "[v]\K(.*)(?=")')
ZIP="terraform_${LATEST_VERSION}_linux_amd64.zip"
URL="https://releases.hashicorp.com/terraform/${LATEST_VERSION}/${ZIP}"
BINARY=terraform
download_and_install
INSTALLED_VERSION=$("$INSTALL_DIR"/tflint --version | awk '{if (NR == 1 ) print $3}')
LATEST_VERSION=$(curl -s https://api.github.com/repos/terraform-linters/tflint/tags | grep -m1 -oP '"name": "[v]\K(.*)(?=")')
ZIP="tflint_linux_amd64.zip"
URL="https://github.com/terraform-linters/tflint/releases/download/${LATEST_VERSION}/${ZIP}"
BINARY=tflint
download_and_install
}
download_and_install() {
if [[ "$LATEST_VERSION" != "$INSTALLED_VERSION" ]]; then
echo "# Version mismatch, installing $BINARY $INSTALLED_VERSION > $LATEST_VERSION ..."
cd /tmp
wget -nv "$URL"
$SUDO unzip -o "$ZIP" -d "$INSTALL_DIR" # or separately, install/rm, mv/chmod, etc
rm -v "$ZIP"
ls -la "${INSTALL_DIR}/$BINARY"*
echo "# Done."
else
echo "# Nothing done. Latest $BINARY, $INSTALLED_VERSION already installed."
fi
}
main_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment