Skip to content

Instantly share code, notes, and snippets.

@robparvin
Created February 28, 2012 12:03
Show Gist options
  • Save robparvin/1932149 to your computer and use it in GitHub Desktop.
Save robparvin/1932149 to your computer and use it in GitHub Desktop.
Amazon CloudFront cache invalidator for Paperclip & Fog for use with various defined image styles
require 'openssl'
require 'digest/sha1'
require 'net/https'
require 'base64'
class CloudFrontInvalidator
#file - The Paperclip attachment
#style - The defined style to invalidate (e.g. :original, :thumbnail...)
def initialize(file, style = :original)
@aws_account = aws_access_key_id
@aws_secret = aws_secret_access_key
@path = URI.parse(file.url(style)).path
end
def invalidate
date = Time.now.strftime("%a, %d %b %Y %H:%M:%S %Z")
digest = Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), @aws_secret, date)).strip
#Bucket_ID - This is the the Amazon Cloud Front Distribution ID for your bucket
#2010-11-01 identifies the version of the CloudFront API you use
uri = URI.parse("https://cloudfront.amazonaws.com/2010-11-01/distribution/#{Bucket_ID}/invalidation")
req = Net::HTTP::Post.new(uri.path)
req.initialize_http_header({
'x-amz-date' => date,
'Content-Type' => 'text/xml',
'Authorization' => "AWS %s:%s" % [@aws_account, digest]
})
#Caller_Ref - This is a unique value that you provide to Amazon Cloudfront
req.body = %|<InvalidationBatch><Path>#{@path}</Path><CallerReference>#{Caller_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)
return res.code == '201'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment