I am now trying to read CSV file(only column name) from S3 bucket using Lambda function. I have created an S3 trigger within Lambda. Here is the sample code;
import json
import boto3
import csv
s3_client = boto3.client('s3')
def lambda_handler(event, context):
# TODO implement
bucket = event['Records'][0]['s3']['bucket']['name']
csv_file = event['Records'][0]['s3']['object']['key']
response = s3_client.get_object(Bucket=bucket, Key=csv_file)
lines = response['Body'].read().decode('utf-8').split()
results = []
for row in csv.DictReader(lines):
results.append(row.name())
print(results)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
Whenever I try to upload a new file, i get this error;
[ERROR] ClientError: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 10, in lambda_handler
response = s3_client.get_object(Bucket=bucket, Key=csv_file)
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
I added a specific role and provided necessary permissions to my S3 bucket.
Snippet of my S3 bucket policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Principal": "*",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::my-bucket/*",
}
}
I have provided necessary permissions to my s3 bucket. But still getting this error:
Response
{
"errorMessage": "An error occurred (AccessDenied) when calling the GetObject operation: Access Denied",
"errorType": "ClientError",
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 19, in lambda_handler\n response = s3_client.get_object(Bucket=bucket, Key=csv_file)\n",
" File \"/var/runtime/botocore/client.py\", line 386, in _api_call\n return self._make_api_call(operation_name, kwargs)\n",
" File \"/var/runtime/botocore/client.py\", line 705, in _make_api_call\n raise error_class(parsed_response, operation_name)\n"
]
}
Can anyone tell me why am i getting this error?
S3 bucket policy. This is invalid bucket policy. Please double check what is your real bucket policy, and also what is your lambda execution role.