|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +### This script expects a file named instances.txt with one AWS instance id per line. |
| 4 | +### It will go through those instances, and kill them if they are running |
| 5 | +### To be used in case of runner issues or security concerns to quickly kill a subset of runners. |
| 6 | +### Note this will stop and fail tests that are currently running. |
| 7 | + |
| 8 | +# Set your AWS region |
| 9 | +REGION="us-east-1" |
| 10 | + |
| 11 | +# Initialize counters |
| 12 | +NON_EXISTENT_COUNT=0 |
| 13 | +RUNNING_COUNT=0 |
| 14 | +NOT_RUNNING_COUNT=0 |
| 15 | + |
| 16 | +# Initialize arrays to keep track of results |
| 17 | +TERMINATED_INSTANCES=() |
| 18 | +EXISTED_BUT_NOT_RUNNING=() |
| 19 | +NON_EXISTENT_INSTANCES=() |
| 20 | + |
| 21 | +# Read instance IDs from file into an array |
| 22 | +mapfile -t INSTANCE_IDS < instances.txt |
| 23 | +TOTAL_INSTANCES=${#INSTANCE_IDS[@]} |
| 24 | + |
| 25 | +# Process each instance |
| 26 | +for ((i=0; i<TOTAL_INSTANCES; i++)); do |
| 27 | + INSTANCE_ID="${INSTANCE_IDS[i]}" |
| 28 | + echo -ne "\rWorking on instance: $INSTANCE_ID ($((i+1))/$TOTAL_INSTANCES) | Non-existent: $NON_EXISTENT_COUNT | Running: $RUNNING_COUNT | Not running: $NOT_RUNNING_COUNT" |
| 29 | + |
| 30 | + # Check if instance exists |
| 31 | + if aws ec2 describe-instances --instance-ids "$INSTANCE_ID" --region "$REGION" &> /dev/null; then |
| 32 | + # Check if instance is running |
| 33 | + STATUS=$(aws ec2 describe-instances --instance-ids "$INSTANCE_ID" --region "$REGION" --query 'Reservations[0].Instances[0].State.Name' --output text) |
| 34 | + if [ "$STATUS" = "running" ]; then |
| 35 | + # Terminate instance |
| 36 | + aws ec2 terminate-instances --instance-ids "$INSTANCE_ID" --region "$REGION" &> /dev/null |
| 37 | + TERMINATED_INSTANCES+=("$INSTANCE_ID") |
| 38 | + RUNNING_COUNT=$((RUNNING_COUNT + 1)) |
| 39 | + else |
| 40 | + EXISTED_BUT_NOT_RUNNING+=("$INSTANCE_ID") |
| 41 | + NOT_RUNNING_COUNT=$((NOT_RUNNING_COUNT + 1)) |
| 42 | + fi |
| 43 | + else |
| 44 | + NON_EXISTENT_INSTANCES+=("$INSTANCE_ID") |
| 45 | + NON_EXISTENT_COUNT=$((NON_EXISTENT_COUNT + 1)) |
| 46 | + fi |
| 47 | +done |
| 48 | + |
| 49 | +echo -e "\n\nTerminated instances:" |
| 50 | +printf '%s\n' "${TERMINATED_INSTANCES[@]}" |
| 51 | +echo "" |
| 52 | +echo "Existed but not running:" |
| 53 | +printf '%s\n' "${EXISTED_BUT_NOT_RUNNING[@]}" |
| 54 | +echo "" |
| 55 | +echo "Non-existent instances:" |
| 56 | +printf '%s\n' "${NON_EXISTENT_INSTANCES[@]}" |
0 commit comments