Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. import re
  2. import boto3
  3.  
  4. def is_valid_host(host):
  5. if len(host) > 255:
  6. return False
  7. if host[-1] == ".":
  8. host = host[:-1]
  9. allowed = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
  10. return all(allowed.match(x) for x in host.split("."))
  11.  
  12. def is_valid_ip(ip):
  13. return re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)
  14.  
  15. def lambda_handler(event, context):
  16. host = event["host"]
  17. cname = host[:host.find(".")]
  18. hosted_zone = host[host.find(".")+1:]
  19. new_ip = event["ip"]
  20. print "Processing request to update %s with ip %s" % (host, new_ip)
  21. route53 = boto3.client('route53')
  22. try:
  23. print ("Validating inputs... "),
  24. if not (is_valid_host(host) and is_valid_ip(new_ip)):
  25. raise
  26. print ("Success")
  27. print ("Retrieving hosted zone..."),
  28. response = route53.list_hosted_zones_by_name(
  29. DNSName=hosted_zone,
  30. MaxItems='1'
  31. )
  32. r53hosted_zone = route53.get_hosted_zone(
  33. Id=response["HostedZones"][0]["Id"]
  34. )
  35. print ("Success")
  36. print ("Checking against existing IP..."),
  37. r53resource_record_set = route53.list_resource_record_sets(
  38. HostedZoneId = r53hosted_zone["HostedZone"]["Id"],
  39. StartRecordName = host,
  40. MaxItems = "1"
  41. )
  42. retMsg = ""
  43. if r53resource_record_set["ResourceRecordSets"][0]["ResourceRecords"][0]["Value"]==new_ip:
  44. print ("IP hasn't changed. Exiting.")
  45. return "nochg %s" % new_ip
  46. print("Success")
  47. print ("Updating route53 record for %s..." % (host)),
  48. dns_changes = {
  49. 'Changes': [
  50. {
  51. 'Action': 'UPSERT',
  52. 'ResourceRecordSet': {
  53. 'Name': host ,
  54. 'Type': 'A',
  55. 'ResourceRecords': [
  56. {
  57. 'Value': new_ip
  58. }
  59. ],
  60. 'TTL': 300
  61. }
  62. }
  63. ]
  64. }
  65. response = route53.change_resource_record_sets(
  66. HostedZoneId=r53hosted_zone["HostedZone"]["Id"],
  67. ChangeBatch=dns_changes
  68. )
  69. print("Success")
  70. return "good %s" % (new_ip)
  71. except:
  72. print ("Failed")
  73. return "dnserr"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement