调用DeleteObject操作遇AccessDenied错误,求S3文件删除排查
Hey Bharathim, let's figure out why you're getting that AccessDenied error when trying to delete an object from S3, and get your code working properly.
1. First Fix: Incorrect Key Parameter in delete_object
Your code is passing the full S3 object URL as the Key parameter, which is wrong. The Key should be the relative path of the object inside the bucket, not the complete URL.
For example, instead of:
s3.delete_object(Bucket=settings.S3_BUCKET_BUCKET_NAME, Key='https://examplebucket123.s3.ap-south-1.amazonaws.com/regionfolder/031619-QA.jpg')
You should use:
s3.delete_object(Bucket=settings.S3_BUCKET_BUCKET_NAME, Key='regionfolder/031619-QA.jpg')
The Bucket parameter already specifies the bucket name, so the Key only needs the path to the object within that bucket.
2. Verify IAM Permissions
Even if you fix the Key, you'll still get AccessDenied if your AWS credentials (access key/secret) don't have permission to delete objects in the bucket.
Make sure the IAM user/role associated with your credentials has the s3:DeleteObject permission. Here's an example IAM policy that grants this access:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:DeleteObject", "Resource": "arn:aws:s3:::your-bucket-name/*" } ] }
Replace your-bucket-name with settings.S3_BUCKET_BUCKET_NAME to match your bucket.
3. Check Bucket Policy Restrictions
Sometimes the bucket itself has a policy that blocks delete operations. Go to your S3 bucket's Permissions > Bucket Policy in the AWS Console and make sure there are no Deny statements that affect s3:DeleteObject for your credentials.
4. Object-Level ACL Settings
If the specific object you're trying to delete has an ACL that doesn't grant delete permissions to your user/role, you'll also get AccessDenied. You can check the object's ACL in the S3 Console (go to the object > Permissions > Access control list) and ensure your user has the necessary delete rights.
Corrected Full Code Snippet
Here's your code with the Key fix applied:
def post(self, request): try: company_id = request.data.get('company_id') execute_function.get_connection_by_company(company_id) s3 = boto3.client('s3', aws_access_key_id=settings.S3_BUCKET_BUCKET_AccessKeyId, aws_secret_access_key=settings.S3_BUCKET_BUCKET_SecretAccessKey) # Use the relative object path as Key s3.delete_object(Bucket=settings.S3_BUCKET_BUCKET_NAME, Key='regionfolder/031619-QA.jpg') except Exception as err: http_err = traceback.format_exc() print(http_err) return HttpResponse(http_err, status=500) finally: execute_function().close_db_connection()
Start with fixing the Key parameter first, then verify permissions if the error persists. That should get you past the AccessDenied issue.
内容的提问来源于stack exchange,提问作者Bharathim

