Last active
April 2, 2023 14:06
-
-
Save yob/2b1b42f89a7bd3c623075b6d21819566 to your computer and use it in GitHub Desktop.
Convert AWS ip-ranges.json into a SQL view for querying
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
require 'net/http' | |
require 'json' | |
require 'pp' | |
def die(msg) | |
$stderr.puts msg | |
exit 1 | |
end | |
uri = URI('https://ip-ranges.amazonaws.com/ip-ranges.json') | |
response = Net::HTTP.get_response(uri) | |
unless response.is_a?(Net::HTTPOK) | |
die("error fetching #{uri}") | |
end | |
data = JSON.parse(response.body) | |
rows = [] | |
data.fetch('prefixes', []).each do |item| | |
if item.has_key?("ip_prefix") | |
rows << "ROW ('#{item.fetch('region')}', '#{item.fetch('ip_prefix')}')" | |
end | |
end | |
sql = <<~SQL | |
CREATE OR REPLACE VIEW "aws_ip_ranges" AS | |
SELECT region, network | |
FROM ( | |
values | |
#{rows.uniq.join(",\n")} | |
) s (region, network) | |
SQL | |
puts sql |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment