Skip to content

Instantly share code, notes, and snippets.

@hartfordfive
Created November 1, 2016 17:47
Show Gist options
  • Save hartfordfive/19097441d3803d9aa75ffe5ecf0696da to your computer and use it in GitHub Desktop.
Save hartfordfive/19097441d3803d9aa75ffe5ecf0696da to your computer and use it in GitHub Desktop.
Check if file exists in S3 bucket with Ruby aws-sdk gem
require 'aws-sdk'
s3 = Aws::S3::Resource.new(
region: 'us-east-1',
credentials: Aws::InstanceProfileCredentials.new()
)
bucket = s3.bucket('my-daily-backups')
file = (DateTime.now).strftime("%Y.%m.%d-backup")
if bucket.object(file).exists?
puts "File '/my-daily-backups/#{file}' is present in S3 bucket!"
else
puts "File '/my-daily-backups/#{file}' is not in S3 bucket!"
end
@toddnestor
Copy link

Thanks, just what I was looking for!

@joshuapinter
Copy link

I had a weird situation where exists? would return true but there would be no meaningful file. Another check that's valuable is to use bucket.object(file).content_length.zero?.

@yumao5
Copy link

yumao5 commented Dec 8, 2017

Thanks, very helpful. Make my way to there as blow.

File url s3://51-alien-test/cover/51.pdf

s3 = Aws::S3::Resource.new(region: 'us-central-51', access_key_id: 'xxxx', secret_access_key: 'xxxxx')
bucket = s3.bucket('51-alien-test')
bucket.object('cover/51.pdf').exists?

@geralch
Copy link

geralch commented Dec 10, 2018

Thank you!! ヽ(^◇^*)/

@kendrikat
Copy link

kendrikat commented Mar 11, 2019

And anyone getting Exceptions instead of a Boolean result, check this aws/aws-sdk-ruby#201 (comment).

@rokity
Copy link

rokity commented Sep 23, 2019

If you don't ahve permission on the object that are you checking, the result it'll be false every time. So it's not an helpful script.

collect=bucket.objects(prefix: _object).collect(&:key)
      p collect
      collect.each do |item|
        if(item==_object)
          return render json: true
        end
      end
return render json: false
`

@MittalPatel-BTC
Copy link

Thanks, it's helpful for me!

@sebasjimenez10
Copy link

Life saver! Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment