Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darrenterhune/929244 to your computer and use it in GitHub Desktop.
Save darrenterhune/929244 to your computer and use it in GitHub Desktop.
require 'hmac-sha1'
require 'net/https'
require 'base64'
desc "Invalidate files from cloudfront distribution"
task :files, :filenames do |task, args|
CONFIG = YAML.load_file(File.join(RAILS_ROOT, 'config', 'amazon_s3.yml'))[RAILS_ENV]
s3_access = CONFIG['access_key_id']
s3_secret = CONFIG['secret_access_key']
cf_distribution = CONFIG['s3_assets_distribution_id']
puts "Distribution id... #{cf_distribution}"
paths = nil
paths = '<Path>/' + args[:filenames].split(" ").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
puts "Parsing url..."
uri = URI.parse('https://cloudfront.amazonaws.com/2010-08-01/distribution/' + cf_distribution + '/invalidation')
puts "Posting to cloudfront... #{uri}"
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)
puts res.code
puts res.body
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment