Skip to content

Instantly share code, notes, and snippets.

@DanielSnipes
Created December 11, 2017 14:55
Show Gist options
  • Save DanielSnipes/04cb1414123b220a5ff7fe8b8a020d80 to your computer and use it in GitHub Desktop.
Save DanielSnipes/04cb1414123b220a5ff7fe8b8a020d80 to your computer and use it in GitHub Desktop.
AWS Lambda Random Letter Add
import json
import urllib.parse
import boto3
#need these to return random string
import random
import string
print('Loading function')
s3 = boto3.client('s3')
def lambda_handler(event, context):
# Get the object from the event and show its content type
bucket = event['Records'][0]['s3']['bucket']['name']
print("Bucket name: ", bucket)
object_name = event['Records'][0]['s3']['object']['key']
print("Object name: ", object_name)
key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
print("Key: ", key)
random_letter = random.choice(string.ascii_letters) + "_"
new_key = random_letter + key
print("Proposed new name: ", new_key)
try:
print("Using waiter to wait for object to persist thru s3 service…")
waiter = s3.get_waiter('object_exists')
waiter.wait(Bucket=bucket, Key=key)
response = s3.get_object(Bucket=bucket, Key=key)
s3.copy_object(Bucket=bucket, CopySource= "{}/{}".format(bucket, key), Key=new_key)
s3.delete_object(Bucket=bucket, Key=key)
print("Old name: {}".format(key))
print("New name: {}".format(new_key))
return response['ContentType']
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment