Quantcast
Channel: Active questions tagged aws-lambda - Stack Overflow
Viewing all articles
Browse latest Browse all 3995

Trigger Lambda function when s3 object with specific tag value is uploaded

$
0
0

Our use case is that, we will be uploading S3 objects with specific tag values and based on that specific tag value lambda function need to be triggered and it should move that object with specific tag value to another bucket.

Example of tag value:

keyvalue
bucketavclean

Kindly share the lambda function code to achieve this.

I tried with below python code, but nothing happens:

import boto3def lambda_handler(event, context):    try:        # Get the bucket and object information from the S3 event        bucket_name = event['Records'][0]['s3']['bucket']['name']        object_key = event['Records'][0]['s3']['object']['key']        # Retrieve the tag value for a specific tag key        tag_key = 'your-tag-key'        desired_tag_value = 'desired-tag-value'        s3_client = boto3.client('s3')        # Get the tags associated with the object        response = s3_client.get_object_tagging(            Bucket=bucket_name,            Key=object_key        )        # Check if the desired tag key exists and has the desired value        for tag in response['TagSet']:            if tag['Key'] == tag_key and tag['Value'] == desired_tag_value:                # Copy the object to the destination bucket                destination_bucket = 'destination-bucket-name'                destination_object_key = object_key  # You can optionally specify a new key for the destination object                s3_client.copy_object(                    Bucket=destination_bucket,                    Key=destination_object_key,                    CopySource={'Bucket': bucket_name, 'Key': object_key}                )                # Delete the object from the source bucket                s3_client.delete_object(                    Bucket=bucket_name,                    Key=object_key                )                print(f"Object '{object_key}' with tag value '{desired_tag_value}' moved from '{bucket_name}' to '{destination_bucket}'")                return {'statusCode': 200,'body': 'Object moved successfully'                }        # If the desired tag key or value is not found        print(f"Object '{object_key}' does not have the desired tag key-value pair.")        return {'statusCode': 400,'body': 'Desired tag key-value pair not found'        }    except KeyError as e:        print(f"Error: Missing key in event data - {e}")        return {'statusCode': 400,'body': 'Error: Missing key in event data'        }    except Exception as e:        print(f"Error moving object: {e}")        return {'statusCode': 500,'body': 'Error moving object'        }

Viewing all articles
Browse latest Browse all 3995

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>