-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy paths3-gettingstarted.sh
More file actions
467 lines (399 loc) · 14.3 KB
/
s3-gettingstarted.sh
File metadata and controls
467 lines (399 loc) · 14.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#!/bin/bash
# S3 Getting Started - Create a bucket, upload and download objects, copy to a
# folder prefix, enable versioning, configure encryption and public access
# blocking, tag the bucket, list objects and versions, and clean up.
set -eE
set -o pipefail
# ============================================================================
# Prerequisites check
# ============================================================================
CONFIGURED_REGION=$(aws configure get region 2>/dev/null || true)
if [ -z "$CONFIGURED_REGION" ] && [ -z "$AWS_DEFAULT_REGION" ] && [ -z "$AWS_REGION" ]; then
echo "ERROR: No AWS region configured. Run 'aws configure' or set AWS_DEFAULT_REGION."
exit 1
fi
# Verify AWS credentials are configured
if ! aws sts get-caller-identity &>/dev/null; then
echo "ERROR: AWS credentials not configured or invalid. Run 'aws configure'."
exit 1
fi
# ============================================================================
# Setup: logging, temp directory, resource tracking
# ============================================================================
UNIQUE_ID=$(head -c 6 /dev/urandom | od -An -tx1 | tr -d ' ')
# Check for shared prereq bucket
PREREQ_BUCKET=$(aws cloudformation describe-stacks --stack-name tutorial-prereqs-bucket \
--query 'Stacks[0].Outputs[?OutputKey==`BucketName`].OutputValue' --output text 2>/dev/null || true)
if [ -n "$PREREQ_BUCKET" ] && [ "$PREREQ_BUCKET" != "None" ]; then
BUCKET_NAME="$PREREQ_BUCKET"
BUCKET_IS_SHARED=true
echo "Using shared bucket: $BUCKET_NAME"
else
BUCKET_IS_SHARED=false
BUCKET_NAME="s3api-${UNIQUE_ID}"
fi
TEMP_DIR=$(mktemp -d)
trap 'rm -rf "$TEMP_DIR"' EXIT
LOG_FILE="${TEMP_DIR}/s3-gettingstarted.log"
CREATED_RESOURCES=()
exec > >(tee -a "$LOG_FILE") 2>&1
echo "============================================"
echo "S3 Getting Started"
echo "============================================"
echo "Bucket name: ${BUCKET_NAME}"
echo "Temp directory: ${TEMP_DIR}"
echo "Log file: ${LOG_FILE}"
echo ""
# ============================================================================
# Helper functions
# ============================================================================
get_region() {
echo "${AWS_REGION:-${AWS_DEFAULT_REGION:-${CONFIGURED_REGION}}}"
}
delete_object_versions() {
local bucket=$1
local query=$2
local versions
versions=$(aws s3api list-object-versions \
--bucket "$bucket" \
--query "$query" \
--output json 2>&1) || return 0
if [ -z "$versions" ] || [ "$versions" = "null" ] || [ "$versions" = "[]" ]; then
return 0
fi
echo "$versions" | jq -r '.[] | "\(.Key)\t\(.VersionId)"' 2>/dev/null | while IFS=$'\t' read -r key version_id; do
if [ -n "$key" ] && [ "$key" != "null" ]; then
aws s3api delete-object --bucket "$bucket" --key "$key" --version-id "$version_id" >/dev/null 2>&1 || true
fi
done
return 0
}
# ============================================================================
# Error handling and cleanup functions
# ============================================================================
cleanup() {
echo ""
echo "============================================"
echo "CLEANUP"
echo "============================================"
if [ "$BUCKET_IS_SHARED" = "false" ]; then
echo "Deleting all object versions in bucket..."
delete_object_versions "$BUCKET_NAME" "Versions[].{Key:Key,VersionId:VersionId}" || true
delete_object_versions "$BUCKET_NAME" "DeleteMarkers[].{Key:Key,VersionId:VersionId}" || true
echo "Deleting bucket: ${BUCKET_NAME}"
if ! aws s3api delete-bucket --bucket "$BUCKET_NAME" 2>/dev/null; then
echo "WARNING: Failed to delete bucket ${BUCKET_NAME}"
fi
# Clean up logs bucket
LOG_TARGET_BUCKET="${BUCKET_NAME}-logs"
if aws s3api head-bucket --bucket "$LOG_TARGET_BUCKET" 2>/dev/null; then
echo "Deleting log bucket: ${LOG_TARGET_BUCKET}"
if ! aws s3api delete-bucket --bucket "$LOG_TARGET_BUCKET" 2>/dev/null; then
echo "WARNING: Failed to delete bucket ${LOG_TARGET_BUCKET}"
fi
fi
else
echo "Keeping shared bucket: ${BUCKET_NAME}"
fi
echo ""
echo "Cleanup complete."
}
handle_error() {
local line_number=$1
echo ""
echo "============================================"
echo "ERROR on line ${line_number}"
echo "============================================"
echo ""
echo "Resources created before error:"
if [ ${#CREATED_RESOURCES[@]} -gt 0 ]; then
for RESOURCE in "${CREATED_RESOURCES[@]}"; do
echo " - ${RESOURCE}"
done
else
echo " (none)"
fi
echo ""
echo "Attempting cleanup..."
cleanup
exit 1
}
trap 'handle_error "$LINENO"' ERR
# ============================================================================
# Step 1: Create a bucket
# ============================================================================
echo "Step 1: Creating bucket ${BUCKET_NAME}..."
if [ "$BUCKET_IS_SHARED" = "false" ]; then
REGION=$(get_region)
if [ "$REGION" = "us-east-1" ]; then
if ! aws s3api create-bucket --bucket "$BUCKET_NAME" >/dev/null 2>&1; then
echo "ERROR: Failed to create bucket $BUCKET_NAME"
exit 1
fi
else
if ! aws s3api create-bucket \
--bucket "$BUCKET_NAME" \
--region "$REGION" \
--create-bucket-configuration LocationConstraint="$REGION" >/dev/null 2>&1; then
echo "ERROR: Failed to create bucket $BUCKET_NAME in region $REGION"
exit 1
fi
fi
CREATED_RESOURCES+=("s3:bucket:${BUCKET_NAME}")
echo "Bucket created."
if ! aws s3api put-bucket-tagging \
--bucket "$BUCKET_NAME" \
--tagging '{
"TagSet": [
{
"Key": "project",
"Value": "doc-smith"
},
{
"Key": "tutorial",
"Value": "s3-gettingstarted"
}
]
}' >/dev/null 2>&1; then
echo "WARNING: Failed to tag bucket"
fi
fi
echo ""
# ============================================================================
# Step 2: Upload a sample text file
# ============================================================================
echo "Step 2: Uploading a sample text file..."
SAMPLE_FILE="${TEMP_DIR}/sample.txt"
cat > "$SAMPLE_FILE" << 'EOF'
Hello, Amazon S3! This is a sample file for the getting started tutorial.
EOF
if ! aws s3api put-object \
--bucket "$BUCKET_NAME" \
--key "sample.txt" \
--body "$SAMPLE_FILE" \
--server-side-encryption AES256 \
--metadata "tutorial=s3-gettingstarted" >/dev/null 2>&1; then
echo "ERROR: Failed to upload sample.txt"
exit 1
fi
echo "File uploaded."
echo ""
# ============================================================================
# Step 3: Download the object
# ============================================================================
echo "Step 3: Downloading the object..."
DOWNLOAD_FILE="${TEMP_DIR}/downloaded-sample.txt"
if ! aws s3api get-object \
--bucket "$BUCKET_NAME" \
--key "sample.txt" \
"$DOWNLOAD_FILE" >/dev/null 2>&1; then
echo "ERROR: Failed to download sample.txt"
exit 1
fi
echo "Downloaded to: ${DOWNLOAD_FILE}"
echo "Contents:"
cat "$DOWNLOAD_FILE"
echo ""
# ============================================================================
# Step 4: Copy the object to a folder prefix
# ============================================================================
echo "Step 4: Copying object to a folder prefix..."
if ! aws s3api copy-object \
--bucket "$BUCKET_NAME" \
--copy-source "${BUCKET_NAME}/sample.txt" \
--key "backup/sample.txt" \
--server-side-encryption AES256 \
--metadata-directive COPY >/dev/null 2>&1; then
echo "ERROR: Failed to copy object to backup/sample.txt"
exit 1
fi
echo "Object copied to backup/sample.txt."
echo ""
# ============================================================================
# Step 5: Enable versioning and upload a second version
# ============================================================================
echo "Step 5: Enabling versioning..."
if ! aws s3api put-bucket-versioning \
--bucket "$BUCKET_NAME" \
--versioning-configuration Status=Enabled >/dev/null 2>&1; then
echo "ERROR: Failed to enable versioning"
exit 1
fi
echo "Versioning enabled."
echo "Uploading a second version of sample.txt..."
cat > "$SAMPLE_FILE" << 'EOF'
Hello, Amazon S3! This is version 2 of the sample file.
EOF
if ! aws s3api put-object \
--bucket "$BUCKET_NAME" \
--key "sample.txt" \
--body "$SAMPLE_FILE" \
--server-side-encryption AES256 \
--metadata "tutorial=s3-gettingstarted,version=2" >/dev/null 2>&1; then
echo "ERROR: Failed to upload second version of sample.txt"
exit 1
fi
echo "Second version uploaded."
echo ""
# ============================================================================
# Step 6: Configure SSE-S3 encryption
# ============================================================================
echo "Step 6: Configuring SSE-S3 default encryption..."
if ! aws s3api put-bucket-encryption \
--bucket "$BUCKET_NAME" \
--server-side-encryption-configuration '{
"Rules": [
{
"ApplyServerSideEncryptionByDefault": {
"SSEAlgorithm": "AES256"
},
"BucketKeyEnabled": true
}
]
}' >/dev/null 2>&1; then
echo "ERROR: Failed to configure SSE-S3 encryption"
exit 1
fi
echo "SSE-S3 encryption configured."
echo ""
# ============================================================================
# Step 7: Block all public access
# ============================================================================
echo "Step 7: Blocking all public access..."
if ! aws s3api put-public-access-block \
--bucket "$BUCKET_NAME" \
--public-access-block-configuration '{
"BlockPublicAcls": true,
"IgnorePublicAcls": true,
"BlockPublicPolicy": true,
"RestrictPublicBuckets": true
}' >/dev/null 2>&1; then
echo "ERROR: Failed to block public access"
exit 1
fi
echo "Public access blocked."
echo ""
# ============================================================================
# Step 8: Configure bucket logging
# ============================================================================
echo "Step 8: Configuring bucket logging..."
LOG_TARGET_BUCKET="${BUCKET_NAME}-logs"
if [ "$BUCKET_IS_SHARED" = "false" ]; then
REGION=$(get_region)
if [ "$REGION" = "us-east-1" ]; then
aws s3api create-bucket --bucket "$LOG_TARGET_BUCKET" >/dev/null 2>&1 || true
else
aws s3api create-bucket \
--bucket "$LOG_TARGET_BUCKET" \
--region "$REGION" \
--create-bucket-configuration LocationConstraint="$REGION" >/dev/null 2>&1 || true
fi
if ! aws s3api put-bucket-tagging \
--bucket "$LOG_TARGET_BUCKET" \
--tagging '{
"TagSet": [
{
"Key": "project",
"Value": "doc-smith"
},
{
"Key": "tutorial",
"Value": "s3-gettingstarted"
}
]
}' >/dev/null 2>&1; then
echo "WARNING: Failed to tag log bucket"
fi
aws s3api put-bucket-acl --bucket "$LOG_TARGET_BUCKET" --acl log-delivery-write 2>/dev/null || true
if ! aws s3api put-bucket-logging \
--bucket "$BUCKET_NAME" \
--bucket-logging-status '{
"LoggingEnabled": {
"TargetBucket": "'$LOG_TARGET_BUCKET'",
"TargetPrefix": "logs/"
}
}' >/dev/null 2>&1; then
echo "WARNING: Failed to configure bucket logging"
else
echo "Bucket logging configured."
fi
else
echo "Skipping logging configuration for shared bucket."
fi
echo ""
# ============================================================================
# Step 9: Tag the bucket
# ============================================================================
echo "Step 9: Tagging the bucket..."
if ! aws s3api put-bucket-tagging \
--bucket "$BUCKET_NAME" \
--tagging '{
"TagSet": [
{
"Key": "project",
"Value": "doc-smith"
},
{
"Key": "tutorial",
"Value": "s3-gettingstarted"
},
{
"Key": "Environment",
"Value": "Tutorial"
},
{
"Key": "Project",
"Value": "S3-GettingStarted"
},
{
"Key": "ManagedBy",
"Value": "Bash-Tutorial"
}
]
}' >/dev/null 2>&1; then
echo "ERROR: Failed to tag bucket"
exit 1
fi
echo "Bucket tagged."
echo "Verifying tags..."
if ! aws s3api get-bucket-tagging --bucket "$BUCKET_NAME" 2>&1; then
echo "WARNING: Failed to retrieve bucket tags"
fi
echo ""
# ============================================================================
# Step 10: List objects and versions
# ============================================================================
echo "Step 10: Listing objects..."
if ! aws s3api list-objects-v2 --bucket "$BUCKET_NAME" 2>&1; then
echo "WARNING: Failed to list objects"
fi
echo ""
echo "Listing object versions..."
if ! aws s3api list-object-versions --bucket "$BUCKET_NAME" 2>&1; then
echo "WARNING: Failed to list object versions"
fi
echo ""
# ============================================================================
# Step 11: Cleanup
# ============================================================================
echo ""
echo "============================================"
echo "TUTORIAL COMPLETE"
echo "============================================"
echo ""
echo "Resources created:"
if [ ${#CREATED_RESOURCES[@]} -gt 0 ]; then
for RESOURCE in "${CREATED_RESOURCES[@]}"; do
echo " - ${RESOURCE}"
done
else
echo " (none)"
fi
echo ""
echo "==========================================="
echo "CLEANUP"
echo "==========================================="
echo "Cleaning up all created resources..."
cleanup
echo ""
echo "Done."