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

使用CloudFormation CLI创建自定义资源时,执行DELETE操作删除S3桶遭遇AccessDenied权限错误

Troubleshooting S3 DeleteBucket Access Denied in CloudFormation Custom Resource

Let’s break down why you’re hitting that AccessDenied error when trying to delete your S3 bucket via a CloudFormation custom resource—even with a wildcard S3 policy attached to your execution role. Here are the most likely culprits and fixes:

1. The bucket isn’t empty (most common cause)

AWS won’t let you delete an S3 bucket that still contains objects, versions, or delete markers—even if your IAM role has full S3 permissions. Your current delete code skips this critical step.

Update your DELETE operation code to first empty the bucket completely:

s3 = session.client("s3", region_name='us-east-2')

# Delete all versions and delete markers from the bucket
version_response = s3.list_object_versions(Bucket='mybucket123')

# Delete object versions
if 'Versions' in version_response:
    for version in version_response['Versions']:
        s3.delete_object(
            Bucket='mybucket123',
            Key=version['Key'],
            VersionId=version['VersionId']
        )

# Delete delete markers
if 'DeleteMarkers' in version_response:
    for marker in version_response['DeleteMarkers']:
        s3.delete_object(
            Bucket='mybucket123',
            Key=marker['Key'],
            VersionId=marker['VersionId']
        )

# Now delete the empty bucket
s3.delete_bucket(Bucket='mybucket123')

2. Local testing is using your personal AWS credentials (not the execution role)

When you run sam local start-lambda and cfn test, your local environment defaults to using credentials from your local AWS config (e.g., ~/.aws/credentials) instead of the CloudFormation execution role you defined in resource-role.yaml.

To fix this:

  • Either grant your local IAM user the necessary S3 permissions (s3:DeleteBucket, s3:DeleteObject, s3:ListBucketVersions)
  • Or run sam local with the --role-arn flag pointing to your execution role’s ARN to simulate the CloudFormation context:
    sam local start-lambda --role-arn arn:aws:iam::YOUR_ACCOUNT_ID:role/ExecutionRole
    

3. The bucket has a restrictive bucket policy

Check if your S3 bucket has its own bucket policy that might be denying the delete operation. Even if your IAM role allows the action, a bucket policy with a Deny statement will take precedence.

  • Go to the S3 console, navigate to your bucket, and check the Permissions > Bucket Policy tab.
  • Look for any statements that block s3:DeleteBucket or related actions, and adjust them if needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:37:48