Carrierwave and amazon s3

2019-04-17 03:04发布

问题:

I am using the carrierwave gem to manage file uploads in my rails 3 app, however, I am not able to connect to my amazon s3 bucket.

I have followed the instructions on the wiki yet they are not quite detailed enough, for example where do I store my s3 credentials?

回答1:

Put something like this in an initializer.

CarrierWave.configure do |config|
  config.storage = :fog
  config.fog_directory = 'your_bucket'

  config.fog_credentials = {
    :provider => 'AWS',
    :aws_access_key_id => 'your_access_key'
    :aws_secret_access_key => 'your_secret_key',
    :region => 'your_region'
  }
end

You can store your credentials right in the file, if you want (and the code is private). Or from a separate file, or the database, up to you. The following would load a config file and allow different configurations based on the env.

# some module in your app
module YourApp::AWS
  CONFIG_PATH = File.join(Rails.root, 'config/aws.yml')

  def self.config
    @_config ||= YAML.load_file(CONFIG_PATH)[Rails.env]
  end
end

# config/aws.yml
base: &base
  secret_access_key: "your_secret_access_key"
  access_key_id: "your_access_key_id"
  region: your_region
development:
  <<: *base
  bucket_name: your_dev_bucket
production:
  <<: *base
  bucket_name: your_production_bucket

# back in the initializer
config.fog_directory = YourApp::AWS.config['bucket_name']
# ...
config.fog_credentials = {
  :provider => 'AWS',
  :aws_access_key_id => YourApp::AWS.config['access_key_id'],
  :aws_secret_access_key => YourApp::AWS.config['secret_access_key'],
  :region => YourApp::AWS.config['region']
}


回答2:

Check out this quick blog post I wrote about how to do it. Basically there are a few steps, each of which is pretty complicated:

  • Configuring API keys (allowing you to connect to the Amazon S3 API)
  • Connecting the API keys to your account (make sure to keep the credentials not checked into GitHub if you're using a public repo though)
  • Deploying the changes out.

Hope this helps!