Advertisement
Guest User

dsfdsf

a guest
Oct 22nd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.68 KB | None | 0 0
  1. import json
  2. import boto3
  3. import uuid
  4. from botocore.vendored import requests
  5.  
  6.  
  7. def lambda_handler(event, context):
  8. print ("Rec event: ")
  9. print (event)
  10. resource_type = event['ResourceType']
  11. request_type = event['RequestType']
  12. resource_properties = event['ResourceProperties']
  13.  
  14. hosted_zone_id = resource_properties['HostedZoneId']
  15. physical_resource_id = event.get('PhysicalResourceId', unicode(uuid.uuid4()))
  16. try:
  17. if resource_type == "Custom::AmazonSesVerificationRecords99":
  18. if request_type == 'Create':
  19. verify_ses(hosted_zone_id=hosted_zone_id, action='UPSERT')
  20. elif request_type == 'Delete':
  21. verify_ses(hosted_zone_id=hosted_zone_id, action='DELETE')
  22. elif request_type == 'Update':
  23. old_hosted_zone_id = event['OldResourceProperties']['HostedZoneId']
  24. verify_ses(hosted_zone_id=old_hosted_zone_id, action='DELETE')
  25. verify_ses(hosted_zone_id=hosted_zone_id, action='UPSERT')
  26. else:
  27. print ('Request type is {request_type}, doing nothing.'.format(request_type=request_type) )
  28. response_data = {}
  29. else:
  30. raise ValueError("Unexpected resource_type: {resource_type}".format(resource_type=resource_type))
  31. except Exception:
  32. send(
  33. event,
  34. context,
  35. responseStatus="FAILED" if request_type != 'Delete' else "SUCCESS",
  36. responseData=None,
  37. physicalResourceId=physical_resource_id,
  38. )
  39. raise
  40. else:
  41. send(
  42. event,
  43. context,
  44. responseStatus="SUCCESS",
  45. responseData=response_data,
  46. physicalResourceId=physical_resource_id,
  47. )
  48.  
  49. def verify_ses(hosted_zone_id, action):
  50. ses = boto3.client('ses')
  51. print ("Retrieving Hosted Zone name")
  52. hosted_zone_name = _get_hosted_zone_name(hosted_zone_id=hosted_zone_id)
  53. print ('Hosted zone name: {hosted_zone_name}'.format(hosted_zone_name=hosted_zone_name))
  54. domain = hosted_zone_name.rstrip('.')
  55. verification_token = ses.verify_domain_identity(
  56. Domain=domain
  57. )['VerificationToken']
  58. dkim_tokens = ses.verify_domain_dkim(
  59. Domain=domain
  60. )['DkimTokens']
  61. print ('Changing resource record sets')
  62. changes = [
  63. {
  64. 'Action': action,
  65. 'ResourceRecordSet': {
  66. 'Name': "_amazonses.{hosted_zone_name}".format(hosted_zone_name=hosted_zone_name),
  67. 'Type': 'TXT',
  68. 'TTL': 1800,
  69. 'ResourceRecords': [
  70. {
  71. 'Value': '"{verification_token}"'.format(verification_token=verification_token)
  72. }
  73. ]
  74. }
  75. }
  76. ]
  77. for dkim_token in dkim_tokens:
  78. change = {
  79. 'Action': action,
  80. 'ResourceRecordSet': {
  81. 'Name': "{dkim_token}._domainkey.{hosted_zone_name}".format(
  82. dkim_token=dkim_token,
  83. hosted_zone_name=hosted_zone_name
  84. ),
  85. 'Type': 'CNAME',
  86. 'TTL': 1800,
  87. 'ResourceRecords': [
  88. {
  89. 'Value': "{dkim_token}.dkim.dev.cloudtpsoftware.com".format(dkim_token=dkim_token)
  90. }
  91. ]
  92. }
  93. }
  94. changes.append(change)
  95. boto3.client('route53').change_resource_record_sets(
  96. ChangeBatch={
  97. 'Changes': changes
  98. },
  99. HostedZoneId=hosted_zone_id
  100. )
  101.  
  102. def _get_hosted_zone_name(hosted_zone_id):
  103. route53 = boto3.client('route53')
  104. route53_resp = route53.get_hosted_zone(
  105. Id=hosted_zone_id
  106. )
  107. return route53_resp['HostedZone']['Name']
  108.  
  109. def send(event, context, responseStatus, responseData, physicalResourceId):
  110. responseUrl = event['ResponseURL']
  111. print (responseUrl)
  112. responseBody = {}
  113. responseBody['Status'] = responseStatus
  114. responseBody['Reason'] = 'details in CloudWatch: ' + context.log_stream_name
  115. responseBody['PhysicalResourceId'] = physicalResourceId
  116. responseBody['StackId'] = event['StackId']
  117. responseBody['RequestId'] = event['RequestId']
  118. responseBody['LogicalResourceId'] = event['LogicalResourceId']
  119. responseBody['Data'] = responseData
  120. json_responseBody = json.dumps(responseBody)
  121. print ("Response body:\n" + json_responseBody)
  122. headers = {
  123. 'content-type': '',
  124. 'content-length': str(len(json_responseBody))
  125. }
  126. try:
  127. response = requests.put(responseUrl,
  128. data=json_responseBody,
  129. headers=headers)
  130. print ("Status code: " + response.reason)
  131. except Exception as e:
  132. print ("send(..)failed" + str(e))
  133.  
  134. def verify_domain_dkim(self, domain):
  135. """
  136. Returns a set of DNS records, or tokens, that must be published in the
  137. domain name's DNS to complete the DKIM verification process. These
  138. tokens are DNS ``CNAME`` records that point to DKIM public keys hosted
  139. by Amazon SES. To complete the DKIM verification process, these tokens
  140. must be published in the domain's DNS. The tokens must remain
  141. published in order for Easy DKIM signing to function correctly.
  142.  
  143. After the tokens are added to the domain's DNS, Amazon SES will be able
  144. to DKIM-sign email originating from that domain. To enable or disable
  145. Easy DKIM signing for a domain, use the ``SetIdentityDkimEnabled``
  146. action. For more information about Easy DKIM, go to the `Amazon SES
  147. Developer Guide
  148. <http://docs.amazonwebservices.com/ses/latest/DeveloperGuide>`_.
  149.  
  150. :type domain: string
  151. :param domain: The domain name.
  152.  
  153. """
  154. return self._make_request('VerifyDomainDkim', {
  155. 'Domain': domain,
  156. })
  157.  
  158. def verify_email_address(self, email_address):
  159. """Verifies an email address. This action causes a confirmation email
  160. message to be sent to the specified address.
  161.  
  162. :type email_adddress: string
  163. :param email_address: The email address to be verified.
  164.  
  165. :rtype: dict
  166. :returns: A VerifyEmailAddressResponse structure. Note that keys must
  167. be unicode strings.
  168. """
  169. return self._make_request('VerifyEmailAddress', {
  170. 'EmailAddress': email_address,
  171. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement