public

  • Download Gist
cloudfront-invalidator.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
# purge cloudfront buckets usage
#
# $ invalidator cloudfront_id [urls]
#
# requires /etc/aws.conf to be a yaml of you aws credentials like:
#
# access_key: [redacted]
# secret_access_key: [redacted]
 
 
require 'rubygems'
require 'yaml'
require 'base64'
require 'openssl'
require 'net/https'
require "rexml/document"
 
class CloudInvalidator
def initialize(cf_id, *urls)
@batch = "purging " + Time.now.to_s
@cf_id = cf_id
@url = URI.parse "https://cloudfront.amazonaws.com/2010-11-01/distribution/#{@cf_id}/invalidation"
@urls = urls
purge!
end
 
private
 
def purge!
resp = post
 
if resp.code == '201'
puts "== \x1b[32mOK \x1b[0mpurging #{@urls.join(",")}"
puts "current jobs: #{get}"
else
puts "== \x1b[31mERROR\x1b[0m\n#{resp.body}"
puts "current jobs:\n#{get}"
end
end
 
def response(method, data='')
req = Net::HTTP.new(@url.host, @url.port)
req.use_ssl = true
req.verify_mode = OpenSSL::SSL::VERIFY_NONE
req.send_request(method, @url.path, data, headers)
end
 
def post
response 'POST', purge_list
end
 
def get
resp_list response 'GET'
end
 
def resp_list(resp)
list = []
REXML::Document.new(resp.body).each_element("/InvalidationList/InvalidationSummary") do |el|
list << el.elements["Id"].text + ":" + el.elements["Status"].text
end
list.join("\n")
end
 
def purge_list
"<InvalidationBatch>#{@urls.map {|u| "<Path>" + u + "</Path>"}.join("")}<CallerReference>#{@batch}</CallerReference></InvalidationBatch>"
end
 
 
def headers
creds = YAML::load_file '/etc/aws.conf'
date = Time.now.strftime('%a, %d %b %Y %H:%M:%S %Z')
 
signer = OpenSSL::Digest::Digest.new('sha1')
digest = OpenSSL::HMAC.digest(signer, creds['secret_access_key'], date)
 
auth = Base64.encode64(digest).strip
 
{ 'Date' => date,
'Authorization'=> ["AWS #{creds['access_key']}:#{auth}"].join(',') }
end
end
 
if __NAME__ = $0
cf_id = ARGV.shift
CloudInvalidator.new cf_id, *ARGV
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.