Last active
April 12, 2024 14:46
-
-
Save kkumler/de7246568a1ce81372bf0a9f1674635b to your computer and use it in GitHub Desktop.
Remove AWS ECS Task Definitions in bulk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -o errexit | |
set -o nounset | |
set -o pipefail | |
FAMILY_PREFIX="" | |
# Ensure variables are set, that we don't directly use. This works do to the nounset option. | |
[[ "${AWS_PROFILE:?}" ]] | |
declare -x AWS_PAGER="" | |
if [[ "${TRACE-0}" == "1" ]]; then | |
set -o xtrace | |
fi | |
join_by() { | |
local d=${1-} f=${2-} | |
if shift 2; then | |
printf %s "$f" "${@/#/$d}" | |
fi | |
} | |
deregister_active() { | |
mapfile -t TASK_DEFINITIONS < <(aws ecs list-task-definitions --status "ACTIVE" --family-prefix ${FAMILY_PREFIX} --query "taskDefinitionArns[]" --output json | jq -r '.[]') | |
echo "Total active: ${#TASK_DEFINITIONS[@]}" | |
for DEF in "${TASK_DEFINITIONS[@]}"; do | |
aws ecs deregister-task-definition --task-definition "${DEF}" --query 'taskDefinition.[taskDefinitionArn, status]' --output text | |
sleep 0.2 | |
done | |
} | |
delete_inactive() { | |
mapfile -t TASK_DEFINITIONS < <(aws ecs list-task-definitions --status "INACTIVE" --family-prefix ${FAMILY_PREFIX} --query "taskDefinitionArns[]" --output json | jq -r '.[]') | |
GROUP=10 | |
echo "Total inactive: ${#TASK_DEFINITIONS[@]}" | |
for ((i=0; i < ${#TASK_DEFINITIONS[@]}; i+=GROUP)); do | |
part=( "${TASK_DEFINITIONS[@]:i:GROUP}" ) | |
DEF_STRING=$(join_by ' ' "${part[@]##*/}") | |
echo "Deleting '${DEF_STRING}'" | |
aws ecs delete-task-definitions --task-definitions ${DEF_STRING} --query 'taskDefinitions[].[taskDefinitionArn, status]' --output text | |
if [ "$i" -lt "${#TASK_DEFINITIONS[@]}" ]; then | |
sleep 0.5 | |
fi | |
done | |
} | |
FAMILIES=(example-to-delete another-to-delete) | |
main() { | |
for fam in "${FAMILIES[@]}"; do | |
echo | |
echo "Family: ${fam}" | |
FAMILY_PREFIX=${fam} | |
deregister_active | |
echo | |
delete_inactive | |
sleep 2 | |
done | |
} | |
cd "$(dirname "$0")" | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment