Sometimes, we need to change header info for S3 objects. One solution is to download file locally and upload it again with new header information.

Using Amazon API COPY functionality, it is possible to change headers on an S3 object without downloading the entire object. We need to set x-amz-metadata-directive as REPLACE to copy a S3 key to the same location.

But if we do this using right_aws ruby gem, ACL information is not preserved. For preserving ACL information as well, we need to preserve ACL permission before changing headers and then apply ACL again after changing headers.


#!/usr/bin/env ruby

require 'rubygems'
require 'right_aws'

@s3 = RightAws::S3Interface.new('AWS_ACESS_KEY', 'AWS_SECRET_KEY', :logger => STDOUT)

#In this example, I'm changing the mime-type to image/png.
#You can change whatever header you want.
update_s3_object_headers(bucket, key, {'Content-Type' => 'image/png'})

def update_s3_object_headers(bucket, key, headers)
#Saving current ACL
acl_xml = @s3.get_acl(bucket, key)[:object]
# Performing a copy with directive REPLACE
@s3.copy(bucket, key, bucket, key, :replace, headers)
#Restore ACL
@s3.put_acl(bucket, key, acl_xml)
end


Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.