Skip to content

Instantly share code, notes, and snippets.

@amit-naudiyal
Created January 20, 2021 23:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amit-naudiyal/6ff770d83ebac8d31bc801f6ebe8ba34 to your computer and use it in GitHub Desktop.
Save amit-naudiyal/6ff770d83ebac8d31bc801f6ebe8ba34 to your computer and use it in GitHub Desktop.
lambda code
import urllib
import boto3
import ast
import json
print('Loading function')
def lambda_handler(event, context):
print 'Recieved following event'
print '--------------------------------------------------'
print event
print '--------------------------------------------------'
s3 = boto3.client('s3')
sns_message = ast.literal_eval(event['Records'][0]['Sns']['Message'])
print 'Defining source and target bucket....'
target_bucket = context.function_name
source_bucket = str(sns_message['Records'][0]['s3']['bucket']['name'])
print 'Defining key....'
key = str(urllib.unquote_plus(sns_message['Records'][0]['s3']['object']['key']).decode('utf8'))
print 'Defining copy source....'
copy_source = {'Bucket':source_bucket, 'Key':key}
print key
print source_bucket
sts_client = boto3.client('sts')
assumedRoleObject = sts_client.assume_role(
RoleArn="arn:aws:iam::114984850847:role/lambda-s3-upload-cross-account",
RoleSessionName="AssumeRoleSession1"
)
print 'role assumed...'
print 'getting credentials...'
credentials = assumedRoleObject['Credentials']
s3 = boto3.client(
's3',
aws_access_key_id = credentials['AccessKeyId'],
aws_secret_access_key = credentials['SecretAccessKey'],
aws_session_token = credentials['SessionToken'],
)
print 'Finally copying....'
s3.copy_object(ACL='bucket-owner-full-control', Bucket=target_bucket, Key=key, CopySource=copy_source)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment