Automate deleting old application versions from ElasticBeanstalk

Intro

AWS ElasticBeanstalk is a very popular way of deploying applications to “the
cloud” without really messing too much with configuration and deployment
scripts.

It’s a very powerful platform if you know how to use it.

The problem

If you work in a team and you do the regular git workflow, you will encounter
this error:

A client error (TooManyApplicationVersionsException) occurred when calling the CreateApplicationVersion operation:
You cannot have more than 500 Application Versions. Either remove some Application Versions or request a limit increase.

ElasticBeanstalk is limited to 500 application versions across all your
applications. You will need to delete old applications.

Automating the solution

I’m an automation freak so I automated the process of deleting application
versions from AWS.

all you need to do is export some variables

$ export APP=your-application
$ export PROFILE=your-aws-profile

Then, you execute

$ ./execute-delete.sh

Solution details

The solution is composed of a few files

parse_versions.rb

This ruby file will except the JSON output from
describe-application-versions and parse it into simple output. Making sure it
belongs to the right application before outputting and verifying the date.

#!/usr/bin/env ruby

require 'time'
require 'json'

ALLOWED_NAMES = [ENV['APP']]

t = DateTime.now - 14

json = ARGF.read
hash = JSON.parse(json)

versions = hash["ApplicationVersions"]

versions.each do |ver|
  application_name = ver["ApplicationName"]
  created_at = DateTime.parse(ver["DateCreated"])

  if ALLOWED_NAMES.include?(application_name)
    if t > created_at
      puts "#{ver["VersionLabel"]}"
    end
  end
end

list-versions.sh

aws elasticbeanstalk describe-application-versions --profile $PROFILE

delete-versions.sh

echo "Starting to delete versions of $APP"

while read ver; do
    echo "Deleting version $ver"
    aws elasticbeanstalk delete-application-version --version-label $ver --profile $PROFILE --application-name $APP
    echo "Version $ver deleted!"
done

Enjoy!

Source Code

Source code for the scripts can be found here: https://gist.github.com/KensoDev/646de085dc8fd4c4b39d.