|
| 1 | +#!/bin/bash |
| 2 | +# Find tutorial resources that may have been left behind by failed script runs. |
| 3 | +# Searches by the 'tutorial' tag that all tutorial scripts apply to resources. |
| 4 | +# Usage: ./find-orphans.sh [tutorial-id] |
| 5 | +# Example: ./find-orphans.sh kinesis |
| 6 | +# ./find-orphans.sh (finds all tutorial-tagged resources) |
| 7 | +set -eo pipefail |
| 8 | + |
| 9 | +FILTER="${1:-}" |
| 10 | + |
| 11 | +echo "Searching for resources tagged with 'tutorial'..." |
| 12 | +echo "" |
| 13 | + |
| 14 | +if [ -n "$FILTER" ]; then |
| 15 | + echo "Filter: tutorial=$FILTER" |
| 16 | + RESULTS=$(aws resourcegroupstaggingapi get-resources \ |
| 17 | + --tag-filters "Key=tutorial,Values=$FILTER" \ |
| 18 | + --query 'ResourceTagMappingList[].ResourceARN' --output text 2>/dev/null) |
| 19 | +else |
| 20 | + RESULTS=$(aws resourcegroupstaggingapi get-resources \ |
| 21 | + --tag-filters "Key=tutorial" \ |
| 22 | + --query 'ResourceTagMappingList[].ResourceARN' --output text 2>/dev/null) |
| 23 | +fi |
| 24 | + |
| 25 | +if [ -z "$RESULTS" ]; then |
| 26 | + echo "No orphaned resources found." |
| 27 | + exit 0 |
| 28 | +fi |
| 29 | + |
| 30 | +echo "Found resources:" |
| 31 | +echo "$RESULTS" | tr '\t' '\n' | while read ARN; do |
| 32 | + # Extract service and resource type from ARN |
| 33 | + SERVICE=$(echo "$ARN" | cut -d: -f3) |
| 34 | + TYPE=$(echo "$ARN" | cut -d: -f6 | cut -d/ -f1) |
| 35 | + NAME=$(echo "$ARN" | rev | cut -d/ -f1 | rev) |
| 36 | + printf " %-20s %-20s %s\n" "$SERVICE" "$TYPE" "$NAME" |
| 37 | +done |
| 38 | + |
| 39 | +echo "" |
| 40 | +TOTAL=$(echo "$RESULTS" | tr '\t' '\n' | wc -l) |
| 41 | +echo "Total: $TOTAL resources" |
| 42 | +echo "" |
| 43 | +echo "To delete these manually, use the appropriate AWS CLI delete commands." |
| 44 | +echo "To delete all resources from a specific tutorial:" |
| 45 | +echo " aws resourcegroupstaggingapi get-resources --tag-filters Key=tutorial,Values=<id> --query 'ResourceTagMappingList[].ResourceARN' --output text" |
0 commit comments