class SimpleCloudfrontInvalidator::CloudfrontClient

Public Class Methods

new(aws_account, aws_secret, distribution) click to toggle source
# File lib/simple-cloudfront-invalidator.rb, line 10
def initialize(aws_account, aws_secret, distribution)
  @aws_account = aws_account
  @aws_secret = aws_secret
  @distribution = distribution
end

Public Instance Methods

invalidate(items) click to toggle source
# File lib/simple-cloudfront-invalidator.rb, line 16
def invalidate(items)
  items = prefix_with_slash(items)
  body = %|
    <InvalidationBatch>
      <Paths>
        <Quantity>#{items.length}</Quantity>
        <Items>
          #{to_xml items}
        </Items>
      </Paths>
      <CallerReference>#{Time.now.utc.to_i}</CallerReference>
    </InvalidationBatch>
  |
  res = sign_and_call(
    "https://cloudfront.amazonaws.com/2012-05-05/distribution/#{@distribution}/invalidation",
    Net::HTTP::Post, body)
  return { :text_report => create_report(items),
           :invalidated_items_count => items.length }
end

Private Instance Methods

create_report(items) click to toggle source
# File lib/simple-cloudfront-invalidator.rb, line 61
def create_report(items)
  report = []
  report << "Invalidating Cloudfront items..."
  items.each do |item|
    report << "  #{item}".yellow
  end
  report << "succeeded".green
end
prefix_with_slash(file_names) click to toggle source
# File lib/simple-cloudfront-invalidator.rb, line 70
def prefix_with_slash(file_names)
  file_names.map { |file_name| "/#{file_name}" }
end
sign_and_call(url, method, body = nil) click to toggle source
# File lib/simple-cloudfront-invalidator.rb, line 38
def sign_and_call(url, method, body = nil)
  date = Time.now.utc.strftime("%a, %d %b %Y %H:%M:%S %Z")
  digest = Base64.encode64(
    OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha1'), @aws_secret, date)).strip
  uri = URI.parse(url)
  req = method.new(uri.path)
  req.initialize_http_header({
    'x-amz-date' => date,
    'Content-Type' => 'text/xml',
    'Authorization' => "AWS %s:%s" % [@aws_account, digest]
  })
  req.body = body unless body == nil
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  res = http.request(req)
  if res.code.to_i.between? 200, 299
    res
  else
    raise "AWS API call failed. Reason:".red + "\n" + res.body
  end
end
to_xml(items) click to toggle source
# File lib/simple-cloudfront-invalidator.rb, line 74
def to_xml(items)
  items.map { |item| "<Path>#{item}</Path>" }
end