Skip to content

Instantly share code, notes, and snippets.

@yujiorama
Last active August 27, 2021 08:28
Show Gist options
  • Save yujiorama/e0b900b6b3845396457642d3964bdd75 to your computer and use it in GitHub Desktop.
Save yujiorama/e0b900b6b3845396457642d3964bdd75 to your computer and use it in GitHub Desktop.
utility functions
# usage: aws-s3-bucket-delete [bucket-name]
# desc: disable(suspend) versioning for [bucket-name], delete all objects in [bucket-name], delete [bucket-name]
function aws-s3-bucket-delete() {
local bucket
bucket="$1"
if [[ -z "${bucket}" ]]; then
return 1
fi
if ! command -v aws >/dev/null 2>&1; then
return 1
fi
if ! command -v jq >/dev/null 2>&1; then
return 1
fi
if ! aws s3api put-bucket-versioning --bucket "${bucket}" --versioning-configuration Status=Suspended; then
return 1
fi
local delete_json
delete_json=$(basename "$(mktemp -p "${PWD}")")
aws s3api list-objects --bucket "${bucket}" | jq -r '{"Objects": [.Contents[] | {"Key": .Key}], "Quiet": false }' > "${delete_json}"
if [[ ! -s "${delete_json}" ]]; then
rm -f "${delete_json}"
return 1
fi
(
trap "rm -v ${delete_json}" 0 1 2 3 15
aws s3api delete-objects --bucket "${bucket}" --delete "file://${delete_json}"
aws s3api delete-bucket --bucket "${bucket}"
) | cat -
return 0
}
# usage: aws-ecr-repository-delete [repository-name]
# desc: delete all images by imageTag in [repository-name], delete [repository-name]
function aws-ecr-repository-delete() {
local repository
repository="$1"
if [[ -z "${repository}" ]]; then
return 1
fi
if ! command -v aws >/dev/null 2>&1; then
return 1
fi
if ! command -v jq >/dev/null 2>&1; then
return 1
fi
local images
images=$(aws ecr list-images --repository-name "${repository}" --query 'imageIds[].imageTag' --output json | jq -r 'map("imageTag=" + .) | join(" ")')
if [[ -z "${images}" ]]; then
return 1
fi
# shellcheck disable=SC2086
if ! aws ecr batch-delete-image --repository "${repository}" --image-ids ${images}; then
return 1
fi
aws ecr delete-repository --repository "${repository}"
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment