Delete Old Application Versions from an Elastic Beanstalk Application

If you’re here, you know what Amazon Elastic Beanstalk is, and you’ve probably deployed at least one application to it.

The issue this article addresses, is the uncontrolled accumulation of old application versions on Amazon Elastic Beanstalk. Eventually, you will run out of space and will no longer be able to deploy the current version.

The solution is a simple PHP script which uses the Amazon Web Services API for PHP to list out all of the application versions for an Elastic Beanstalk application, and deletes all but the N newest versions.

You can adapt this script for your needs, and run it at the end of your deployment script, right after your eb deploy command.

First, install the AWS SDK for PHP. Follow the instructions here, using the instructions titled “Installing via Composer”, stopping right before the third step titled “Require Composer’s autoloader”.

After installation, you’ll need to create a .aws folder in your home folder (this assumes Linux as your deployment environment), and add a file named “credentials”, chmod 600, with the following contents:

[eb-cli]
aws_access_key_id = <put your access key here>
aws_secret_access_key = <put your secret key here>

Once you have the SDK installed and configured, you can now modify this script and use it to delete older versions of your application. Simply run the PHP script right after each deployment.

#!/usr/bin/php
<?php
// Delete old Email Creative API app versions from Elastic Beanstalk.

require_once('<put the path to your composer directory here>/vendor/autoload.php');

use Aws\ElasticBeanstalk\ElasticBeanstalkClient;

$APPLICATION_NAME = '<put your application name here>';
$REGION = '<put your AWS region here>';
$VERSIONS_TO_KEEP = 2;	// Must be at least 2.

$client = Aws\ElasticBeanstalk\ElasticBeanstalkClient::factory(array(
	'profile'=>'eb-cli',
	'region'=>$REGION,
	'version'=>'2010-12-01',
));

$response = $client->describeApplicationVersions(array(
	'ApplicationName'=>$APPLICATION_NAME
));

$versions = $response->get('ApplicationVersions');

$versionsToKeep = max($VERSIONS_TO_KEEP, 2);
if (count($versions) > $versionsToKeep) {
	$versionsToDelete = array_slice($versions, $versionsToKeep);
	foreach ($versionsToDelete as $version) {
		echo "Deleting application version: {$version['VersionLabel']}\n";
		$client->deleteApplicationVersion(array(
			'ApplicationName'=>$APPLICATION_NAME,
			'VersionLabel'=>$version['VersionLabel'],
		));
	}
}