Setting Up AWS S3 With Rails

Letting a user upload images is tricky because they have to, you know, live somewhere. Here's how to set up AWS S3 with the Paperclip gem.

Tags: AWS, S3, Paperclip, Images, Ruby on Rails

Back to Blogs

Basically, the photos uploaded by your site will go into a "bucket" at AWS. First, log into your Amazon console account and go here to create a bucket.

As you progress, you will need to know the following properties of your bucket:

The other two things you'll need from Amazon are the access keys found in the "My Security Credentials" section of your AWS console:

The rest of the process to set up Paperclip is described pretty well here, especially if you're deploying to Heroku.

The only change I have had to make is to the config/environments/production.rb bit, where I had to add a line for the host name, which is basically a combination of the region and an AWS domain. This doesn't change how they're uploaded, but without it I haven't been able to get the photos to display properly. Here's the entire chunk, the last line being the part I added to Heroku's documentation:

  config.paperclip_defaults = {
    storage: :s3,
    s3_credentials: {
      bucket: ENV.fetch('S3_BUCKET_NAME'),
      access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
      secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY'),
      s3_region: ENV.fetch('AWS_REGION'),
      s3_host_name: 's3-us-west-1.amazonaws.com'
    }
  }

Obviously, the last bit is an example and you'll need to replace us-west-1 with whatever region your bucket is actually in.

HERE IS A VERY IMPORTANT DETAIL
This pearl of wisdom is dearly bought but freely given: do not put your AWS security credentials in your code. Put something like this lovely critter in your secrets.yml:

production:
  AWS_ACCESS_KEY_ID: <%= ENV["AWS_ACCESS_KEY_ID"] %>
  AWS_REGION: <%= ENV["AWS_REGION"] %>
  AWS_SECRET_ACCESS_KEY: <%= ENV["AWS_SECRET_ACCESS_KEY"] %>
  S3_BUCKET_NAME: <%= ENV["S3_BUCKET_NAME"] %>

And then use heroku config:set AWS_ACCESS_KEY=blahdeblah AWS_SECRET_ACCESS_KEY=blahdeblahdeblah to set your config variables in Heroku. Why, you might ask? Because if you publish these guys to GitHub, "entrepreneurial individuals" will find it, use your AWS account for free, and leave you with a bill for $7,468.08 in the few days it takes AWS to realize something is amuck. You will then have to spend a billion hours with the kindly folk AWS attempting to convince them that it wasn't you using their services across six continents. Not anyone's idea of a good time. Just a friendly warning.


Back to Blogs