Skip to content

Instantly share code, notes, and snippets.

@madysondesigns
Forked from jmlacroix/aws_cf_invalidate.rb
Last active August 29, 2015 14:10
Show Gist options
  • Save madysondesigns/8b06f8d29c5c4b65aa61 to your computer and use it in GitHub Desktop.
Save madysondesigns/8b06f8d29c5c4b65aa61 to your computer and use it in GitHub Desktop.
Invalidate Cloudfront objects from the command line.
# Forked from jmlacroix/aws_cf_invalidate.rb
# Modified to read s3 creds from the environment and the distribution id from arguments passed in.
require 'rubygems'
require 'hmac-sha1'
require 'net/https'
require 'base64'
s3_access=ENV['S3_ACCESS']
s3_secret=ENV['S3_SECRET']
if ARGV.length < 1
puts 'usage: aws_cf_invalidate.rb distribution_id file1.html dir1/file2.jpg ...'
exit
end
if s3_access.nil?
puts 's3_access token is nil'
exit
end
if s3_secret.nil?
puts 's3_secret is nil'
exit
end
cf_distribution=ARGV.shift
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment