-
-
Save jonyen/3948822 to your computer and use it in GitHub Desktop.
Ruby script to invalidate objects on Amazon's CloudFront CDN (shows status of recent requests also)
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 'rubygems' | |
require 'hmac-sha1' # on OS X: sudo gem install ruby-hmac | |
require 'net/https' | |
require 'base64' | |
# | |
# CHANGE ME: S3 access credentials go here, along with CloudFront Distribution ID | |
# | |
s3_access='' | |
s3_secret='' | |
cf_distribution='' | |
paths = nil | |
if ARGV[0] =~ /\-help/ | |
puts "usage: aws_cf_invalidate.rb [file1.html dir1/file2.jpg ...]" | |
puts "File list is optional... not specifying a list will return current status of recent invalidation requests" | |
exit | |
end | |
if ARGV.length > 0 | |
paths = '<Path>/' + ARGV.join('</Path><Path>/') + '</Path>' | |
quantity = ARGV.length.to_s | |
end | |
date = Time.now.utc | |
date = date.strftime("%a, %d %b %Y %H:%M:%S %Z") | |
digest = HMAC::SHA1.new(s3_secret) | |
digest << date | |
uri = URI.parse('https://cloudfront.amazonaws.com/2012-07-01/distribution/' + cf_distribution + '/invalidation') | |
if paths != nil | |
req = Net::HTTP::Post.new(uri.path) | |
else | |
req = Net::HTTP::Get.new(uri.path) | |
end | |
req.initialize_http_header({ | |
'x-amz-date' => date, | |
'Content-Type' => 'text/xml', | |
'Authorization' => "AWS %s:%s" % [s3_access, Base64.encode64(digest.digest)] | |
}) | |
if paths != nil | |
req.body = "<InvalidationBatch><Paths><Quantity>" + quantity + "</Quantity><Items>" + paths + "</Items></Paths><CallerReference>ref_#{Time.now.utc.to_i}</CallerReference></InvalidationBatch>" | |
end | |
http = Net::HTTP.new(uri.host, uri.port) | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
res = http.request(req) | |
# TODO: Check status code and pretty print the output | |
# Tip: pipe the output to | xmllint -format - |less for easier reading | |
#puts $STDERR res.code | |
puts res.body |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to latest API documentation changes and modified the schema accordingly as well.