Stale Betty

Blog // About // Contact

Read on Apple News

Connecting the Rails Girls App with Amazon S3

January 19 2017

Connecting the Rails Girls App with Amazon S3

Amazon S3 (Simple Storage Service) is a web service offered by Amazon Web Services. Amazon S3 provides storage through web services interfaces. It allows users running applications on Heroku to store and deliver images for their apps.

It seems like I’ve been working on the Rails Girls Ideas App for ages. GitHub says it’s been about two months but it may be longer. This week I finally figured out how to get it connected to Amazon S3. I’m not going to lie, it took the wind out of my sails to get it set up on Heroku only to find out the images disappeared every day. I still don’t understand why I would be encouraged to use a service like Heroku that can not fulfill ALL my application needs. Maybe someone can explain?

Getting connected to Amazon S3 was a lot more time consuming than I expected. I ended up writing a gist with instructions for my own future reference but if you would like to read it, please view it here: Rails Girls App with Amazon S3. The gist is a bit detailed so to summarize, I signed up for an Amazon Web Services (AWS) account, created a user for my app, and two buckets - each with read-only permission for anonymous users. Since I was already using Carrierwave, I installed Fog and Figaro and used an initializer to set the variables for the AWS ID and Key.

# config/initializers/carrierwave.rb
require 'carrierwave/storage/abstract'
require 'carrierwave/storage/file'
require 'carrierwave/storage/fog'
CarrierWave.configure do |config|
  config.root = Rails.root.join('tmp')
  config.cache_dir = 'carrierwave'
  config.fog_credentials = {
    :provider               => 'AWS',
    :aws_access_key_id      => ENV["AWS_ACCESS_KEY_ID"],
    :aws_secret_access_key  => ENV["AWS_SECRET_ACCESS_KEY"]
  config.fog_directory  = ENV["S3_BUCKET_NAME"]

Then I updated the uploader to change the storage to Fog and added a whitelist so limit uploads to jpeg, jpg, png, and gif images. When I installed the gems, a new file was created called config/application.yml. It was added to .gitignore automatically so it would not be included in my git commits… important because this is where I specified my AWS ID, Key, and bucket names, like so:

  FOG_DIRECTORY: my-app-name-dev
  S3_BUCKET_NAME: my-app-name-dev
  FOG_DIRECTORY: my-app-name
  S3_BUCKET_NAME: my-app-name

I added, committed, and pushed to my GitHub repository. Before pushing to Heroku, I added my AWS ID and Key:

heroku config:set S3_KEY=XXX S3_SECRET=XXX

I ran into a few errors along the way. At least one was due to reading the wrong Carrierwave documentation but the biggest issue was solved by simply adding policy permissions to my AWS user and buckets. In the end it was a “duh” moment but it tied me up for hours before I figured it out.