如何通过Lambda每小时更新Amazon S3文件修改时间并保留原内容
Update S3 File Last Modified Time Without Overwriting Content
Got it, let's fix this for you! The problem with using putObject here is that it overwrites your file's content, which isn't what you want. Instead, you can use S3's copyObject API to copy the file onto itself—this trick updates the last modified timestamp while keeping the original content intact, and you don't need to fetch the file content first.
Here's the revised Lambda code that does exactly this:
const AWS = require('aws-sdk'); const s3 = new AWS.S3(); exports.handler = async (event) => { const bucketName = 'BUCKET_NAME'; const keyName = 'KEY_NAME'; try { await s3.copyObject({ Bucket: bucketName, Key: keyName, // Specify the same object as the source CopySource: `/${bucketName}/${keyName}`, // Explicitly tell S3 to copy existing metadata (this is the default, but makes intent clear) MetadataDirective: 'COPY' }).promise(); const updateMessage = `Successfully updated last modified time for: s3://${bucketName}/${keyName}`; console.log(updateMessage); return { statusCode: 200, body: JSON.stringify(updateMessage) }; } catch (error) { console.error('Failed to update file:', error); return { statusCode: 500, body: JSON.stringify(`Error updating file: ${error.message}`) }; } };
Key Details:
- Why
copyObjectworks: When you copy an object to its own key in the same bucket, S3 automatically updates the object's last modified timestamp. The content and metadata (unless you specify otherwise) remain identical to the original. - No content fetch needed: Unlike
putObject, you don't have to retrieve the file's content first—S3 handles copying the existing object internally. - Permissions: Make sure your Lambda execution role has the
s3:CopyObjectpermission for the target bucket and key. Add this to your role's policy if it's missing:{ "Effect": "Allow", "Action": "s3:CopyObject", "Resource": "arn:aws:s3:::BUCKET_NAME/KEY_NAME" }
Additional Notes:
- Cost: Copying within the same AWS region doesn't charge data transfer fees, but you'll pay the standard S3 API request cost (which is minimal for hourly runs).
- Versioning: If your bucket has versioning enabled, this will create a new version of the object with the updated timestamp. Original versions will still be accessible if you need to roll back later.
内容的提问来源于stack exchange,提问作者Kaz
相关产品推荐
相关产品推荐

