Heroku + ActiveStorage + Amazon S3

1 AWS Console → Services → Storage → Packet creation with S3

item Input / selection
Packet name ex: my-rails-app-first-bucket
region :flag_jp:Tokyo
Access rights All check boxes are off
Other than those above Default

2 Make an access key See below https://tech-blog.s-yoshiki.com/entry/135

3 Required Gem installation

gem "aws-sdk-s3", require: false #Postscript

4 Enter the access key to S3

$ EDITOR=vim rails credentials:edit

#Uncomment
aws:
 access_key_id: #Copy and paste your access key ID here
 secret_access_key: #Copy and paste your secret access key here

-vi / vim operation- Start editing with i key, end editing with esc, save with ZZ and end If you want to confirm the input later

$ rails credentials:show

5 Change image save destination on Heroku to Amazon S3

config/storage.yml


amazon:
  #The following 3 lines remain as they are
  service: S3
  access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
  secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
  #Change the following two lines
  region: ap-northeast-1 #Tokyo
  bucket: my-rails-app-first-bucket #The name of your S3 bucket

config/environmentas/production.rb


config.active_storage.service = :amazon #Change to amazon

6 Last thing to do on Heroku

$ heroku buildpacks:add -i 1 https://github.com/heroku/heroku-buildpack-activestorage-preview
$ git add .
$ git commit -m "added s3 to production"
$ git push heroku master

Copy the Rails project master key (contents of config / master.key)

$ heroku config:set RAILS_MASTER_KEY=Paste the master key here
$ heroku run rails db:migrate
$ heroku open

Recommended Posts

Heroku + ActiveStorage + Amazon S3
Save images to Amazon S3 (Local / Heroku)
upload images to refile heroku S3