Skip to content

Instantly share code, notes, and snippets.

@miguelperez
Created September 8, 2023 16:19
Show Gist options
  • Select an option

  • Save miguelperez/8d0a9280d7589b55f353d242b3fdb120 to your computer and use it in GitHub Desktop.

Select an option

Save miguelperez/8d0a9280d7589b55f353d242b3fdb120 to your computer and use it in GitHub Desktop.
Use the same IAM assumed roles to connect to AWS S3 without having to pass credentials.

Intro

when using activestorage, one could set the ec2 instance with a role with access to certain aws s3 buckets.

In this case, we only define the region and bucket name to allow activestorage to connect to s3.

# in config/storage.yml
some_files:
  service: S3
  region: #{Rails.application.credentials.dig(:aws, :some_files, :region)}
  bucket: #{Rails.application.credentials.dig(:aws, :some_files, :bucket)}

Then if you would like to download or upload something to S3 without having to do it via ActiveStorage you could do the following:

client = Aws::S3::Client.new(region: 'us-east-2')  
resource = Aws::S3::Resource.new(client: client)
bucket = resource.bucket("bucket-name")

# getting a file from the bucket
new_object = bucket.object("some file key")
object = new_object.get

# if you would like to store this file
File.open('my new file name', 'wb') do |file|
  IO.copy_stream(object.body, file)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment