AWS S3 Bucket Policies: Restricting to In-Region access

From time to time, Amazon Web Services adds new IP address ranges (it keeps growing!). These new addresses are published in the forums, such as via this post from EricS. I was creating a bucket policy to restrict access only to nonymous users who are within my region – I’m happy for the access requests, but I don’t want to pay the bandwidth charges. So here’s a small Perl script that takes the copy-and-paste text from EricS’s forum post, and creates an S3 buck policy element suitable for this:

#!/usr/bin/perl
open F, 'ips.txt' or die "Cannot read list of IPs: $!";
my @ip_conditions;
while (<F>) {
  push @ip_conditions, $1 if /^(\d+\.\d+\.\d+\.\d+\/\d+)\s/;
}
print "\t\"aws:SourceIp\": [" . join(",", @ip_conditions) . "]\n";