hellomello
hellomello

Reputation: 8597

How to setup AWS credentials in rails for development?

I'm trying to figure out what is the best way to set up my credentials in development? I'm able to set up credentials in production because of heroku's configuration variables... but need help doing so if you're just testing app locally.

I have this in my development.rb

config.paperclip_defaults = {
  :storage => :s3,
  :s3_credentials => {
    :bucket => ENV['BUCKET_NAME'],
    :access_key_id => ENV['ACCESS_KEY_ID'],
    :secret_access_key => ENV['SECRET_ACCESS_KEY']
  }
}  

But, I'm not sure how to reference these ENV variables?

I created this aws.yml file in my /config folder

development:
  BUCKET_NAME: "somename"
  ACCESS_KEY_ID: "4205823951412980"
  SECRET_ACCESS_KEY: "123141ABNCEFEHUDSL2309489850"

I thought if I matched the ENV name, it'll work? I guess thats not the case...

I made sure to include aws.yml to my .ignore file

/config/aws.yml

Upvotes: 5

Views: 7221

Answers (4)

MZaragoza
MZaragoza

Reputation: 10111

What I like to is create a config.yml on my ./config directory.

then I tell the ./config/application.rb I have a small block that loads the variables like

config.before_initialize do
  dev = File.join(Rails.root, 'config', 'config.yml')
  YAML.load(File.open(dev)).each do |key,value|
    ENV[key.to_s] = value
  end if File.exists?(dev)
end

Here is my ./config/config.yml

BUCKET_NAME: "somename"
ACCESS_KEY_ID: "4205823951412980"
SECRET_ACCESS_KEY: "123141ABNCEFEHUDSL2309489850"

New Updates

Here is a copy of my #config/application.rb

#config/application.rb
require File.expand_path('../boot', __FILE__)

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

    module Appname
      class Application < Rails::Application
        # Settings in config/environments/* take precedence over those specified here.
        # Application configuration should go into files in config/initializers
        # -- all .rb files in that directory are automatically loaded.
    
        # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
        # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
        # config.time_zone = 'Central Time (US & Canada)'
    
        # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
        # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
        # config.i18n.default_locale = :de
    
        # Do not swallow errors in after_commit/after_rollback callbacks.
        config.active_record.raise_in_transactional_callbacks = true
    
        initializer 'setup_asset_pipeline', :group => :all  do |app|
          # We don't want the default of everything that isn't js or css, because it pulls too many things in
          app.config.assets.precompile.shift
    
          # Explicitly register the extensions we are interested in compiling
          app.config.assets.precompile.push(Proc.new do |path|
            File.extname(path).in? [
              '.html', '.erb', '.haml',                 # Templates
              '.png',  '.gif', '.jpg', '.jpeg',         # Images
              '.eot',  '.otf', '.svc', '.woff', '.ttf', # Fonts
            ]
          end)
        end
    
        I18n.enforce_available_locales = false
    
        config.before_initialize do
          dev = File.join(Rails.root, 'config', 'config.yml')
          YAML.load(File.open(dev)).each do |key,value|
            ENV[key.to_s] = value
          end if File.exists?(dev)
        end
      end
    end

Upvotes: 1

user4776684
user4776684

Reputation:

If everything else fails, you can simply start your rails app with command line params. It is good to know the base case, where you know for sure that your params are indeed passed to your app:

ACCESS_KEY_ID=ABCDEFG SECRET_ACCESS_KEY=secreTaccessKey BUCKET_NAME=dev-images rails s

I actually prefer to set an alias in env:

alias railss='ACCESS_KEY_ID=ABCDEFG SECRET_ACCESS_KEY=secreTaccessKey BUCKET_NAME=dev-images rails s'

Upvotes: 0

memoht
memoht

Reputation: 781

I like to use Foreman locally and store all my variables in a .ENV file. Plays well with Heroku and is easy to manage. Also in my case I have the following:

Under config/initiliazers/aws.rb

require 'aws-sdk'
require 'aws-sdk-resources'

# Rails.configuration.aws is used by AWS, Paperclip, and S3DirectUpload
Rails.configuration.aws = YAML.load(ERB.new(File.read("#{Rails.root}/config/aws.yml")).result)[Rails.env].symbolize_keys!
AWS.config(logger: Rails.logger)
AWS.config(Rails.configuration.aws)

Under config/initializers/paperclip.rb

# https://devcenter.heroku.com/articles/paperclip-s3
if Rails.env.test?
  Paperclip::Attachment.default_options.merge!(
    path: ":rails_root/public/paperclip/:rails_env/:class/:attachment/:id_partition/:filename",
    storage: :filesystem
  )
else
  Paperclip::Attachment.default_options.merge!(
    url: ':s3_domain_url',
    path: '/:class/:filename',
    storage: :s3,
    s3_credentials: Rails.configuration.aws,
    s3_protocol: 'https'
  )
end

Under config/aws.yml

defaults: &defaults
  access_key_id: <%= ENV['AWS_ACCESS_KEY_ID'] %>
  secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
test:
  <<: *defaults
  bucket: <%= ENV['AWS_TEST_BUCKET'] %>
development:
  <<: *defaults
  bucket: <%= ENV['AWS_TEST_BUCKET'] %>
production:
  <<: *defaults
  bucket: <%= ENV['AWS_BUCKET'] %>

Upvotes: 1

adamliesko
adamliesko

Reputation: 1915

You are looking for dotenv gem. Install the gem gem 'dotenv-rails', :groups => [:development, :test], then just create and `.env' file and put the variables into it like this.

S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE

Upvotes: 5

Related Questions