Search code examples
ruby-on-railsamazon-web-servicesamazon-s3amazon-iamrails-activestorage

Failing to set credentials for Rails project to use S3 with IAM role


I'm using ActiveStorage to upload files to S3 bucket. If anyone is familiar with Heroku Bucketeer add-on, I used it for a while to test ActiveStorage and uploading and downloading files to and from the bucket worked.

For certain reasons, I have to set credentials to new Amazon S3 bucket with only bucket name and region, using IAM role. In ActiveStorage RubyOnRails guide it says:

If you want to use environment variables, standard SDK configuration files, profiles, IAM instance profiles or task roles, you can omit the access_key_id, secret_access_key, and region keys in the example above.

However I get

(Aws::Sigv4::Errors::MissingCredentialsError)
- :access_key_id and :secret_access_key
- :credentials
- :credentials_provider

my storage.yml looks like this:

amazon:   
  service: S3   
  bucket: <%= ENV['BUCKET_NAME'] %>   
  region: <%= ENV['AWS_REGION'] %>

I have written config.active_storage.service = :amazon both in development.rb and production.rb

I already tried Configuring ActiveStorage to use S3 with IAM role, but in vain.

I'm using Rails 5.2.4.1, Ruby 2.6.3, and have gem 'aws-sdk' in Gemfile


Solution

  • Especially when working in development you will need to provided an access_key_id and a secret_access_key. You can do this by putting in storage.yml:

    amazon:
      service: S3
      access_key_id: <%= ENV['AWS_ACCESS_KEY_ID'] %> 
      secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
      bucket: <%= ENV['BUCKET_NAME'] %>   
      region: <%= ENV['AWS_REGION'] %>
    

    Alternatively, ensure that you have set the right environment variables, to enable the implicit lookup of your aws credentials, as specified by AWS. That is, set the environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY