AWS S3 add metadata cache control to existing keys

Code for adding cache-control to the all S3 key/object for a given bucket.

    import json
    import urllib
    from boto.s3.connection import S3Connection
    one_month = 3600*24*30
    one_year  = 3600*24*365
    cckey = 'cache-control'

    s3_connection = S3Connection()
    bucket_name = ''
    bucket = s3_connection.get_bucket(bucket_name, validate=False)

    for key in bucket:
        key_name = key.key
        if  key.size == 0: # continue on directories
            continue
        key = bucket.get_key(key_name)

        cache_time = one_month
        key.set_metadata(name=cckey, value = ('max-age=%d, public' % (cache_time)))
        key.set_metadata(name='content-type', value = key.content_type) # preserve the content-type
        
        key2 = key.copy(key.bucket.name, key.name, key.metadata, preserve_acl=True)
        #print(key2.__dict__)
        continue

Code for adding cache-control to a particular key for a given bucket.

    import json
    import urllib
    from boto.s3.connection import S3Connection
    one_month = 3600*24*30
    one_year  = 3600*24*365
    cckey = 'cache-control'

    s3_connection = S3Connection()
    bucket_name = ''
    key_name = ''
    bucket = s3_connection.get_bucket(bucket_name, validate=False)
    key = bucket.get_key(key_name) 
    key_name = key.key
    cache_time = one_month
    key.set_metadata(name=cckey, value = ('max-age=%d, public' % (cache_time)))
    key.set_metadata(name='content-type', value = key.content_type) # preserve the content-type
    
    key2 = key.copy(key.bucket.name, key.name, key.metadata, preserve_acl=True)

Leave a Reply

Your email address will not be published. Required fields are marked *