Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby script to invalidate objects on Amazon's CloudFront CDN (shows status of recent requests also)
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>'
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/2010-08-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 + "<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
@kyranjamie

This comment has been minimized.

Copy link

commented Jul 7, 2015

Great fork 👍

This script is so much better than using Cyberduck.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.