Skip to content

Commit

Permalink
add empty bucket script
Browse files Browse the repository at this point in the history
  • Loading branch information
FaithKovi committed Aug 3, 2024
1 parent 730c136 commit 9b06f9a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/destroy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@ jobs:
zip -r ../terraform/lambda_function.zip . -x "venv/*"
echo "Lambda function zipped"
- name: Empty S3 bucket
- name: Empty S3 Bucket
working-directory: ./terraform
run: |
aws s3 rm s3://$BUCKET_NAME --recursive
chmod +x ./scripts/empty_bucket.sh
./scripts/empty_bucket.sh ${{ secrets.BUCKET_NAME }} ${{ secrets.AWS_REGION }}
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
AWS_REGION: ${{ secrets.AWS_REGION }}
BUCKET_NAME: ${{ secrets.BUCKET_NAME }}

- name: Destroy Terraform
working-directory: ./terraform
Expand Down
26 changes: 26 additions & 0 deletions terraform/scripts/empty_bucket.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#!/bin/bash
# Exit immediately if a command exits with a non-zero status
set -e

# Define variables
BUCKET_NAME="$1"
AWS_REGION="$2"

echo "Deleting all objects and versions from bucket $BUCKET_NAME in region $AWS_REGION"

# Delete all objects
aws s3 rm s3://$BUCKET_NAME --recursive --region $AWS_REGION

# If versioning is enabled, delete all object versions
aws s3api list-object-versions --bucket $BUCKET_NAME --region $AWS_REGION --query "Versions[].[Key,VersionId]" --output text | \
while read -r key version_id; do
aws s3api delete-object --bucket $BUCKET_NAME --key "$key" --version-id "$version_id" --region $AWS_REGION
done

# If there are delete markers, delete them too
aws s3api list-object-versions --bucket $BUCKET_NAME --region $AWS_REGION --query "DeleteMarkers[].[Key,VersionId]" --output text | \
while read -r key version_id; do
aws s3api delete-object --bucket $BUCKET_NAME --key "$key" --version-id "$version_id" --region $AWS_REGION
done

echo "Bucket $BUCKET_NAME emptied."

0 comments on commit 9b06f9a

Please sign in to comment.