Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Region and service on AWS for IP addresses
#!/usr/bin/ruby
require 'open-uri'
require 'json'
require 'ipaddr'
require 'pp'
prefixes = Hash.new
source = 'https://ip-ranges.amazonaws.com/ip-ranges.json'
JSON.parse(URI::parse(source).read)['prefixes'].each do |e|
x = IPAddr.new(e['ip_prefix'])
prefixes[x] ||= Array.new
prefixes[x] << e
end
begin
addrs = ARGV.map{|path| File.read(path).split}.flatten
rescue Errno::ENOENT
addrs = ARGV
end
addrs.each do |addr|
ranges = prefixes.keys.select{|x| x.include? addr}.map{|x| prefixes[x]}
if not ranges.empty?
regions = ranges[0].map{|x| x['region']}.uniq
services = ranges[0].map{|x| x['service']}.uniq
if services.size > 1 and services.include?('AMAZON')
services.reject!{|x| x == 'AMAZON'}
end
x = "#{regions.join(",")} on #{services.join(",")}"
else
x = "Not on AWS"
end
puts "#{addr}: #{x}"
end
Owner

zunda commented Jun 1, 2017

Doesn't seem to handle IPv6 addresses as expected

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment