-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
46 lines (38 loc) · 1.68 KB
/
lambda_function.py
File metadata and controls
46 lines (38 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import json
import urllib.parse
import boto3
import os
print('Loading function')
s3 = boto3.client('s3')
def lambda_handler(event, context):
for record in event['Records']:
# Skip if this event was generated by Lambda
if record.get('userIdentity', {}).get('principalId', '').endswith(':aws:lambda'):
print("Skipping Lambda-generated event to prevent recursion")
continue
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
try:
# Get the object
response = s3.get_object(Bucket=bucket, Key=key)
content = response['Body'].read().decode('utf-8')
# Split into lines and modify first line
lines = content.splitlines(keepends=True)
if len(lines) > 0:
print(f"First line of {key}: '{lines[0].strip()}'")
if (lines[0].strip() == 'abc'):
lines[0] = "def\n"
# Upload to different location to prevent recursion
s3.put_object(
Bucket='myawsbucket-lambda-output',
Key=key,
Body=''.join(lines),
Metadata=response.get('Metadata', {}),
ContentType=response.get('ContentType', 'text/plain')
)
except Exception as e:
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 e