-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcleanup.sh
More file actions
executable file
·375 lines (307 loc) · 13.3 KB
/
cleanup.sh
File metadata and controls
executable file
·375 lines (307 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/bin/bash
#
# cleanup.sh - Airbrx Data Gateway Cleanup Script
#
# Removes all AWS resources created by deploy.sh
# USE WITH CAUTION - This will delete all data!
#
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
#------------------------------------------------------------------------------
# Helper Functions
#------------------------------------------------------------------------------
print_header() {
echo ""
echo -e "${BLUE}═══════════════════════════════════════════════════════════════${NC}"
echo -e "${BLUE} $1${NC}"
echo -e "${BLUE}═══════════════════════════════════════════════════════════════${NC}"
echo ""
}
print_step() {
echo -e "${GREEN}▶${NC} $1"
}
print_warning() {
echo -e "${YELLOW}⚠${NC} $1"
}
print_error() {
echo -e "${RED}✗${NC} $1"
}
print_success() {
echo -e "${GREEN}✓${NC} $1"
}
die() {
print_error "$1"
exit 1
}
#------------------------------------------------------------------------------
# Intro
#------------------------------------------------------------------------------
echo ""
echo " +========================= "
echo " =========================== "
echo " =========== -========== "
echo " ==========. .========== "
echo " =========: .. .:========= "
echo " ========- .--.:=-:======== "
echo " ========. .==. .======== "
echo " =======. .----. .======= "
echo " ======: :====== "
echo " =====-. .::::::. -===== "
echo " =====. .========. .===== "
echo " ============================ "
echo " =========================== "
echo " ========================== "
echo ""
echo " A I R B R X"
echo " Data Gateway Cleanup"
echo ""
echo -e "${RED}─────────────────────────────────────────────────────────────────${NC}"
echo ""
echo -e "${RED}WARNING: This script will permanently delete:${NC}"
echo ""
echo " • All S3 buckets and their contents"
echo " • All Lambda functions"
echo " • CloudFront distribution"
echo " • IAM roles and policies"
echo ""
echo -e "${RED}THIS ACTION CANNOT BE UNDONE!${NC}"
echo ""
echo -e "${RED}─────────────────────────────────────────────────────────────────${NC}"
echo ""
#------------------------------------------------------------------------------
# Load Configuration
#------------------------------------------------------------------------------
CONFIG_FILE="${1:-}"
if [[ -z "$CONFIG_FILE" ]]; then
# Look for configs in generated folder
CONFIG_FILES=(generated/*-config.env)
if [[ ! -e "${CONFIG_FILES[0]}" ]]; then
die "No config files found. Run prereq.sh first."
elif [[ ${#CONFIG_FILES[@]} -eq 1 ]]; then
CONFIG_FILE="${CONFIG_FILES[0]}"
print_step "Using config: $CONFIG_FILE"
else
echo "Multiple config files found:"
echo ""
for i in "${!CONFIG_FILES[@]}"; do
echo " $((i+1))) ${CONFIG_FILES[$i]}"
done
echo ""
read -p "Select config [1-${#CONFIG_FILES[@]}]: " choice
if [[ "$choice" =~ ^[0-9]+$ ]] && [[ "$choice" -ge 1 ]] && [[ "$choice" -le ${#CONFIG_FILES[@]} ]]; then
CONFIG_FILE="${CONFIG_FILES[$((choice-1))]}"
else
die "Invalid selection"
fi
fi
fi
if [[ ! -f "$CONFIG_FILE" ]]; then
die "Config file not found: $CONFIG_FILE"
fi
# shellcheck source=/dev/null
source "$CONFIG_FILE"
echo "Configuration: $PREFIX in $AWS_REGION"
echo ""
# Confirm deletion
read -p "Type '${PREFIX}' to confirm deletion: " CONFIRM
if [[ "$CONFIRM" != "$PREFIX" ]]; then
echo "Aborted."
exit 0
fi
echo ""
print_warning "Starting cleanup..."
#------------------------------------------------------------------------------
# Get AWS Account ID
#------------------------------------------------------------------------------
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text 2>/dev/null) || die "AWS CLI not configured"
#------------------------------------------------------------------------------
# Delete CloudFront Distributions
#------------------------------------------------------------------------------
print_header "Deleting CloudFront Distributions"
delete_cloudfront() {
local name="$1"
local search_pattern="$2"
# Find distribution
local dist_id=$(aws cloudfront list-distributions --query \
"DistributionList.Items[?contains(Comment, '${search_pattern}')].Id" \
--output text 2>/dev/null | head -1)
if [[ -z "$dist_id" || "$dist_id" == "None" ]]; then
print_step "$name: No distribution found"
return
fi
print_step "$name: Found distribution $dist_id"
# Check if enabled
local enabled=$(aws cloudfront get-distribution --id "$dist_id" \
--query 'Distribution.DistributionConfig.Enabled' --output text)
if [[ "$enabled" == "true" ]]; then
print_step "$name: Disabling..."
local etag=$(aws cloudfront get-distribution-config --id "$dist_id" --query 'ETag' --output text)
aws cloudfront get-distribution-config --id "$dist_id" --query 'DistributionConfig' > /tmp/dist-config.json
jq '.Enabled = false' /tmp/dist-config.json > /tmp/dist-config-disabled.json
aws cloudfront update-distribution --id "$dist_id" --if-match "$etag" \
--distribution-config file:///tmp/dist-config-disabled.json > /dev/null
print_step "$name: Waiting to disable (may take several minutes)..."
aws cloudfront wait distribution-deployed --id "$dist_id" 2>/dev/null || true
fi
# Delete
local etag=$(aws cloudfront get-distribution --id "$dist_id" --query 'ETag' --output text)
if aws cloudfront delete-distribution --id "$dist_id" --if-match "$etag" 2>/dev/null; then
print_success "$name: Deleted"
else
print_warning "$name: Could not delete (may still be disabling)"
fi
rm -f /tmp/dist-config.json /tmp/dist-config-disabled.json
}
delete_oac() {
local oac_name="$1"
local oac_id=$(aws cloudfront list-origin-access-controls --query \
"OriginAccessControlList.Items[?Name=='${oac_name}'].Id" --output text 2>/dev/null)
if [[ -n "$oac_id" && "$oac_id" != "None" ]]; then
local etag=$(aws cloudfront get-origin-access-control --id "$oac_id" --query 'ETag' --output text)
aws cloudfront delete-origin-access-control --id "$oac_id" --if-match "$etag" 2>/dev/null || true
print_success "Deleted OAC: $oac_name"
fi
}
# Delete all CloudFront distributions (search patterns must match deploy.sh comments)
delete_cloudfront "Frontend" "Airbrx App - ${PREFIX}"
delete_cloudfront "API" "Airbrx api - ${PREFIX}"
delete_cloudfront "Gateway" "Airbrx gateway - ${PREFIX}"
# Delete OAC (only used for S3 frontend)
delete_oac "${PREFIX}-airbrx-app-oac"
#------------------------------------------------------------------------------
# Delete Lambda Functions
#------------------------------------------------------------------------------
print_header "Deleting Lambda Functions"
delete_lambda() {
local func_name="$1"
if aws lambda get-function --function-name "$func_name" &>/dev/null; then
# Delete function URL first
if aws lambda get-function-url-config --function-name "$func_name" &>/dev/null; then
print_step "Deleting function URL: $func_name"
aws lambda delete-function-url-config --function-name "$func_name" 2>/dev/null || true
fi
print_step "Deleting function: $func_name"
aws lambda delete-function --function-name "$func_name"
print_success "Deleted: $func_name"
else
print_step "Function not found: $func_name"
fi
}
delete_lambda "${PREFIX}-airbrx-api"
delete_lambda "${PREFIX}-airbrx-gateway"
delete_lambda "${PREFIX}-airbrx-log-summary"
#------------------------------------------------------------------------------
# Delete S3 Buckets
#------------------------------------------------------------------------------
print_header "Deleting S3 Buckets"
delete_bucket() {
local bucket_name="$1"
if aws s3api head-bucket --bucket "$bucket_name" &>/dev/null; then
print_step "Deleting bucket: $bucket_name"
# Force delete bucket and all contents
if aws s3 rb "s3://${bucket_name}" --force 2>/dev/null; then
print_success "Deleted: $bucket_name"
return
fi
# If force delete failed, bucket likely has versioned objects - delete them
print_step "Removing versioned objects..."
aws s3api delete-objects --bucket "$bucket_name" --delete \
"$(aws s3api list-object-versions --bucket "$bucket_name" \
--query '{Objects: [Versions,DeleteMarkers][].{Key:Key,VersionId:VersionId}}')" \
--quiet 2>/dev/null || true
# Now delete the bucket
aws s3 rb "s3://${bucket_name}" 2>/dev/null || true
print_success "Deleted: $bucket_name"
else
print_step "Bucket not found: $bucket_name"
fi
}
delete_bucket "${PREFIX}-airbrx-admin-storage"
delete_bucket "${PREFIX}-airbrx-gateway-storage"
delete_bucket "${PREFIX}-airbrx-app"
#------------------------------------------------------------------------------
# Delete IAM Roles
#------------------------------------------------------------------------------
print_header "Deleting IAM Roles"
delete_role() {
local role_name="$1"
if aws iam get-role --role-name "$role_name" &>/dev/null; then
# Delete inline policies
print_step "Removing policies from: $role_name"
POLICIES=$(aws iam list-role-policies --role-name "$role_name" --query 'PolicyNames' --output json)
echo "$POLICIES" | jq -r '.[]' 2>/dev/null | while read -r policy; do
aws iam delete-role-policy --role-name "$role_name" --policy-name "$policy" 2>/dev/null || true
done
# Detach managed policies
ATTACHED=$(aws iam list-attached-role-policies --role-name "$role_name" --query 'AttachedPolicies[].PolicyArn' --output json)
echo "$ATTACHED" | jq -r '.[]' 2>/dev/null | while read -r arn; do
aws iam detach-role-policy --role-name "$role_name" --policy-arn "$arn" 2>/dev/null || true
done
print_step "Deleting role: $role_name"
aws iam delete-role --role-name "$role_name"
print_success "Deleted: $role_name"
else
print_step "Role not found: $role_name"
fi
}
delete_role "${PREFIX}-airbrx-api-role"
delete_role "${PREFIX}-airbrx-gateway-role"
delete_role "${PREFIX}-airbrx-log-summary-role"
#------------------------------------------------------------------------------
# Delete Temporary Build Files
#------------------------------------------------------------------------------
print_header "Deleting Temporary Files"
# Remove any leftover /tmp/airbrx-deploy-* directories from failed/interrupted deploys
TEMP_DIRS=$(ls -d /tmp/airbrx-deploy-* 2>/dev/null || true)
if [[ -n "$TEMP_DIRS" ]]; then
for dir in $TEMP_DIRS; do
print_step "Removing: $dir"
rm -rf "$dir"
done
print_success "Removed temporary build directories"
else
print_step "No temporary build directories found"
fi
#------------------------------------------------------------------------------
# Delete Generated Files
#------------------------------------------------------------------------------
print_header "Deleting Generated Files"
CONFIG_DIR=$(dirname "$CONFIG_FILE")
if [[ -d "$CONFIG_DIR" ]]; then
print_step "Removing generated files for: ${PREFIX}"
rm -f "${CONFIG_DIR}/${PREFIX}-config.env"
rm -f "${CONFIG_DIR}/${PREFIX}-god-pat.json"
rm -f "${CONFIG_DIR}/${PREFIX}-lambda-trust-policy.json"
rm -f "${CONFIG_DIR}/${PREFIX}-airbrx-api-policy.json"
rm -f "${CONFIG_DIR}/${PREFIX}-airbrx-gateway-policy.json"
rm -f "${CONFIG_DIR}/${PREFIX}-airbrx-log-summary-policy.json"
rm -f "${CONFIG_DIR}/${PREFIX}-deployer-policy.json"
print_success "Removed generated files"
# Remove generated directory if empty
if [[ -d "$CONFIG_DIR" ]] && [[ -z "$(ls -A "$CONFIG_DIR" 2>/dev/null)" ]]; then
rmdir "$CONFIG_DIR"
print_step "Removed empty generated/ directory"
fi
fi
#------------------------------------------------------------------------------
# Cleanup Complete
#------------------------------------------------------------------------------
print_header "Cleanup Complete"
echo "
All Airbrx resources for '${PREFIX}' have been deleted:
✓ CloudFront distributions (frontend, api, gateway)
✓ S3 buckets (admin-storage, gateway-storage, app)
✓ Lambda functions (api, gateway, log-summary)
✓ IAM roles and policies
✓ Generated config files
Note: CloudWatch log groups may still exist and can be deleted manually:
aws logs delete-log-group --log-group-name /aws/lambda/${PREFIX}-airbrx-api
aws logs delete-log-group --log-group-name /aws/lambda/${PREFIX}-airbrx-gateway
aws logs delete-log-group --log-group-name /aws/lambda/${PREFIX}-airbrx-log-summary
"
print_success "Cleanup complete!"