Skip to content

CloudFront Invalidation from Ruby

Since none of the examples that I could find on the internet of how to invalidate a cloudfront asset in ruby were correct, I decided to post my solution:

require 'rubygems' # may not be needed
require 'openssl'
require 'digest/sha1'
require 'net/https'
require 'base64'

class CloudfrontInvalidator
	def initialize(aws_account, aws_secret, distribution)
		@aws_account = aws_account
		@aws_secret = aws_secret
		@distribution = distribution
	def invalidate(path)
		date ="%a, %d %b %Y %H:%M:%S %Z")
		digest = Base64.encode64(OpenSSL::HMAC.digest('sha1'), @aws_secret, date)).strip
		uri = URI.parse("{@distribution}/invalidation")

		req =
		  'x-amz-date' => date,
		  'Content-Type' => 'text/xml',
		  'Authorization' => "AWS %s:%s" % [@aws_account, digest]
		req.body = %|<InvalidationBatch><Path>#{path}</Path><CallerReference>SOMETHING_SPECIAL_#{}</CallerReference></InvalidationBatch>|
		http =, uri.port)
		http.use_ssl = true
		http.verify_mode = OpenSSL::SSL::VERIFY_NONE
		res = http.request(req)
		# it was successful if response code was a 201
		return res.code == '201'

Then just run it with:



  1. Bob Tekiela wrote:

    Thanks. This is exactly what I was looking for today. Worked like a charm.

    Wednesday, October 26, 2011 at 12:50 pm | Permalink
  2. This is great! FYI i’ve modified it slightly to take any number of path args like so:

    def invalidate(*paths)
    paths ={|p| “#{p}”}.join


    Monday, January 9, 2012 at 10:43 am | Permalink
  3. That previous post stripped out my Path tags that wrap the #{p} in the path string mapping

    Monday, January 9, 2012 at 10:46 am | Permalink

Post a Comment

Your email is never published nor shared.