Skip to content

Instantly share code, notes, and snippets.

@pocari
Last active December 19, 2019 01:21
Show Gist options
  • Save pocari/626c623cdc539b60988a5b121778fc03 to your computer and use it in GitHub Desktop.
Save pocari/626c623cdc539b60988a5b121778fc03 to your computer and use it in GitHub Desktop.
beanstalkの指定したアプリケーション内のアプリケーションバージョンを削除するshell関数
# --dry-run ... 実際に実行はせず削除コマンドの表示だけ行う
# --keep n ... 直近N個のみ保持しそれ以外は削除
# --target regexp ... regexpにマッチするアプリケーションバージョン名のみを対象
# --v-target regexp ... regexpにマッチしないアプリケーションバージョン名のみを対象
# 例)
# productionが含まれるバージョンを直近20件のみ保持
# $ delete_old_application_versions karada-yosozu --target "production" --keep 20
#
# production, staging以外のバージョンを直近20件のみ保持
# $ delete_old_application_versions karada-yosozu --v-target "staging|production" --keep 20
function delete_old_application_versions() {
local appname=$1
if [ -z "${appname}" ]; then
echo "error: require application name."
exit 1
fi
shift
local verbose=
local dry_run=
local delete_line=19
local target=
local v_target=
local grep_v=
while [ $# -gt 0 ];
do
case ${1} in
--verbose)
verbose=1
;;
--dry-run)
dry_run=1
;;
--target)
target=${2}
shift
;;
--v-target)
v_target=${2}
grep_v="-v"
shift
;;
--keep)
delete_line=$(expr ${2} + 1)
shift
;;
*)
echo "[ERROR] Invalid option '${1}'"
usage
exit 1
;;
esac
shift
done
if [ -n "${target}" -a -n "${v_target}" ]; then
echo "--target と --v-targetは同時に指定できません"
exit 2
fi
if [ -z "${target}" -a -z "${v_target}" ]; then
echo "--target、--v-targetはいずれかが必要です"
exit 2
fi
if [ -n "${verbose}" ]; then
echo "applicaiton name : ${appname}"
echo "dry_run : ${dry_run}"
echo "target : ${target}"
echo "v_target : ${v_target}"
echo "grep_v : ${grep_v}"
echo "delete_line : ${delete_line}"
fi
if [ -n "${v_target}" ]; then
target=${v_target}
fi
local delete_versions=$(aws elasticbeanstalk describe-application-versions --region ap-northeast-1 --application-name ${appname} \
| jq -r '.ApplicationVersions[] | .VersionLabel' \
| egrep ${grep_v} -E -e "${target}" \
| tail -n +${delete_line} \
)
IFS=$'\n'
for version in ${delete_versions}
do
local command='aws elasticbeanstalk delete-application-version --region ap-northeast-1 --application-name ${appname} --delete-source-bundle --version-label "${version}"'
if [ -n "${dry_run}" ]; then
command="echo $command"
fi
eval $command
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment