我们的用例是,我们将上传具有特定标签值的 S3 对象,并根据该特定标签值需要触发 lambda 函数,并且它应该将该具有特定标签值的对象移动到另一个存储桶。
标签值示例:
键 | 价值 |
---|---|
桶 | 干净 |
请分享实现此目的的 lambda 函数代码。
我尝试使用下面的Python代码,但没有任何反应:
import boto3
def 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'
}
1.检查 Lambda 函数是否具有对 S3 存储桶执行操作所需的权限,例如 s3:GetObjectTagging、s3:PutObject。 2.检查 CloudWatch Logs 以查看是否记录了任何错误或异常。