Skip to content

Instantly share code, notes, and snippets.

@huynhbaoan
Last active March 1, 2025 12:32
Show Gist options
  • Select an option

  • Save huynhbaoan/4eabbab6364e06ba124d4e4c4be5e5e3 to your computer and use it in GitHub Desktop.

Select an option

Save huynhbaoan/4eabbab6364e06ba124d4e4c4be5e5e3 to your computer and use it in GitHub Desktop.
Tfw
DIR_PATH=$(pwd | sed 's%^.*account-build%account-build%g')
AWS_SHORT_ACCOUNT_ID=$(echo ${DIR_PATH} | /bin/awk -F "/" '{print $2}')
APPACC_ID=$( cat account-variables.tf | tr '\n' ' ' | sed -e 's/.*variable[ \t]*"account-id"[ \t]*{[ \t]*default = "\([0-9]*\)"[ \t]*}.*/\1/g' )
STACKNAME=$(basename "${DIR_PATH}")
AWS_ACCOUNT_NUMBER=$(aws sts get-caller-identity --query 'Account' --output text)
S3_CF_BUCKET="${AWS_ACCOUNT_NUMBER}-config"
CORRECT_ACC_FLAG="false"
ACCOUNT_TYPE=$( cat account-variables.tf | grep account-type | awk -F '"' '{print tolower($4)}' )
ROLE_NAME=$(aws sts get-caller-identity | jq '.Arn' | awk -F "/" '{ print $2 }')
APPACC_NAME=$(cat account-variables.tf | grep account-shortname | awk -F '"' '{print tolower($4)}')
TENANTACC_ID=$(cat variables.tf | grep tenant-account-id | awk -F '"' '{print tolower($4)}')
TENANTACC_NAME=$(cat variables.tf | grep tenant-account-name | awk -F '"' '{print tolower($4)}')
# --- New functions added for importing and removing resources ---
import_resource() {
local resource_address="$1"
local resource_id="$2"
$INIT_COMMAND
terraform get
terraform import "$resource_address" "$resource_id"
if [ $? -ne 0 ]; then
echo "Terraform import failed for $resource_address with ID $resource_id"
exit 1
fi
if [ -d "upload" ]; then
aws s3 sync upload s3://${S3_CF_BUCKET}/${STACKNAME}
fi
}
remove_resource() {
local resource_address="$1"
$INIT_COMMAND
terraform get
terraform state rm "$resource_address"
if [ $? -ne 0 ]; then
echo "Terraform state remove failed for $resource_address"
exit 1
fi
if [ -d "upload" ]; then
aws s3 sync upload s3://${S3_CF_BUCKET}/${STACKNAME}
fi
}
# --- End of new functions ---
COMMAND="${1}"
BUILD_SERVER="${2}"
#
# MAIN
#
if [ -z "${COMMAND}" ]; then
echo "'COMMAND' must be plan or apply"
invalid_parameters=true
fi
if [ -z "${STACKNAME}" ]; then
echo "'STACKNAME' must not be empty"
invalid_parameters=true
fi
if [ -z "${AWS_ACCOUNT_NUMBER}" ]; then
echo "'AWS_ACCOUNT_NUMBER' must not be empty"
invalid_parameters=true
fi
if [ "${invalid_parameters}" = true ]; then
exit 1
fi
if [ "$BUILD_SERVER" = "true" ]; then
export TF_IN_AUTOMATION="yes"
INIT_COMMAND="terraform init -upgrade -plugin-dir=${TERRAFORM_PLUGIN_DIR}"
else
INIT_COMMAND="terraform init -upgrade"
fi
#use a prefix parameter assignment for this one, then create the targets strin
#usage example (multiple targets): targets=aws_network_acl_rule.ib-private-nonprod-vpc-nacl-ingress-rule505,module.ib-private-zone.null_resource.accept_zone_association ./terraform.sh plan
if [[ ! -z "${targets// }" ]]; then
IFS=','
read -ra ELEM <<< "${targets// }"
for i in "${ELEM[@]}"; do
TARGETS_LIST+="-target=$i"' '
done
TARGETS="$(echo -e "${TARGETS_LIST}" | sed -e 's/[[:space:]]*$//')"
echo TARGETS: ${TARGETS}
unset IFS
fi
res=$( terraform -v | grep 'Terraform v' | awk -F "v" '{print $2}' | awk -F "." '{print $1$2$3}' )
if [ $res -lt 1411 ]; then
echo "This script should be used with terraform 0.14.11 or greater!!!"
#exit 1
fi
echo "This script should only be run with terraform version 0.14.11 or above"
if [ "${ACCOUNT_TYPE}" == "nonprod" ]; then
PROV_ACC_ID=${HIP_NP_ACC_ID}
PROV_ACC_NAME=${HIP_NP_ACC_NAME}
PROV_ACC_KMS=${HIP_NP_ACC_KMS}
PROV_ACC_SSH=${HIP_NP_ACC_SSH}
aws iam list-account-aliases --query 'AccountAliases[*]' --output text | grep -q $PROV_ACC_NAME
if [ $? == 0 ]; then CORRECT_ACC_FLAG="true"; fi
fi
if [ "${ACCOUNT_TYPE}" == "preprod" ]; then
PROV_ACC_ID=${HIP_PP_ACC_ID}
PROV_ACC_NAME=${HIP_PP_ACC_NAME}
PROV_ACC_KMS=${HIP_PP_ACC_KMS}
PROV_ACC_SSH=${HIP_PP_ACC_SSH}
aws iam list-account-aliases --query 'AccountAliases[*]' --output text | grep -q $PROV_ACC_NAME
if [ $? == 0 ]; then CORRECT_ACC_FLAG="true"; fi
fi
if [ "${ACCOUNT_TYPE}" == "prod" ]; then
PROV_ACC_ID=${HIP_P_ACC_ID}
PROV_ACC_NAME=${HIP_P_ACC_NAME}
PROV_ACC_KMS=${HIP_P_ACC_KMS}
PROV_ACC_SSH=${HIP_P_ACC_SSH}
aws iam list-account-aliases --query 'AccountAliases[*]' --output text | grep -q $PROV_ACC_NAME
if [ $? == 0 ]; then CORRECT_ACC_FLAG="true"; fi
fi
if [ "$CORRECT_ACC_FLAG" == "false" ]; then
echo "Error: You need active ${PROV_ACC_NAME} credentials to run automation in ${AWS_SHORT_ACCOUNT_ID}"
exit 1
fi
echo "Generating providers.tf for ${APPACC_NAME}"
if [ -f ../../templates/template-providers.tf ]; then
cp ../../templates/template-providers.tf providers.tf
sed -i "s/__APPACC_ID__/${APPACC_ID}/g" providers.tf
sed -i "s/__APPACC_NAME__/${APPACC_NAME}/g" providers.tf
sed -i "s/__TENANTACC_ID__/${TENANTACC_ID}/g" providers.tf
else
cp ../../../templates/template-providers.tf providers.tf
sed -i "s/__APPACC_ID__/${APPACC_ID}/g" providers.tf
sed -i "s/__APPACC_NAME__/${APPACC_NAME}/g" providers.tf
sed -i "s/__TENANTACC_ID__/${TENANTACC_ID}/g" providers.tf
fi
if [[ ${ROLE_NAME} == AUR-Resource-AWS-services*-2FA-hip-admin ]]; then
sed -i "s/__APPACC_ROLE_NAME__/AUR-Resource-AWS-${APPACC_NAME}-2FA-hip-admin/g" providers.tf
sed -i "s/__TENANTACC_ROLE_NAME__/AUR-Resource-AWS-${TENANTACC_NAME}-2FA-hip-admin/g" providers.tf
else
if [[ $COMMAND == 'apply' ]]; then
echo "Invalid command! Apply can only be called from the services hip-admin role"
exit 1
fi
sed -i "s/__APPACC_ROLE_NAME__/HIPViewOnlyRole/g" providers.tf
sed -i "s/__TENANTACC_ROLE_NAME__/HIPViewOnlyRole/g" providers.tf
fi
# PLAN
if [ "${COMMAND}" == "plan" ]; then
if [ -d pre-plan-tasks ] ; then
echo "found pre-plan-tasks directory -- checking"
cd pre-plan-tasks
for preplantask in *.sh ; do
if [ -x ${preplantask} ] ; then
echo "...found pre-plan-task ${preplantask} .. executing.."
./${preplantask}
fi
done
cd ..
fi
# syncing upload in plan mode
if [ -d "upload" ]; then
aws s3 sync upload s3://${S3_CF_BUCKET}/${STACKNAME} --dryrun
fi
$INIT_COMMAND
terraform get
set +e
plan_code="terraform plan -detailed-exitcode ${TARGETS}"
eval "$plan_code"; echo $? > status
return_code=$(cat status)
set -e
if [ "$return_code" == 1 ]; then
exit 1
fi
exit 0
fi
# APPLY
if [ "${COMMAND}" == "apply" ]; then
if [ -d pre-apply-tasks ] ; then
echo "found pre-apply-tasks directory -- checking"
cd pre-apply-tasks
for preapplytask in *.sh ; do
if [ -x ${preapplytask} ] ; then
echo "...found pre-apply-task ${preapplytask} .. executing.."
./${preapplytask}
fi
done
cd ..
fi
$INIT_COMMAND
terraform get
apply_code="terraform apply -auto-approve ${TARGETS}"
eval "$apply_code"; echo $? > status
return_code=$(cat status)
# syncing upload
if [ -d "upload" ]; then
aws s3 sync upload s3://${S3_CF_BUCKET}/${STACKNAME}
fi
if [[ $return_code -ne 0 ]]; then
echo "ERROR. Terraform apply failed"
exit $return_code
fi
fi
# NEW: IMPORT RESOURCE in LZ account
if [ "${COMMAND}" == "import" ]; then
RESOURCE_ADDRESS=${3}
RESOURCE_ID=${4}
if [ -z "${RESOURCE_ADDRESS}" ] || [ -z "${RESOURCE_ID}" ]; then
echo "For import command, please provide resource address and resource id."
exit 1
fi
import_resource "${RESOURCE_ADDRESS}" "${RESOURCE_ID}"
exit 0
fi
# NEW: REMOVE RESOURCE in LZ account
if [ "${COMMAND}" == "remove" ]; then
RESOURCE_ADDRESS=${3}
if [ -z "${RESOURCE_ADDRESS}" ]; then
echo "For remove command, please provide resource address."
exit 1
fi
remove_resource "${RESOURCE_ADDRESS}"
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment