I have a python function that I am running through a Lambda. The function runs properly when uploading an object to S3, if the object’s name does not contain a space. For example if I upload an object called “example.txt” the object is tagged properly. However, if I upload an object called “example 2.txt” the function errors out with a permission denied error. Below is the python script I am running.
import json
import logging
import boto3
from botocore.exceptions import ClientError
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
# Create an S3 client
s3 = boto3.client('s3')
def lambda_handler(event, context):
# Log the event received
logger.info(f"Received event: {json.dumps(event)}")
try:
# Iterate through each record in the event
for record in event["Records"]:
s3_bucket = record["s3"]["bucket"]["name"]
s3_key = record["s3"]["object"]["key"]
# Log bucket and key information
logger.info(f"Processing object {s3_key} in bucket {s3_bucket}")
# Define the tag set
tags = {
"TagSet": [
{"Key": "SomeKey", "Value": "SomeValue"}
]
}
# Log the tags being applied
logger.info(f"Applying tags to object: {tags}")
try:
# Add tags to the object
response = s3.put_object_tagging(
Bucket=s3_bucket,
Key=s3_key,
Tagging=tags
)
# Log the request ID from the response metadata
request_id = response.get('ResponseMetadata', {}).get('RequestId', 'N/A')
logger.info(f"Successfully tagged object {s3_key} in bucket {s3_bucket} with tags: {tags}. S3 request ID: {request_id}")
except ClientError as e:
# Log any exceptions from the put_object_tagging call
logger.error(f"Error tagging object {s3_key} in bucket {s3_bucket}: {e.response['Error']['Message']}")
if e.response["Error"]["Code"] == "AccessDenied":
logger.error("Access Denied. Check if the Lambda function's role has the necessary permissions.")
# Optionally raise the exception if you want to stop processing further records
raise
# Return a success response
return {
"statusCode": 200,
"body": json.dumps("S3 object tagged!")
}
except Exception as e:
# Log any exceptions
logger.error(f"Error processing event: {str(e)}")
# Raise the exception to allow Lambda to handle it
raise
I have verified my IAM role permissions and attempted to add an encoding library to the code, I have also attempted wrapping the s3_key in quotes.
Jeffrey Demuth is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.