From a59ce8050c90b266181ef05c38563f4405ff7d83 Mon Sep 17 00:00:00 2001 From: Kenneth Bingham Date: Thu, 5 Oct 2023 12:56:49 -0400 Subject: [PATCH] improve housekeeper script for fablab aws --- zititest/scripts/housekeeper-aws.bash | 72 ++++++++++++++++----------- 1 file changed, 43 insertions(+), 29 deletions(-) diff --git a/zititest/scripts/housekeeper-aws.bash b/zititest/scripts/housekeeper-aws.bash index 6bf3e8410..40449b315 100644 --- a/zititest/scripts/housekeeper-aws.bash +++ b/zititest/scripts/housekeeper-aws.bash @@ -6,13 +6,14 @@ BASENAME=$(basename "$0") function describe_instances() { cd "$(mktemp -d)" local oldest=$1 + local state=$2 for region in us-east-1 us-west-2 do local outfile="aged-fablab-instances-${region}.json" aws --region "$region" ec2 describe-instances \ - --filters "Name=instance-state-name,Values=running" \ + --filters "Name=instance-state-name,Values=${state}" \ "Name=tag:source,Values=fablab" \ - --query "Reservations[*].Instances[*].{InstanceId:InstanceId,LaunchTime:LaunchTime,Tags:Tags}" \ + --query "Reservations[*].Instances[*].{InstanceId:InstanceId,LaunchTime:LaunchTime,State:State.Name,Tags:Tags}" \ | jq -r \ --arg region "$region" \ --arg oldest "$oldest" ' @@ -20,7 +21,7 @@ function describe_instances() { .[] |.[] |select(.LaunchTime < $oldest) - |{InstanceId: .InstanceId, Region: $region, LaunchTime: .LaunchTime, Tags: .Tags} + |{InstanceId: .InstanceId, Region: $region, LaunchTime: .LaunchTime, State: .State, Tags: .Tags} ] ' \ | tee $outfile \ @@ -65,30 +66,43 @@ check_json_file(){ fi } -case "${1:-}" in - --help|-h) - echo "Usage: $BASENAME [--oldest ISO8601|stop FILE|terminate FILE]" - exit 0 - ;; - stop) - check_json_file "${2:-}" - stop_instances "${2:-}" - exit - ;; - terminate) - check_json_file "${2:-}" - terminate_instances "${2:-}" - exit - ;; - --oldest) - OLDEST="${2:-}" - if ! [[ "$OLDEST" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2} ]]; - then - echo "Usage: $BASENAME --oldest ISO8601 (e.g. 2024-01-01 or 2024-01-01T12:00:00Z)" - exit 1 - fi - shift 2 - ;; -esac +while (( $# )) +do + case "${1}" in + stop) + check_json_file "${2:-}" + stop_instances "${2:-}" + exit + ;; + terminate) + check_json_file "${2:-}" + terminate_instances "${2:-}" + exit + ;; + --age) + AGE="${2:-}" + if ! [[ "$AGE" =~ ^[0-9]+$ ]]; + then + echo "Usage: $BASENAME --age DAYS" + exit 1 + fi + shift 2 + ;; + --state) + STATE="${2:-}" + if ! [[ "$STATE" =~ ^(running|stopped)$ ]]; + then + echo "Usage: $BASENAME --state (running|stopped)" + exit 1 + else + shift 2 + fi + ;; + --help|\?|*) + echo "Usage: $BASENAME [--age DAYS|--state (running|stopped)|stop FILE|terminate FILE]" + exit 0 + ;; + esac +done -describe_instances "${OLDEST:-$(date -d '-2 days' -Id)}" \ No newline at end of file +describe_instances "$(date -d "-${AGE:-7} days" -Id)" "${STATE:-running}"