Created
September 22, 2010 05:23
-
-
Save jmlacroix/591196 to your computer and use it in GitHub Desktop.
Command line script to set the default root object of a cloudfront distribution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'hmac-sha1' | |
require 'net/https' | |
require 'base64' | |
s3_access='S3_ACCESS_KEY' | |
s3_secret='S3_SECRET_KEY' | |
cf_distribution='CLOUDFRONT_DISTRIBUTION_ID' | |
newobj = ARGV[0] | |
if newobj == nil | |
puts "usage: aws_cf_setroot.rb index.html" | |
exit | |
end | |
date = Time.now.utc | |
date = date.strftime("%a, %d %b %Y %H:%M:%S %Z") | |
digest = HMAC::SHA1.new(s3_secret) | |
digest << date | |
uri = URI.parse('https://cloudfront.amazonaws.com/2010-08-01/distribution/' + cf_distribution + '/config') | |
req = Net::HTTP::Get.new(uri.path) | |
req.initialize_http_header({ | |
'x-amz-date' => date, | |
'Content-Type' => 'text/xml', | |
'Authorization' => "AWS %s:%s" % [s3_access, Base64.encode64(digest.digest)] | |
}) | |
http = Net::HTTP.new(uri.host, uri.port) | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
res = http.request(req) | |
currentobj = /<DefaultRootObject>(.*?)<\/DefaultRootObject>/.match(res.body)[1] | |
if newobj == currentobj | |
puts "'#{currentobj}' is already the DefaultRootObject" | |
exit | |
end | |
etag = res.header['etag'] | |
req = Net::HTTP::Put.new(uri.path) | |
req.initialize_http_header({ | |
'x-amz-date' => date, | |
'Content-Type' => 'text/xml', | |
'Authorization' => "AWS %s:%s" % [s3_access, Base64.encode64(digest.digest)], | |
'If-Match' => etag | |
}) | |
if currentobj == nil | |
regex = /<\/DistributionConfig>/ | |
replace = "<DefaultRootObject>#{newobj}</DefaultRootObject></DistributionConfig>" | |
else | |
regex = /<DefaultRootObject>(.*?)<\/DefaultRootObject>/ | |
replace = "<DefaultRootObject>#{newobj}</DefaultRootObject>" | |
end | |
req.body = res.body.gsub(regex, replace) | |
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.code | |
puts res.body |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice stuff. I think there is a small bug though. You should have something like the following for the first comers (when DefaultRootObject is not there yet). But then again, not a ruby expert.