You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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 copyObject works: 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:CopyObject permission 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:09:28