Skip to content

Instantly share code, notes, and snippets.

@ajorpheus
Created January 27, 2022 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajorpheus/808246209aa6ed41fa74d2dc12abdfc7 to your computer and use it in GitHub Desktop.
Save ajorpheus/808246209aa6ed41fa74d2dc12abdfc7 to your computer and use it in GitHub Desktop.
Delete log groups matching a specific pattern and other filter criteria
#!/bin/bash
## Log groups must match ALL these criteria to be processed
log_name_include="$1" #Only logs containing this string in their name will be included
region="${2:-"eu-west-1"}"
retention_period_filter="400" #Logs with this retention period will be excluded
log() { printf "\n%b" "$*"; }
define_colors_for_logging() {
err="\e[48;5;1m"
highlight="\e[1;33;46m"
reset="\e[0m"
header="\e[0;33m"
}
define_colors_for_logging
delete_log_no_prompt() {
local log_name="$1"
log "Deleting ${highlight}$log_name${reset}"
if output="$(aws logs delete-log-group --region "$region" --log-group-name "$log_name" 2>&1)"; then
log "Deleted ${highlight}$log_name${reset}\n(Exit Code)Output:($?)$output"
else
log "Error while deleting ${highlight}$log_name${reset}\nExit Code: ${err}$?${reset},\n Output:${err}$output${reset}"
fi
}
delete_log_group() {
local log_name="$1"
log "Do you want to delete log-group ${highlight}$log_name${reset}\n"
select answer in "Yes" "No(Skip)" "Abort"; do
case $answer in
Yes)
delete_log_no_prompt "$log_name"
break
;;
'No(Skip)')
log "Skipped deleting of ${highlight}$log_name${reset}\n\n"
break
;;
Abort)
echo "Eeeeeeeks! Abort abort!"
exit
;;
esac
done </dev/tty
}
if output="$(aws logs describe-log-groups --output json --query "logGroups[?retentionInDays!=\`$retention_period_filter\` && contains(logGroupName,\`$log_name_include\`)].logGroupName" --region "$region" | jq -r '.[]' | grep "$log_name_include")"; then
## Create an array from output
IFS=$'\n' read -r -d '' -a log_groups_arr <<<"$output"
log_group_count=${#log_groups_arr[@]}
log "Found $log_group_count log groups matching criteria: Log name contains ${err}$log_name_include${reset} and retention days != ${highlight}$retention_period_filter${reset}\n"
echo "${log_groups_arr[*]}" | tr ' ' '\n' | nl -w2 -s'>'
log "${header}Deleting one by one with prompt for confirmation${reset}\n\n"
## now loop through the above array
COUNTER=1
for log_name in "${log_groups_arr[@]}"; do
log "\n\n$COUNTER> ${highlight}$log_name${reset}"
delete_log_group "$log_name"
COUNTER=$((COUNTER + 1))
done
else
log "No log found matching the name provided,\nOutput: ${err}$output${reset}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment