Lambda function cannot access S3 bucket, even after granting IAM role/policy

0

I have followed the instructions for creating an AWS Lambda function and have created an IAM user role for an AWS Lambda function to access an S3 bucket. I have allowed both the putObject and getObject actions for the role, and specified which bucket I wanted Lambda to access within the creation page for the policy. Additionally, I unchecked the "Block all public access" button while creating my S3 bucket. However, whenever I try using boto3:

s3 = boto3.client('s3')
bucket_name = 'example_bucketname'
object_key = 'data.json' 

 try:
        response = s3.get_object(Bucket=bucket_name, Key=object_key)
        cached_data = response['Body'].read().decode('utf-8')
        return json.loads(cached_data)
    except s3.exceptions.NoSuchKey:
        return None

I receive an error stating "An error occurred (AccessDenied) when calling the GetObject operation: Access Denied" when testing my lambda function. Am I forgetting anything?

Any help will be much appreciated. Thank you! (Additionally, I have already looked at the guide posted by AWS OFFICIAL and I have also watched the YouTube video created by Francisco on the AWS OFFICIAL YouTube channel).

3 Respostas
1
Resposta aceita

Something that will help you get more information is adding ListBucket permission to your function's IAM Role. I see you're trying to trap s3.exceptions.NoSuchKey but without ListBucket permission you'll never get this. Instead, if your object_key is wrong then you'll get "access denied".

Note that ListBucket applies to the bucket, not objects, so should be allowed for the "example_bucketname" resource, whereas GetObject & PutObject should be allowed for "example_bucketname/*".

If you're still having trouble please post your IAM policy here.

ESPECIALISTA
respondido há 2 meses
profile picture
ESPECIALISTA
avaliado há 2 meses
1

The IAM Policy Simulator can be utilized to verify that your service roles possess the required permissions to execute the desired action.

IAM Policy Simulator

If the simulator encounters a failure when applying the service role to the resources, it indicates that your policy is improperly configured and requires correction.

profile picture
ESPECIALISTA
respondido há 2 meses
0

Hello.

Are the S3 bucket name and object key correct?
Did you set the IAM policy for the correct IAM role?
You can check the Lambda IAM role as shown in the image below.
a

Also, since you are accessing with IAM, there is no need to uncheck "Block all public access".

profile picture
ESPECIALISTA
respondido há 2 meses

Você não está conectado. Fazer login para postar uma resposta.

Uma boa resposta responde claramente à pergunta, dá feedback construtivo e incentiva o crescimento profissional de quem perguntou.

Diretrizes para responder a perguntas