Created
August 31, 2016 07:38
-
-
Save spbriggs/edb65817708af6b9d3b4e6d4810a3c18 to your computer and use it in GitHub Desktop.
PHP script to scrape spot instance pricing data from Amazon AWS and display cheapest region for each instance tyoe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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