Skip to main content

Can I move parts of Shrine config to environments?

Rails • Asked by Michael Horton

I am using Shrine as you described in your Direct File Uploads to S3 episodes. It works fine, although I had to make a few minor tweaks to suit Bootstrap 4. One thing is troubling me: all files are going into one S3 bucket regardless of environment. I have a bucket created for Dev, Staging and Production, but I don't see in your episodes how to choose the buckets depending on environment. My only two thoughts are conditional statements in initializers/shrine.rb (which I don’t think I should) or move this block to the respective environments .rb files (which I don’t know if I can). Can I move the block over?

s3_options = {
  access_key_id:     ENV['AWS_ACCESS_KEY_ID'],
  secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
  region:            ENV['S3_REGION'],
  bucket:            ENV['S3_BUCKET_NAME'],

Because we set the bucket name in the secrets.yml, you can just change that for each environment just like you would do with any other secrets.

# config/initializers/shrine.rb
  bucket:            Rails.application.secrets.aws_bucket,
# config/secrets.yml
  aws_bucket: app-development

  aws_bucket: app-staging

  aws_bucket: app-production

Make sense?

It does make sense.

Although I don't use secrets.yml, I use environment variables.

Also, it appears I'll have to do the same with IAM logins since we made the login specific to the bucket. I might just add the policy to the user for now...


You can still populate secrets.yml with environment variables so it doesn't matter either way you slice it.

  aws_bucket: <%= ENV["AWS_BUCKET"] %>

Benefit of using secrets.yml is you can do both to keep everything consistent, especially when things like development environments often share test keys which don't really matter if they're in the repo or not.

And yeah, best long term solution for IAM stuff would be to have separate users for each bucket so nobody in development could accidentally delete your production files and vice versa.

I used secrets.yml incorrectly this summer and my AWS account got hacked. Luckily I didn't have to pay the $31,000 back. lol. But because of that, it will probably be a long time before I use secrets.yml again. I'll just suffer through making sure all my local machines have matching env variables. I use Heroku for all production projects. But thanks for the info.

DANG. That's a rough lesson to learn. Glad you didn't have to pay for any of that and I can't imagine how rampant that problem is for Amazon and other places.

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.