Skip to content

Instantly share code, notes, and snippets.

@thejefflarson
Created January 18, 2012 01:17
Show Gist options
  • Save thejefflarson/1630177 to your computer and use it in GitHub Desktop.
Save thejefflarson/1630177 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment