Last active
June 19, 2017 18:17
-
-
Save iamkevinlowe/300ee4f35dc520b74789da09eaa55fff to your computer and use it in GitHub Desktop.
Ruby script to update cache control on S3 objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@s3 = Aws::S3::Client.new( | |
access_key_id: ENV['AWS_ACCESS_KEY_ID'], | |
secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'] | |
) | |
@bucket = ENV['S3_BUCKET_NAME'] | |
def get_objects(continuation_token = nil, last_key = nil) | |
options = { bucket: @bucket, prefix: 'images/uploads/' } | |
options.merge!(continuation_token: continuation_token) if continuation_token | |
options.merge!(start_after: last_key) if last_key | |
res = @s3.list_objects_v2(options) | |
replace_metadata(res[:contents]) | |
get_objects(res[:next_continuation_token], res[:contents].last.key) if res[:key_count] >= res[:max_keys] | |
end | |
def replace_metadata(objects) | |
objects.each do |object| | |
begin | |
if (/^images\/uploads\//).match(object.key) | |
@s3.copy_object( | |
bucket: @bucket, | |
key: object.key, | |
copy_source: "#{@bucket}/#{object.key}", | |
cache_control: 'public,max-age=31536000', | |
content_type: "image/#{object.key.match(/\.(\w*$)/)[1]}", | |
metadata_directive: 'REPLACE' | |
) | |
puts "Success: #{object.key}" | |
end | |
rescue Exception => e | |
puts "EXCEPTION: #{object.key} - #{e}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment