Skip to content

Instantly share code, notes, and snippets.

@crowdmatt
Created June 23, 2012 18:42
Show Gist options
  • Save crowdmatt/2979403 to your computer and use it in GitHub Desktop.
Save crowdmatt/2979403 to your computer and use it in GitHub Desktop.
Create a new Amazon CloudFront distribution for an S3 bucket in Ruby
# Here is some sample code to create a CloudFront distribution programmatically from Ruby.
# Tested to be working on 06-23-2012.
# Amazon's documentation is wrong, so we're putting the XML here!
#
# We're using this at http://www.crowdmob.com/ to simplify our development process.
#
# Prerequisite: You'll need the simple_aws gem which you can get from `gem install simple_aws`
#
require 'simple_aws/s3'
require 'simple_aws/cloud_front'
S3_BUCKET_NAME = 'MYBUCKETNAME'
AWS_KEY = '...'
AWS_SECRET = '...'
def cloudfront_creation_xml(s3bucket)
"<DistributionConfig xmlns=\"http://cloudfront.amazonaws.com/doc/2012-05-05/\"><CallerReference>#{s3bucket}-creation-#{Time.now}</CallerReference><S3Origin><DNSName>#{s3bucket}.s3.amazonaws.com</DNSName></S3Origin><Aliases><Quantity>0</Quantity></Aliases><Comment/><Logging><Enabled>false</Enabled><Bucket>#{s3bucket}-logs-disabled.s3.amazonaws.com</Bucket><Prefix>#{s3bucket}.logprefix</Prefix></Logging><TrustedSigners><Enabled>false</Enabled><Quantity>0</Quantity></TrustedSigners><Enabled>true</Enabled></DistributionConfig>"
end
cloudfront = SimpleAWS::CloudFront.new AWS_KEY, AWS_SECRET
distribution = cloudfront.post "/distribution",
:body => cloudfront_creation_xml(S3_BUCKET_NAME)
puts "- Cloudfront distribution created `#{distribution.domain_name}`"
@alexanderdean
Copy link

Are you sure line 11 shouldn't be:

require 'simple_aws/cloud_front'

?

@crowdmatt
Copy link
Author

Indeed

@alexanderdean
Copy link

Thanks Matt - this is really helpful! I still get an error with this XML when accessing a resource:

MissingKeyMissing Key-Pair-Id query parameter

The underlying file I'm accessing is available publically through its S3 URL no problem. I think the issue is something to do with the <TrustedSigners> tag - any idea offhand what it might be?

@crowdmatt
Copy link
Author

I'm not sure -- did you make sure trusted signers was false? i.e. false ...

@crowdmatt
Copy link
Author

Oops looks like might markdown didn't work <TrustedSigners><Enabled>false</Enabled> ... </TrustedSigners>

@alexanderdean
Copy link

Hmm, yep I made sure TrustedSigners was false. Weird. Will try using another library...

@alexanderdean
Copy link

The other libraries were terrible - your gist is the only game in town :-) I fixed it by removing:

<TrustedSigners><Enabled>false</Enabled> ... </TrustedSigners>

To confirm: for a public distribution, do not add the TrustedSigners section, or you will get missing key errors...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment