Error with connecting lambda function to S3 bucket. \"statusCode\": 500, \"body\": \"An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied\"

0

I am aware that this means I "don't have permission to list buckets" in my lambda function but I have double checked all my policies and permissions and it should work. Im just confused as to why. I know my lambda function code is written very inefficiently but I am just trying to figure out why I can't access files in my bucket. I am very new to AWS and just trying to get this to work.

Lambda Function:

import json
import pandas
import datetime
import boto3

#import cartopy

def lambda_handler(event, context):
    x = event['queryStringParameters']['x']
    y = event['queryStringParameters']['y']

    print(f" x:{x} , y:{y}")


    res_body = {}
    res_body['x'] = str(x)
    res_body['y'] = str(y)
    res_body['ans'] = add(x,y)

    http_res = {}
    http_res['statusCode'] = 200
    http_res['headers'] = {
        "Content-Type": "application/json",
        "Access-Control-Allow-Headers": "Content-Type",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET"
    }
    http_res['body'] = json.dumps(res_body)

    return http_res
def add(x,y):
    bucket_name = "aerocastwx.com"
    file_name = "/model_csv/delte.csv"
    print("Getting S3")
    # Create an S3 client
 

    try:
        aws_access_key_id = 'xx'
        aws_secret_access_key = 'xx'
        
        # Create an S3 client
        s3 = boto3.client(
            's3',
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key
        )
        #response = s3.get_object(Bucket=bucket_name, Key=file_name)
        # Example: List S3 buckets
        response = s3.list_buckets()
        
        # Print the bucket names
        #print("S3 Buckets:")
        #for bucket in response['Buckets']:
            #print(f"- {bucket['Name']}")

    except Exception as e:
        return {
            'statusCode': 500,
            'body': str(e)
        }
    return x+y+y

Here are images of the permissions for lambda function, s3 bucket, IAM user: Enter image description here Enter image description here Enter image description here

Kevin
질문됨 8달 전303회 조회
2개 답변
0

Hello.

Looking at the code, it seems to be using an access key when listing S3.
You can set an IAM role for Lambda, so there is no need to set an access key.
Another possible cause of the error is that the IAM user who issued the access key does not have permissions.
Please try deleting the access key from Lambda and setting access rights to S3 in the IAM role.

        aws_access_key_id = 'xx'
        aws_secret_access_key = 'xx'
        
        # Create an S3 client
        s3 = boto3.client(
            's3',
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key
        )
        #response = s3.get_object(Bucket=bucket_name, Key=file_name)
        # Example: List S3 buckets
        response = s3.list_buckets()
profile picture
전문가
답변함 8달 전
  • Hi. Yes I am aware about the IAM user. I tried the approach like you said without the access keys but then the lamda function stalls and times out on this line: response = s3.get_object(Bucket=bucket_name, Key=file_name)

0

Your code is performing a ListBuckets call, and your IAM permissions are allowing s3:ListBucket. You need s3:ListAllMyBuckets in order to call ListBuckets.

If you update your IAM policy to:

{
	"Version": "2012-10-17",
	"Statement": [
		{
			"Sid": "SamplePolicy",
			"Effect": "Allow",
			"Action": "s3:ListAllMyBuckets",
			"Resource": "*"
		}
	]
}

Then your code will work as intended.

Best practice of course is what is described by Riko, and to use a role in Lambda (which would need the same permissions I talk about here), and not to use static credentials the way you are.

AWS
전문가
답변함 8달 전
  • Hi I attached the following

    { "Version": "2012-10-17", "Statement": [ { "Sid": "SamplePolicy", "Effect": "Allow", "Action": "s3:", "Resource": "" } ] }

    to my IAM policy thats connected to lambda function..

    When I try to run the following lambda function it just times out.. The file path is correct. In my bucket I have a folder called model_csv and a file named delte.csv .

    bucket_name = "aerocastwx.com"
    file_name = "/model_csv/delte.csv"
    print("Getting S3")
    # Create an S3 client
    
    
    try:
        s3 = boto3.client('s3')
        # Create an S3 client
        #@s3 = boto3.client(
            #'s3',
            #aws_access_key_id=aws_access_key_id,
            #aws_secret_access_key=aws_secret_access_key
        #)
        response = s3.get_object(Bucket=bucket_name, Key=file_name)
    

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠