-
Notifications
You must be signed in to change notification settings - Fork 12
/
lambda_function.py
75 lines (57 loc) · 2.38 KB
/
lambda_function.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
72
73
74
75
import base64
import uuid
import httplib
import urlparse
import json
import boto3
def send_response(request, response, status=None, reason=None):
""" Send our response to the pre-signed URL supplied by CloudFormation
If no ResponseURL is found in the request, there is no place to send a
response. This may be the case if the supplied event was for testing.
"""
if status is not None:
response['Status'] = status
if reason is not None:
response['Reason'] = reason
if 'ResponseURL' in request and request['ResponseURL']:
url = urlparse.urlparse(request['ResponseURL'])
body = json.dumps(response)
https = httplib.HTTPSConnection(url.hostname)
https.request('PUT', url.path+'?'+url.query, body)
return response
def lambda_handler(event, context):
response = {
'StackId': event['StackId'],
'RequestId': event['RequestId'],
'LogicalResourceId': event['LogicalResourceId'],
'Status': 'SUCCESS'
}
# PhysicalResourceId is meaningless here, but CloudFormation requires it
if 'PhysicalResourceId' in event:
response['PhysicalResourceId'] = event['PhysicalResourceId']
else:
response['PhysicalResourceId'] = str(uuid.uuid4())
# There is nothing to do for a delete request
if event['RequestType'] == 'Delete':
return send_response(event, response)
# Encrypt the value using AWS KMS and return the response
try:
for key in ['KeyId', 'PlainText']:
if key not in event['ResourceProperties'] or not event['ResourceProperties'][key]:
return send_response(
event, response, status='FAILED',
reason='The properties KeyId and PlainText must not be empty'
)
client = boto3.client('kms')
encrypted = client.encrypt(
KeyId=event['ResourceProperties']['KeyId'],
Plaintext=event['ResourceProperties']['PlainText']
)
response['Data'] = {
'CipherText': base64.b64encode(encrypted['CiphertextBlob'])
}
response['Reason'] = 'The value was successfully encrypted'
except Exception as E:
response['Status'] = 'FAILED'
response['Reason'] = 'Encryption Failed - See CloudWatch logs for the Lamba function backing the custom resource for details'
return send_response(event, response)