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

AWS Lambda Python调用CopyObject时出现Access Denied问题求助

问题分析与解决

一、CopyObject权限错误的修复

1. IAM策略资源配置错误

你的IAM策略中,s3:GetObject和s3:PutObject的资源仅指定了桶ARN,但这类操作需要对象级ARN(桶ARN后追加/*)。修正后的策略如下:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:GetObjectTagging"
            ],
            "Resource": "arn:aws:s3:::knlambdasourcebucket/*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": "s3:ListBucket",
            "Resource": "arn:aws:s3:::knlambdasourcebucket"
        },
        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:PutObjectTagging"
            ],
            "Resource": "arn:aws:s3:::knlambdadestbucket/*"
        }
    ]
}
  • s3:ListBucket属于桶级操作,资源用桶ARN即可;
  • s3:GetObject/s3:PutObject是对象级操作,必须指定桶ARN/*覆盖桶内所有对象。

2. Python代码逻辑错误

你的for循环写在了lambda_handler函数外部,Lambda执行时仅会运行lambda_handler内部的代码,循环逻辑根本不会触发。修正后的代码:

import boto3
import json

s3 = boto3.resource('s3')

def lambda_handler(event, context):
    dest_bucket = s3.Bucket('knlambdadestbucket')
    source_bucket = s3.Bucket('knlambdasourcebucket')
  
    for obj in source_bucket.objects.all():
        dest_key = obj.key
        print(dest_key)
        s3.Object(dest_bucket.name, dest_key).copy_from(
            CopySource={'Bucket': obj.bucket_name, 'Key': obj.key}
        )
    return {"statusCode": 200, "body": "Copy completed"}

二、Lambda代码调试工具

  • Lambda控制台内置测试:在控制台创建测试事件,执行后直接查看返回结果与基础日志;
  • CloudWatch日志:Lambda执行日志自动同步至CloudWatch,可通过日志组(格式为/aws/lambda/你的函数名)查看详细报错、打印信息;
  • 本地调试工具:使用AWS SAM CLI,能在本地模拟Lambda运行环境,支持断点调试;
  • Lambda步进调试:控制台开启步进调试功能后,可逐行执行代码,实时查看变量值与调用栈。

内容的提问来源于stack exchange,提问作者Keyan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:55:28