Skip to content

Instantly share code, notes, and snippets.

@jmlacroix
Forked from nbibler/amazon_cloudfront_invalidation.rb
Created September 21, 2010 03:14
Show Gist options
  • Save jmlacroix/589132 to your computer and use it in GitHub Desktop.
Save jmlacroix/589132 to your computer and use it in GitHub Desktop.
Command line script to invalidate cloudfront objects
require 'rubygems'
require 'hmac-sha1'
require 'net/https'
require 'base64'
s3_access='S3_ACCESS_KEY'
s3_secret='S3_SECRET_KEY'
cf_distribution='CLOUDFRONT_DISTRIBUTION_ID'
if ARGV.length < 1
puts "usage: aws_cf_invalidate.rb file1.html dir1/file2.jpg ..."
exit
end
paths = '<Path>/' + ARGV.join('</Path><Path>/') + '</Path>'
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')
req = Net::HTTP::Post.new(uri.path)
req.initialize_http_header({
'x-amz-date' => date,
'Content-Type' => 'text/xml',
'Authorization' => "AWS %s:%s" % [s3_access, Base64.encode64(digest.digest)]
})
req.body = "<InvalidationBatch>" + paths + "<CallerReference>ref_#{Time.now.utc.to_i}</CallerReference></InvalidationBatch>"
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
res = http.request(req)
puts res.code
puts res.body
@adamjt
Copy link

adamjt commented Feb 18, 2011

Thanks! Saved me a bunch of work!

@raine
Copy link

raine commented Jul 18, 2011

+1, thanks!

@jookyboi
Copy link

+1, sweet

@eik3
Copy link

eik3 commented Jan 10, 2012

gem install ruby-hmac provides hmac-sha1

@nside
Copy link

nside commented Nov 15, 2014

I know this guy!

@opyate
Copy link

opyate commented Feb 12, 2015

👍

@Resvina
Copy link

Resvina commented Apr 6, 2017

not sure how to get in touch with you, that's why commenting; . I very new to ruby and cloud front and I see I can invalidate a specific image or a specific folder with this script but do you know how to use this path to invalidate everything in the host instead of providing a single path?(like the default path which cloudfront invalidates{/*}

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