I am trying to build a service where user will upload an image to first s3 bucket. Which will trigger a Lambda function and the function will use amazon rekognition to analyze the image and get the labels. Finally store the output into a second bucket.
After uploading the image, I see this error in CloudWatch log and no output in 2nd bucket. The code that I used for Lambda function and policies for Lambda role, error message is included bellow. I am doing all these using the aws root user. Tried policy simulator, it says with these 3 policies Lambda is allowed to access DetectLabels. Please give me suggestion…
============================================Lambda Code
import boto3
import json
def lambda_handler(event, context):
# Extract the bucket and object key from the S3 event
source_bucket = event[‘Records’][0][‘s3’][‘bucket’][‘name’]
source_key = event[‘Records’][0][‘s3’][‘object’][‘key’]
# Create an Amazon Rekognition client
rekognition_client = boto3.client('rekognition')
# Specify the source S3 object for Rekognition
image_source = {'S3Object': {'Bucket': source_bucket, 'Name': source_key}}
try:
# Detect labels in the image
response = rekognition_client.detect_labels(Image=image_source)
# Extract labels from the response
labels = [{'Name': label['Name'], 'Confidence': label['Confidence']} for label in response['Labels']]
# Create a new S3 bucket to store the analysis output
destination_bucket = 'bucket2-lambda-rekognition-100-ca-central1-26nov23'
destination_key = f'rekognition-analysis/{source_key.split("/")[-1]}'
# Save the analysis output as JSON to the destination S3 bucket
s3_client = boto3.client('s3')
s3_client.put_object(
Bucket=destination_bucket,
Key=destination_key,
Body=json.dumps(labels),
ContentType='application/json'
)
print(f"Image analysis completed. Analysis results saved to {destination_bucket}/{destination_key}")
return {
'statusCode': 200,
'body': 'Image analysis and result storage completed successfully.'
}
except Exception as e:
print(f"Error analyzing image: {e}")
return {
'statusCode': 500,
'body': 'Error analyzing image and storing results.'
}
===========================Policies
Policies attached to the IAM role that is attached to the Lambda function >>
AmazonRekognitionReadOnlyAccess
AmazonS3FullAccess
AWSLambdaBasicExecutionRole
===========================
Error message >>
"Error analyzing image: An error occurred (AccessDeniedException) when calling the DetectLabels operation:"
2
Answers
Found the reason why I was getting that error. The reason is simply its not available in Canada central region and i was using it.enter image description here
We have a very similiar use case example in the AWS Code Library which is implemented in different programming langauges. See this example:
Create a photo asset management application that lets users manage photos using labels
For the given IAM role (which the Lambda function uses) to use detect labels functionality, we set this permission:
Now when we run the app, the app can detect labels when an image is uploaded into an S3 bucket. If you read through one of the implementations, you will gain a much deeper understanding of this use case.