Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Delete unused Launch Configuration. Based on http://www.markomedia.com.au/delete-launch-config-programatically-aws/
#!/bin/bash
#
# based on https://gist.github.com/brauliobo/d3692d3ac5eb8b00e863
# our version handle spaces and other chars we use in the launch configuration
#
BOLD="\e[1m"
RESET="\e[0m"
GREEN="\e[32m"
RED="\e[31m"
IFS=$'\n'
# called when the launch configuration is still in used
keep() {
# remove quotes
local lc_name=$(echo "$1" | sed s/\"//g )
echo -e "${BOLD}${GREEN}${RESET} ${lc_name}"
}
# called when the launch configuration is no longer in use, and should be deleted
delete() {
# remove quotes
local lc_name=$(echo "$1" | sed s/\"//g )
echo -e "${BOLD}${RED}${RESET} ${lc_name}"
aws autoscaling delete-launch-configuration --launch-configuration-name "${lc_name}"
}
# Check if a value exists in an array
# @param $1 mixed Needle
# @param $2 array Haystack
# @return Success (0) if value exists, Failure (1) otherwise
# Usage: in_array "$needle" "${haystack[@]}"
# See: http://fvue.nl/wiki/Bash:_Check_if_array_element_exists
in_array() {
local hay needle=$1
shift
for hay; do
[[ "$hay" == "$needle" ]] && return 0
done
return 1
}
# Get all launch configuration names that have been created for this AWS account
echo "aws autoscaling describe-launch-configurations"
allconfigs=$(aws autoscaling describe-launch-configurations | jq '.LaunchConfigurations[].LaunchConfigurationName' | grep -v null)
configs=($allconfigs)
# Get all active launch configurations names that are currently associated with running instances
echo "aws autoscaling describe-auto-scaling-instances"
allinstances=$(aws autoscaling describe-auto-scaling-instances | jq '.AutoScalingInstances[].LaunchConfigurationName' | grep -v null)
instances=($allinstances)
# Get all active launch configuration names that are currently associated with launch configuration groups
echo "aws autoscaling describe-auto-scaling-groups"
allgroups=$(aws autoscaling describe-auto-scaling-groups | jq '.AutoScalingGroups[].LaunchConfigurationName' | grep -v null)
groups=($allgroups)
# merge group configs and active instances configs into one array. We need to keep them, and remove the rest
groupsandinstances=(`for R in "${instances[@]}" "${groups[@]}" ; do echo "$R" ; done | sort -du`)
# Loop through all configs and check against active ones to determine whether they need to be deleted
for i in "${configs[@]}"
do
in_array "$i" "${groupsandinstances[@]}" && keep "${i}" || delete "${i}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment