Last Updated: February 25, 2016
·
919
· brunochauvet

Find the cheapest AZ to request your spot instance

Sometimes you need to run an instance on AWS and don't care about where this one lives. Here is a snippet of ruby code to find the availability zone where an instance type is currently the cheapest.

ec2 = AWS::EC2.new
regions = ec2.regions.map(&:name)

spot_prices = []
regions.each do |region|
  ec2 = AWS::EC2.new(region: region)
  spot_price = ec2.client.describe_spot_price_history({instance_types: ['m3.medium'], product_descriptions: ['Linux/UNIX'], start_time: (Time.now - 1).iso8601(3), end_time: Time.now.iso8601(3)})
  spot_price[:spot_price_history_set].each do |sp|
    spot_prices << sp.merge({region: region})
  end
end

min_spot_price = spot_prices.min_by{|sp| sp[:spot_price].to_f}

puts "#{min_spot_price[:instance_type]} has lowest price on #{min_spot_price[:region]} #{min_spot_price[:availability_zone]} at $#{min_spot_price[:spot_price]}"

About the parameters of describe_spot_price_history

instance_types: array of instance types to retrieve price history

product_descriptions: array of OS to retrieve

start_time and end_time: timeframe of the price history. We use 1 second to get only the latest price

This can be customised if your instance needs to live on a specific region or if you want to be able to support multiple instance types.
Then you can easily request your spot instance using this snippet of code https://coderwall.com/p/iw4pfw