Using Amazon S3

So I noticed that when I accessed my app on Heroku and uploaded images, that if I left them there they would eventually go away and be dead images.  I figured it had something to do with how Heroku doesn’t store images, and I was correct.  Every so often (maybe when the server powers down?) all images and uploads are deleted to prevent people from using Heroku for file storage.  The solution here is Amazon S3, and I’ll use this guide to do it.

I registered for an Amazon Web Services account and waited for it to be activated.  Next I need to paste the following into my production.rb file:

# Configuring Amazon S3 for Paperclip file uploads
config.paperclip_defaults = {
  :storage => :s3,
  :s3_credentials => {
    :bucket => ENV['AWS_BUCKET'],
    :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
    :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']

Instead of actually entering in my AWS access keys (which would be really insecure since I’m uploading all of this code to a public repo on Github) I’m going to use those environment variables (ENV) which I set via terminal and don’t have to enter in my code.

After I add that code, I’ll commit and push to Git & Heroku.  Image uploads still don’t work though, because we never set those variables.  That’s okay, I can do that now.  To do this I put the following in Terminal:

$ heroku config:add AWS_BUCKET=your_bucket_name
$ heroku config:add AWS_ACCESS_KEY_ID=your_access_key_id
$ heroku config:add AWS_SECRET_ACCESS_KEY=your_secret_access_key

If I ever want to check on these variables again in the future I can put $ heroku config in the Terminal.  Now, it works!  My images are uploading to S3 and the app is still hosted on Heroku.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s