Skip to content

Instantly share code, notes, and snippets.

@nbibler
Created March 23, 2011 16:50
Show Gist options
  • Save nbibler/883455 to your computer and use it in GitHub Desktop.
Save nbibler/883455 to your computer and use it in GitHub Desktop.
Ruby script interacting with the Amazon AWS CloudFront Custom Origin API
#!/usr/bin/env ruby -w
require 'rubygems'
require 'hmac-sha1'
require 'net/https'
require 'base64'
AWS_KEY = '...'
AWS_SECRET = '...'
date = Time.now.utc
date = date.strftime("%a, %d %b %Y %H:%M:%S %Z")
digest = HMAC::SHA1.new(AWS_SECRET)
digest << date
uri = URI.parse("https://cloudfront.amazonaws.com/2010-11-01/distribution")
req = Net::HTTP::Post.new(uri.path)
req.initialize_http_header({
'x-amz-date' => date,
'Content-Type' => 'text/xml',
'Authorization' => "AWS %s:%s" % [AWS_KEY, Base64.encode64(digest.digest)]
})
req.body = <<XML
<?xml version="1.0" encoding="UTF-8"?>
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2010-11-01/">
<CustomOrigin>
<DNSName>%{origin_domain}</DNSName>
<HTTPPort>80</HTTPPort>
<HTTPSPort>443</HTTPSPort>
<OriginProtocolPolicy>match-viewer</OriginProtocolPolicy>
</CustomOrigin>
<CallerReference>%{reference}</CallerReference>
<Comment>%{comment}</Comment>
<Enabled>true</Enabled>
</DistributionConfig>
XML
req.body = req.body % {
origin_domain: '...',
reference: "CF#{Time.now.utc.to_f.to_s.gsub('.', '')}",
comment: '...'
}
puts req.body
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
res = http.request(req)
puts res.inspect
puts res.body
puts res.code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment