Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP script to scrape spot instance pricing data from Amazon AWS and display cheapest region for each instance tyoe
<?php
// Copyright Simon Briggs 2016
// Licensed under the Gnu Lesser General Public License
// https://www.gnu.org/licenses/lgpl.txt
// Get pricing data from Amazon
// (For better performance get the data and cache it with a cron job)
$data = file_get_contents("https://spot-price.s3.amazonaws.com/spot.js");
// Trim off the JSONP function to give us propert JSON
$data = substr($data, 9, strlen($data)-10);
$parsed_data = json_decode($data, true);
$regions = $parsed_data["config"]["regions"];
// Declare a variable to hold the output array
$cheapest;
// Iterate through the regions
foreach ($regions as $region)
{
foreach ($region["instanceTypes"] as $instanceTypes)
{
foreach ($instanceTypes["sizes"] as $instanceSizes)
{
if(!isset($cheapest[$instanceSizes["size"]])) {
// Create an entry for this instance size if it doesn't already exist
$cheapest[$instanceSizes["size"]] = ["nowhere",PHP_INT_MAX];
}
$price = floatval($instanceSizes["valueColumns"][0]["prices"]["USD"]);
// If the price of this instance in this region is cheaper than the previous cheapest region, store this region and price
if($price>0 && floatval($cheapest[$instanceSizes["size"]][1]) > $price ) {
$cheapest[$instanceSizes["size"]] = [$region["region"],$price,$instanceSizes["size"]];
}
}
}
}
?>
<table>
<thead><tr>
<td>Instance type</td>
<td>Region</td>
<td>Price (USD)</td>
</tr></thead><tbody>
<?php
foreach($cheapest as $cheap)
{
echo ('<tr><td>' . $cheap[2] . '</td><td>' . trim($cheap[0]) . '</td><td>' . $cheap[1] . '</td></tr>');
}
?></tbody>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment