-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathhandler2.py
71 lines (59 loc) · 2.01 KB
/
handler2.py
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import os
import boto3
from aws_error_utils import errors
ROLE_ARN = os.environ['ROLE_ARN']
BUCKET_NAME = os.environ['BUCKET_NAME']
TABLE_NAME = os.environ['TABLE_NAME']
USE_SOURCE_IDENTITY = os.environ.get('USE_SOURCE_IDENTITY', '').lower() in ['1', 'true']
KEY = 'Function2'
def handler(event, context):
session = boto3.Session()
sts = session.client('sts')
lambda_role_arn = sts.get_caller_identity()['Arn']
if USE_SOURCE_IDENTITY:
response = sts.assume_role(
RoleArn=ROLE_ARN,
RoleSessionName=os.environ['AWS_LAMBDA_FUNCTION_NAME'],
SourceIdentity=os.environ['AWS_LAMBDA_FUNCTION_NAME'],
)
else:
response = sts.assume_role(
RoleArn=ROLE_ARN,
RoleSessionName=os.environ['AWS_LAMBDA_FUNCTION_NAME'],
)
credentials = response['Credentials']
assumed_role_session = boto3.Session(
aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken']
)
assumed_role_arn = assumed_role_session.client('sts').get_caller_identity()['Arn']
s3 = assumed_role_session.client('s3')
try:
response = s3.get_object(
Bucket=BUCKET_NAME,
Key=KEY,
)
s3_result = response['Body'].read()
except errors.AccessDenied:
s3_result = "Access denied!"
except Exception as e:
s3_result = str(e)
dynamodb = assumed_role_session.resource('dynamodb')
table = dynamodb.Table(TABLE_NAME)
try:
response = table.get_item(
Key={'pk': KEY},
)
ddb_result = response['Item']
except errors.AccessDeniedException:
ddb_result = "Access denied!"
except Exception as e:
ddb_result = str(e)
return {
'lambda_role_arn': lambda_role_arn,
'assumed_role_arn': assumed_role_arn,
'use_source_identity': USE_SOURCE_IDENTITY,
's3': s3_result,
'ddb': ddb_result,
}