Skip to content

Instantly share code, notes, and snippets.

@james-jory
Created April 13, 2020 01:55
Show Gist options
  • Save james-jory/7d5550b7e32b258500c8c021217555a9 to your computer and use it in GitHub Desktop.
Save james-jory/7d5550b7e32b258500c8c021217555a9 to your computer and use it in GitHub Desktop.
Deregisters AWS ECS task definitions using an optional filter expression
#!/bin/bash
# Deregisters AWS ECS task definitions based on a filter expression. The optional --dry-run
# argument can be used to test filter expressions before deleting.
TASK_DEF_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 task definitions to deregister"
echo ""
}
function deregister_task_definition() {
if [ "$DRY_RUN" == "Y" ]; then
echo "Dry-Run: would deregister task definition: $1"
else
echo "Deleting task definition: $1"
aws ecs deregister-task-definition --task-definition $1 > /dev/null
fi
}
function deregister_task_definitions() {
aws ecs list-task-definitions --query 'taskDefinitionArns[*]' --output table | \
awk '{print $2}' | \
grep "$TASK_DEF_FILTER" | \
while read -a tmp_arr; do for x in "${tmp_arr[@]}"; do deregister_task_definition $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
TASK_DEF_FILTER="$var"
fi
done
if [ -z "$TASK_DEF_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 deregister ALL task definitions in default region (y/n)?" choice
case "$choice" in
y|Y ) deregister_task_definitions;;
n|N ) echo "Exiting without deregistering task definitions" && usage && exit 1;;
* ) echo "Invalid; exiting" && usage && exit 2;;
esac
else
deregister_task_definitions
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment