Skip to content

Instantly share code, notes, and snippets.

@james-jory
Last active April 10, 2020 16:49
Show Gist options
  • Save james-jory/6202277a2dc2ddc38109037a1bf044e1 to your computer and use it in GitHub Desktop.
Save james-jory/6202277a2dc2ddc38109037a1bf044e1 to your computer and use it in GitHub Desktop.
Delete AWS log groups using an optional filter expression
#!/bin/bash
# Deletes AWS log groups based on a filter expression. The optional --dry-run
# argument can be used to test filter expressions before deleting.
LOG_GROUP_FILTER=""
DRY_RUN="N"
THIS_SCRIPT=$0
function usage() {
echo ""
echo "Usage: $THIS_SCRIPT [--dry-run] [filter_expression]"
echo "Where:"
echo " --dry-run: print what log groups would be deleted without deleting"
echo " filter_expression: expression used to filter log groups to delete"
echo ""
}
function delete_log_group() {
if [ "$DRY_RUN" == "Y" ]; then
echo "Dry-Run: would delete log group: $1"
else
echo "Deleting log group: $1"
aws logs delete-log-group --log-group-name $1
fi
}
function delete_log_groups() {
aws logs describe-log-groups --query 'logGroups[*].logGroupName' --output table | \
awk '{print $2}' | \
grep "$LOG_GROUP_FILTER" | \
while read -a tmp_arr; do for x in "${tmp_arr[@]}"; do delete_log_group $x; done; done
}
# Make sure region is either set for profile or as environment variable.
CONFIG_REGION=`aws configure get region`
if [[ -z "$AWS_DEFAULT_REGION" ]] && [[ -z "$CONFIG_REGION" ]] ; then
echo "Region is required. Please configure a default AWS region for this profile using 'aws configure' or set AWS_DEFAULT_REGION environment variable."
exit 1
fi
# Process command-line arguments.
for var in "$@"
do
if [ "$var" == "--dry-run" ]; then
DRY_RUN="Y"
else
LOG_GROUP_FILTER="$var"
fi
done
if [ -z "$LOG_GROUP_FILTER" ]; then
# No filter expression provided which means all log groups will be deleted for the
# default region. Prompt user to make sure they know what they are about to do.
read -p "Are you sure you want to delete ALL log groups in default region (y/n)?" choice
case "$choice" in
y|Y ) delete_log_groups;;
n|N ) echo "Exiting without deleting log groups" && usage && exit 1;;
* ) echo "Invalid; exiting" && usage && exit 2;;
esac
else
delete_log_groups
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment