I just deployed a lambda using serverless but I'm not allowed to access the s3 bucket I want to. Is there anything in this code that is obviously broken?
service: handler
frameworkVersion: '2'
provider:
name: aws
runtime: python3.8
lambdaHashingVersion: 20201221
iam:
role:
statements:
- Effect: 'Allow'
Action:
- 's3:GetObject'
- 's3:PutObject'
Resource: "arn:aws:s3:::my_bucket"
plugins:
- serverless-python-requirements
package:
exclude:
- node_modules/**
functions:
login:
handler: handler.login
events:
- httpApi:
path: /login
method: post
And here's the function trying to access s3
def check_s3(user):
s3 = boto3.client('s3')
obj = s3.get_object(Bucket="my_bucket", Key=user)
data = json.loads(obj['Body'].read())
return data
Error I'm getting:
[ERROR] ClientError: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied
Traceback (most recent call last):
File "/var/task/handler.py", line 11, in login
d = check_s3(username)
File "/var/task/handler.py", line 34, in check_s3
obj = s3.get_object(Bucket="my_bucket", Key=user)
File "/var/runtime/botocore/client.py", line 386, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/var/runtime/botocore/client.py", line 705, in _make_api_call
raise error_class(parsed_response, operation_name)
Your resource needs to be "arn:aws:s3:::my_bucket/*"
because you get an object, not the bucket itself. S3 Permissions
问题是我试图获取的文件不存在
TL;DR make sure your role can do s3:ListBucket
I want to share an answer for this because it was a pain for our team because we knew that the server had s3:GetObject
but kept getting the error above. Sometimes you will get this error if the object does not exist. Ie you get the following error:
ClientError: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied
Instead of a more meaningful error like a s3_client.exceptions.NoSuchKey
. The reason can be found in the boto3 docs :
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.