When I run GetObject from S3 on AWS Lambda, I get an error and I don't know what to do.

Asked 1 years ago, Updated 1 years ago, 197 views

When I run GetObject from S3 on AWS Lambda, I get an error and I don't know what to do.

Error Contents

{
  "errorMessage": "An error occurred (AccessDenied) when calling the GetObject operation: Access Denied",
  "errorType": "ClientError",
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      24,
      "lambda_handler",
      "rise e".
    ],
    [
      "/var/task/lambda_function.py",
      18,
      "lambda_handler",
      "response=s3.get_object(Bucket=bucket, Key=key)"
    ],
    [
      "/var/runtime/botocore/client.py",
      312,
      "_api_call",
      "return self._make_api_call(operation_name,kwargs)"
    ],
    [
      "/var/runtime/botocore/client.py",
      601,
      "_make_api_call",
      "raise error_class(parsed_response, operationn_name)"
    ]
  ]
}

Policy for S3

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

lambda function

import json
import urllib.parse
import boto3

print('Loading function')

s3 = boto3.client('s3')


deflambda_handler(event, context):
    # print("Received event:" + json.dumps(event,indent=2))"

    # Get the object from the event and show its content type
    bucket=event['Records'][0]['s3']['bucket']['name']
    key=urllib.parse.unquote_plus (event['Records'][0]['s3']['object']['key'], encoding='utf-8')
    try:
        response=s3.get_object(Bucket=bucket, Key=key)
        print("CONTENT TYPE:" + response ['ContentType'])
        return response ['ContentType']
    except Exception as:
        print(e)
        print('Error getting object{} from bucket{}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise

As I'm a beginner at aws, I can't judge whether the questions are appropriate or not.
Please let me know.

aws lambda amazon-s3

2022-09-30 18:00

1 Answers

I feel that the S3 bucket policy was basically a security control when making HTTP requests.
I think Lambda can select the IAM role to use for that function when registering a function, so please select the role that has S3 access.
If such a role does not exist, you must create it.
http://docs.aws.amazon.com/ja_jp/lambda/latest/dg/with-s3-example-create-iam-role.html


2022-09-30 18:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.