Alex Rivera | Logout

Rails How to upload precompiled assets to Cloudfront

Asked 2012-05-24T22:09:19.993
15
  • I'm using a Rails 3.2 app
  • I created a Cloudfront distribution with a S3 origin
  • I already change config.action_controller.asset_host to my cloudfront asset
  • I'm using capistrano

I want to know, how to upload my precompiled assets to Cloudfront every time I deploy

Edit
Report

1 Answer

15

After installing the aws-s3 gem, you can add this at this end of your capistrano recipe :

set :cdn_user, "KEY ID" # This is called "CDN KEY API" for AWS
set :cdn_api_key, "YOUR KEY SECRET"
set :cdn_container, "bucket name"

namespace :assets do
    task :to_cdn do
      require 'aws/s3'
      AWS::S3::Base.establish_connection!(:access_key_id => cdn_user, :secret_access_key => cdn_api_key )
      assets_dir = "#{shared_path}/assets"
      Dir.glob(assets_dir + "/**/*").each do |file|
        if !File.directory?(file)
          cdn_filename = file.gsub(assets_dir,"assets")
          AWS::S3::S3Object.store(cdn_filename, open(file) , cdn_container)
        end
      end
    end
end

Using a trigger like this :

after "deploy:assets:precompile", "assets:to_cdn"

You will also need to launch the compilation at some point in your recipe with :

load 'deploy/assets'

Result : at the end of your asset compilation, all your assets are going to be pushed on S3, and you will be able to access them from cloudfront.

You then have to update your config/environment/production.rb to point to your CDN URL.

config.action_controller.asset_host = "http://assets.example.com"
answered 2012-05-24T22:32:39.373

Your Answer