|
| 1 | +#!/bin/bash |
| 2 | +WORK_DIR=$(mktemp -d); exec > >(tee -a "$WORK_DIR/ttl.log") 2>&1 |
| 3 | +REGION=${AWS_DEFAULT_REGION:-$(aws configure get region 2>/dev/null)}; [ -z "$REGION" ] && echo "ERROR: No region" && exit 1; export AWS_DEFAULT_REGION="$REGION"; echo "Region: $REGION" |
| 4 | +RANDOM_ID=$(openssl rand -hex 4); TABLE="tut-ttl-${RANDOM_ID}" |
| 5 | +handle_error() { echo "ERROR on line $1"; trap - ERR; cleanup; exit 1; }; trap 'handle_error $LINENO' ERR |
| 6 | +cleanup() { echo ""; echo "Cleaning up..."; aws dynamodb delete-table --table-name "$TABLE" > /dev/null 2>&1 && echo " Deleted table"; rm -rf "$WORK_DIR"; echo "Done."; } |
| 7 | +echo "Step 1: Creating table" |
| 8 | +aws dynamodb create-table --table-name "$TABLE" --key-schema AttributeName=pk,KeyType=HASH --attribute-definitions AttributeName=pk,AttributeType=S --billing-mode PAY_PER_REQUEST > /dev/null |
| 9 | +aws dynamodb wait table-exists --table-name "$TABLE" |
| 10 | +echo "Step 2: Enabling TTL" |
| 11 | +aws dynamodb update-time-to-live --table-name "$TABLE" --time-to-live-specification Enabled=true,AttributeName=expires_at > /dev/null |
| 12 | +echo " TTL enabled on 'expires_at' attribute" |
| 13 | +echo "Step 3: Writing items with TTL" |
| 14 | +PAST=$(($(date +%s) - 3600)) |
| 15 | +FUTURE=$(($(date +%s) + 86400)) |
| 16 | +aws dynamodb put-item --table-name "$TABLE" --item "{\"pk\":{\"S\":\"expired-item\"},\"data\":{\"S\":\"This should expire\"},\"expires_at\":{\"N\":\"$PAST\"}}" 2>/dev/null |
| 17 | +aws dynamodb put-item --table-name "$TABLE" --item "{\"pk\":{\"S\":\"active-item\"},\"data\":{\"S\":\"This stays\"},\"expires_at\":{\"N\":\"$FUTURE\"}}" 2>/dev/null |
| 18 | +echo " Wrote 2 items (1 expired, 1 active)" |
| 19 | +echo "Step 4: Describing TTL" |
| 20 | +aws dynamodb describe-time-to-live --table-name "$TABLE" --query 'TimeToLiveDescription.{Status:TimeToLiveStatus,Attribute:AttributeName}' --output table |
| 21 | +echo "Step 5: Scanning items" |
| 22 | +aws dynamodb scan --table-name "$TABLE" --query 'Items[].{pk:pk.S,data:data.S,expires:expires_at.N}' --output table |
| 23 | +echo " Note: DynamoDB deletes expired items within 48 hours, not immediately" |
| 24 | +echo ""; echo "Tutorial complete." |
| 25 | +echo "Do you want to clean up? (y/n): "; read -r CHOICE; [[ "$CHOICE" =~ ^[Yy]$ ]] && cleanup |
0 commit comments