Skip to content

Instantly share code, notes, and snippets.

@joost
Last active August 26, 2016 01:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joost/94963b74c5b03b2b752f to your computer and use it in GitHub Desktop.
Save joost/94963b74c5b03b2b752f to your computer and use it in GitHub Desktop.
Change metadata on existing S3 files
# Using v1 of Ruby aws-sdk as currently v2 seems not able to do this (broken?).
require 'aws-sdk-v1'
key = YOUR_AWS_KEY
secret = YOUR_AWS_SECRET
region = YOUR_AWS_REGION
AWS.config(access_key_id: key, secret_access_key: secret, region: region)
s3 = AWS::S3.new
bucket = s3.buckets[bucket_name]
bucket.objects.with_prefix('images/').each do |obj|
puts obj.key
# Add metadata: {} to next line for more metadata.
obj.copy_from(obj.key, content_type: obj.content_type, cache_control: 'max-age=1576800000', acl: :public_read)
end
# Using aws-sdk version 2.
# NOTE: This currently does NOT seem to work.
require 'aws-sdk'
credentials = Aws::Credentials.new(aws_key, aws_secret)
# s3 = Aws::S3::Client.new(credentials: credentials, region: aws_region)
# s3.list_objects(bucket: bucket_name, prefix: "images/").each do |response|
# puts response.contents.first
# puts response.contents.map(&:key)
# end
# operation_names
s3resource = Aws::S3::Resource.new(credentials: credentials, region: Rails.configuration.aws_region)
bucket = s3resource.bucket(bucket_name)
# obj = bucket.objects.first
bucket.objects.each do |obj|
puts "#{obj.key} => #{obj.etag}"
# obj.copy_from(obj.key) # FIXME: Using aws-sdk v2.0.27 this currently does not work :S
end
@doooby
Copy link

doooby commented Sep 1, 2015

Yeah so #copy_from either #copy_to doesn't work/exists, although documentations mentions them. here's what I did (down&up-loading each file):

s3o = bucket.object key
IO.copy_stream s3o.get.body, tmp_file
s3o.upload_file tmp_file, content_type: 'image/jpeg'

@justjake
Copy link

#copy_from and #copy_to work fine; see my Stack Overflow answer: http://stackoverflow.com/a/39156978

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