Created
May 4, 2024 13:18
-
-
Save theendofline/60ce0abccbb24cc5cbae2f7ab9ade9f9 to your computer and use it in GitHub Desktop.
Created for updating or installing the Terraform for specific purposes when the destination is different than the default one. In this case the destination is /usr/loca/bin/ instead of default /usr/bin/
This file contains hidden or 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 | |
# Required system tools | |
SYSTEM_DEPS=( | |
curl | |
jq | |
unzip | |
wget | |
) | |
# Install missing dependencies | |
for SYSTEM_DEP in ${SYSTEM_DEPS[*]}; do | |
if ! which $SYSTEM_DEP >/dev/null; then | |
echo -e "[+] Installing missing dependency: $SYSTEM_DEP" | |
sudo apt-get install -y $SYSTEM_DEP | |
fi | |
done | |
# Retrieve latest terraform version | |
LATEST_RELEASE=$(curl -s https://checkpoint-api.hashicorp.com/v1/check/terraform | jq -r .current_version) | |
if [ $? -ne 0 ]; then | |
echo "Error fetching latest Terraform version" | |
exit 1 | |
fi | |
# Check whether install or update is required | |
INSTALL_REQUIRED=0 | |
if ! which terraform >/dev/null; then | |
echo -e "'Terraform' tool not found" | |
INSTALL_REQUIRED=1 | |
else | |
CURRENT_RELEASE=$(terraform version -json | jq -r .terraform_version 2>/dev/null) | |
if [ $? -ne 0 ] || [[ ${LATEST_RELEASE} != $CURRENT_RELEASE ]]; then | |
echo -e "'Terraform' tool is outdated" | |
INSTALL_REQUIRED=1 | |
fi | |
fi | |
# Install latest version if required | |
if [[ $INSTALL_REQUIRED > 0 ]]; then | |
echo "[+] Installing Terraform ${LATEST_RELEASE} ..." | |
TEMP_FOLDER=$(mktemp -d -t terraform_install_XXXX) | |
pushd ${TEMP_FOLDER} | |
FILENAME=terraform_${LATEST_RELEASE}_linux_amd64.zip | |
# Download latest version | |
if ! wget https://releases.hashicorp.com/terraform/${LATEST_RELEASE}/$FILENAME; then | |
echo "Failed to download Terraform" | |
popd | |
exit 1 | |
fi | |
if ! unzip $FILENAME; then | |
echo "Failed to unzip Terraform" | |
popd | |
exit 1 | |
fi | |
rm $FILENAME | |
# Extract and link executible in /usr/local/bin folder | |
LINKED_TARGET="/usr/local/bin/terraform" | |
BIN_TARGET="${LINKED_TARGET}-v${LATEST_RELEASE}" | |
sudo mv terraform ${BIN_TARGET} | |
sudo ln -sf ${BIN_TARGET} ${LINKED_TARGET} | |
echo -e "Installation complete: ${LINKED_TARGET}" | |
popd | |
rm -r ${TEMP_FOLDER} | |
else | |
echo "Latest version of Terraform (${LATEST_RELEASE}) already installed." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment