get data from s3 Bucket [closed]

Tags: , , , ,



def lambda_handler(event, context):
    if event:
        # TODO implement
        params=event.get('city')

        print(params)
        s3 = boto3.client('s3')
        data = s3.get_object(Bucket='clg-data' ,Key='citiescsv.csv')

        file = data['body'].read().decode('utf-8')
        print(file)

This is my code

    {"errorMessage": "An error occurred (AccessDenied) when calling the GetObject operation: Access Denied", "errorType": "ClientError",  "stackTrace": [
    "  File "/var/task/lambda_function.py", line 15, in lambda_handlern    data = s3.get_object(Bucket='clg-data',Key='citiescsv.csv')n",
    "  File "/var/runtime/botocore/client.py", line 357, in _api_calln    return self._make_api_call(operation_name, kwargs)n",
    "  File "/var/runtime/botocore/client.py", line 676, in _make_api_calln    raise error_class(parsed_response, operation_name)n" ]}

I got this error while getting the data from the bucket.

Answer

The error message writes “GetObject operation: Access Denied” which most likely means that your lambda execution role does not have S3 read permissions. You can rectify this by adding the following inline policy to the lambda’s role:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::clg-data/*"
        }
    ]
}

Other reasons are also possible, e.g. lambda needs KMS permissions as bucket is encrypted or bucket is not in your account.



Source: stackoverflow