Created
September 24, 2011 13:28
-
-
Save glebm/1239322 to your computer and use it in GitHub Desktop.
A module to invalidate cache on Amazon CloudFront
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'openssl' | |
require 'net/http' | |
require 'net/https' | |
module CloudFront | |
extend self | |
def invalidate(path) | |
date = Time.now.utc | |
date = date.strftime("%a, %d %b %Y %H:%M:%S %Z") | |
digest = OpenSSL::HMAC.digest("sha1", s3_secret_key, date) | |
# 2010-11-01 is the API version | |
uri = URI.parse('https://cloudfront.amazonaws.com/2010-11-01/distribution/' + distribution_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" % [s3_access_key, Base64.encode64(digest)] | |
req.body = "<InvalidationBatch>" + "<Path>#{path}</Path>" + "<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) | |
# res.code == 201 # 201 for successful response | |
res.body | |
end | |
private | |
def s3_access_key | |
s3_config[Rails.env]['access_key_id'] | |
end | |
def s3_secret_key | |
s3_config[Rails.env]['secret_access_key'] | |
end | |
def distribution_id | |
s3_config[Rails.env]['cloud_front_distribution_id'] | |
end | |
def s3_config | |
@s3_config ||= YAML.load(File.read('config/amazon_s3.yml')) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment