Last active
May 24, 2021 08:54
-
-
Save timbirk/b12c0ee8ddf5e76a4da733c08b1d24fa to your computer and use it in GitHub Desktop.
A script used as a shell step in Jenkins jobs to start / stop RDS instances.
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
#!/usr/bin/env bash | |
set +x | |
ACTION="start" | |
ERR_RETRIES=3 | |
STEP_SLEEP=60 | |
MACHINE_TIMEOUT=3600 | |
RDS_INSTANCE={envname}-mysql-rds | |
REGION=eu-west-1 | |
# No need to edit below | |
STEP_COUNT=0 | |
ERR_COUNT=0 | |
ERR_CODE=0 | |
while true; do | |
STATE="$(aws --region $REGION rds describe-db-instances --db-instance-identifier $RDS_INSTANCE | jq --raw-output '.DBInstances | .[].DBInstanceStatus')" | |
case "$STATE" in | |
"available") | |
case "$ACTION" in | |
"stop") | |
aws --region eu-west-1 rds stop-db-instance --db-instance-identifier $RDS_INSTANCE | |
;; | |
"start") | |
echo "Success! RDS DB Instance $RDS_INSTANCE is $STATE" | |
break | |
;; | |
esac | |
;; | |
"stopped") | |
case "$ACTION" in | |
"stop") | |
echo "Success! RDS DB Instance $RDS_INSTANCE is $STATE" | |
break | |
;; | |
"start") | |
aws --region eu-west-1 rds start-db-instance --db-instance-identifier $RDS_INSTANCE | |
;; | |
esac | |
;; | |
"modifying" | "rebooting" | "starting" | "stopping") | |
echo "RDS DB Instance $RDS_INSTANCE is $STATE. Instance $ACTION in progress..." | |
;; | |
*) | |
let "ERR_COUNT++" | |
if [[ $ERR_COUNT -gt 3 ]] ; then | |
echo "Failed to $ACTION RDS Instance $RDS_INSTANCE after $ERR_COUNT attempts. Failed with state: $STATE" | |
ERR_CODE=1 | |
break | |
fi | |
echo "Invalid state \"$STATE\" Retrying..." | |
;; | |
esac | |
TIME_RUNNING=$(($STEP_COUNT * $STEP_SLEEP)) | |
if [[ $TIME_RUNNING -ge $MACHINE_TIMEOUT ]] ; then | |
echo "Trying to start RDS Instance $RDS_INSTANCE timed out with state: $STATE" | |
break | |
fi | |
let "STEP_COUNT++" | |
sleep $STEP_SLEEP | |
done | |
exit $ERR_CODE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment