This repository has been archived by the owner on Apr 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathunion_python3.py
1702 lines (1500 loc) · 68.2 KB
/
union_python3.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
DDNS Lambda Python3 Script
This script will perform the following functions.
if no CNAME or ZONE tags is set on the ec2 instance, and not using a custom dhcp option set:
1. Script will do nothing
if no CNAME or ZONE tags are set, but are using a custom dhcp option set with
a hosted zone created, which matches the domain name.
1. An 'A' record is created to the IP
2. A 'PTR" record is create to the DNS name
if a CNAME tag is set.
1. Creates a CNAME to the DNS name
2. Creates a PTR record to the CNAME
if a ZONE tag is set.
1. Creates an 'A' record to the IP
2. Creates a 'PTR" record to the DNS name
"""
import json
import sys
import datetime
import random
import logging
import re
import uuid
import time
import inspect
import boto3
from botocore.exceptions import ClientError
# Setting Global Variables
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)
ACCOUNT = None
REGION = None
SNS_CLIENT = None
print('Loading function ' + datetime.datetime.now().time().isoformat())
def lineno(): # pragma: no cover
"""
Returns the current line number in our script
:return:
"""
return str(' - line number: ' + str(inspect.currentframe().f_back.f_lineno))
def get_sns_client():
"""
Get sns client
:return:
"""
try:
return boto3.client('sns')
except ClientError as err:
print("Unexpected error: %s" % err)
def get_route53_client():
"""
Get route53 client
:return:
"""
try:
return boto3.client('route53')
except ClientError as err:
print("Unexpected error: %s" % err)
def get_ec2_client():
"""
Get ec2 client
:return:
"""
try:
return boto3.client('ec2')
except ClientError as err:
print("Unexpected error: %s" % err)
def get_dynamodb_client():
"""
Get dynamodb client
:return:
"""
try:
return boto3.client('dynamodb')
except ClientError as err:
print("Unexpected error: %s" % err)
def lambda_handler(
event,
context,
dynamodb_client=get_dynamodb_client(),
compute=get_ec2_client(),
route53=get_route53_client(),
sns_client=get_sns_client()
):
"""
Check to see whether a DynamoDB table already exists. If not, create it.
This table is used to keep a record of instances that have been created
along with their attributes. This is necessary because when you terminate an instance
its attributes are no longer available, so they have to be fetched from the table.
:param event:
:param context:
:param dynamodb_client:
:param compute:
:param route53:
:param sns_client:
:return:
"""
LOGGER.info("event: %s", str(event) + lineno())
LOGGER.info("context: %s", str(context) + lineno())
SNS_CLIENT = sns_client
caller_response = []
# Checking to make sure there is a dynamodb table named DDNS or we will create it
tables = list_tables(dynamodb_client)
LOGGER.info("tables: %s", str(tables))
if 'DDNS' in tables['TableNames']:
LOGGER.info('DynamoDB table already exists')
else:
create_table(dynamodb_client, 'DDNS')
# Set variables
# Get the state from the Event stream
state = event['detail']['state']
LOGGER.debug("instance state: %s", str(state) + lineno())
# Get the instance id, region, and tag collection
instance_id = event['detail']['instance-id']
LOGGER.debug("instance id: %s", str(instance_id) + lineno())
ACCOUNT = event['account']
region = event['region']
REGION = region
LOGGER.debug("region: %s", str(region) + lineno())
# Only doing something if the state is running
if state == 'running':
LOGGER.debug("sleeping for 60 seconds %s", lineno())
if "pytest" in sys.modules:
# called from within a test run
time.sleep(1)
else:
# called "normally"
time.sleep(60)
# Get instance information
instance = get_instances(compute, instance_id)
# Remove response metadata from the response
if 'ResponseMetadata' in instance:
instance.pop('ResponseMetadata')
# Remove null values from the response. You cannot save a dict/JSON
# document in DynamoDB if it contains null values
LOGGER.debug("instance: %s", str(instance) + lineno())
instance = remove_empty_from_dict(instance)
instance_dump = json.dumps(instance, default=json_serial)
instance_attributes = json.loads(instance_dump)
LOGGER.debug("instance_attributes: %s", str(instance_attributes) + lineno())
LOGGER.debug("trying to put instance information in "
"dynamo table %s", str(instance_attributes) + lineno())
put_item_in_dynamodb_table(dynamodb_client, 'DDNS', instance_id, instance_attributes)
LOGGER.debug("done putting item in dynamo table %s", lineno())
else:
# Fetch item from DynamoDB
LOGGER.debug("Fetching instance information from dynamodb %s", lineno())
instance = get_item_from_dynamodb_table(dynamodb_client, 'DDNS', instance_id)
LOGGER.debug("instance: %s", str(instance) + lineno())
# Get the instance tags and reorder them because we want a zone created before CNAME
try:
tags = instance['Reservations'][0]['Instances'][0]['Tags']
except:
tags = []
LOGGER.debug("tags are: %s", str(tags) + lineno())
tag_type = determine_tag_type(tags)
if tag_type == 'invalid':
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION,
"Must have either CNAME or ZONE in tags, can not have both tags" + lineno())
exit(-1)
LOGGER.debug("Get instance attributes %s", lineno())
LOGGER.debug("instance: %s", str(instance) + lineno())
LOGGER.debug("type: %s", str(type(instance)) + lineno())
if instance and 'Reservations' in instance:
LOGGER.debug("reservations: %s", str(instance['Reservations']) + lineno())
LOGGER.debug("reservations: %s", str(instance['Reservations'][0]) + lineno())
LOGGER.debug("reservations: %s", str(instance['Reservations'][0]['Instances']) + lineno())
LOGGER.debug("reservations:"
" %s", str(instance['Reservations'][0]['Instances'][0]) + lineno())
private_ip = instance['Reservations'][0]['Instances'][0]['PrivateIpAddress']
private_dns_name = instance['Reservations'][0]['Instances'][0]['PrivateDnsName']
private_host_name = private_dns_name.split('.')[0]
LOGGER.debug("private ip: %s", str(private_ip) + lineno())
LOGGER.debug("private_dns_name: %s", str(private_dns_name) + lineno())
LOGGER.debug("private_host_name: %s", str(private_host_name) + lineno())
public_ip = None
public_dns_name = None
if 'PublicIpAddress' in instance['Reservations'][0]['Instances'][0]:
LOGGER.debug('instance has public ip address key')
try:
LOGGER.debug("instance: %s", str(instance) + lineno())
if 'Reservations' in instance:
LOGGER.debug("reservations: %s", str(instance['Reservations'][0]))
if 'Instances' in instance['Reservations'][0]:
LOGGER.debug("instances: %s", str(instance['Reservations'][0]['Instances'][0]))
public_ip = instance['Reservations'][0]['Instances'][0]['PublicIpAddress']
LOGGER.debug("public_ip: %s", str(public_ip) + lineno())
if public_ip and 'PublicDnsName' not in instance['Reservations'][0]['Instances'][0]:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION,
"Could not find PublicDnsName for public instance,"
" check that vpc has dns hostnames enabled:" + lineno())
exit()
else:
public_dns_name = instance['Reservations'][0]['Instances'][0]['PublicDnsName']
LOGGER.debug("public_dns_name: %s", str(public_dns_name) + lineno())
public_host_name = public_dns_name.split('.')[0]
LOGGER.debug("public_host_name: %s", str(public_host_name))
except BaseException as err:
LOGGER.info("Instance has no public IP or host name %s", str(err))
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" + str(err) + lineno())
# Get the subnet mask of the instance
subnet_id = instance['Reservations'][0]['Instances'][0]['SubnetId']
LOGGER.debug("subnet_id: %s", str(subnet_id) + lineno())
cidr_block = get_subnet_cidr_block(compute, subnet_id)
LOGGER.debug("cidr_block: %s", str(cidr_block) + lineno())
subnet_mask = int(cidr_block.split('/')[-1])
LOGGER.debug("subnet_mask: %s", str(subnet_mask) + lineno())
reversed_ip_address = reverse_list(private_ip)
reversed_domain_prefix = get_reversed_domain_prefix(subnet_mask, private_ip)
reversed_domain_prefix = reverse_list(reversed_domain_prefix)
LOGGER.debug("reversed_domain_prefix is: %s", str(reversed_domain_prefix) + lineno())
# Set the reverse lookup zone
reversed_lookup_zone = reversed_domain_prefix + 'in-addr.arpa.'
LOGGER.info("The reverse lookup zone for this instance is: %s", str(reversed_lookup_zone))
# Get VPC id
vpc_id = instance['Reservations'][0]['Instances'][0]['VpcId']
# Are DNS Hostnames and DNS Support enabled?
if is_dns_hostnames_enabled(compute, vpc_id):
LOGGER.debug("DNS hostnames enabled for %s", str(vpc_id) + lineno())
else:
LOGGER.debug("DNS hostnames disabled for %s. You have to enable DNS hostnames \
to use Route 53 private hosted zones. %s", vpc_id, lineno())
if is_dns_support_enabled(compute, vpc_id):
LOGGER.debug("DNS support enabled for %s", str(vpc_id) + lineno())
else:
LOGGER.debug("DNS support disabled for %s. You have to enabled DNS support \
to use Route 53 private hosted zones. %s", str(vpc_id), lineno())
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, 'DNS support disabled for '+
str(vpc_id)+'. You have to enabled DNS support \
to use Route 53 private hosted zones. ' + lineno())
exit()
# Create the public and private hosted zone collections.
# These are collections of zones in Route 53.
hosted_zones = list_hosted_zones(route53)
LOGGER.debug("hosted_zones: %s", str(hosted_zones) + lineno())
private_hosted_zones = get_private_hosted_zones(hosted_zones)
LOGGER.debug("private_hosted_zones: %s", str(list(private_hosted_zones)) + lineno())
private_hosted_zone_collection = get_private_hosted_zone_collection(private_hosted_zones)
LOGGER.debug("private_hosted_zone_collection: %s",
str(list(private_hosted_zone_collection)) + lineno())
public_hosted_zones = get_public_hosted_zones(hosted_zones)
LOGGER.debug("public_hosted_zones: %s", str(list(public_hosted_zones)) + lineno())
public_hosted_zones_collection = get_public_hosted_zone_collection(public_hosted_zones)
LOGGER.debug("public_hosted_zones_collection:"
" %s", str(list(public_hosted_zones_collection)) + lineno())
# Check to see whether a reverse lookup zone for the instance
# already exists. If it does, check to see whether
# the reverse lookup zone is associated with the instance's
# VPC. If it isn't create the association. You don't
# need to do this when you create the reverse lookup
# zone because the association is done automatically.
LOGGER.info("reversed_lookup_zone: %s", str(reversed_lookup_zone) + lineno())
reverse_zone = None
for record in hosted_zones['HostedZones']:
LOGGER.debug("record name: %s", str(record['Name']) + lineno())
if record['Name'] == reversed_lookup_zone:
reverse_zone = record['Name']
break
if reverse_zone:
LOGGER.debug("Reverse lookup zone found: %s", str(reversed_lookup_zone) + lineno())
reverse_lookup_zone_id = get_zone_id(route53, reversed_lookup_zone)
LOGGER.debug("reverse_lookup_zone_id: %s", str(reverse_lookup_zone_id) + lineno())
reverse_hosted_zone_properties = get_hosted_zone_properties(route53, reverse_lookup_zone_id)
LOGGER.debug("reverse_hosted_zone_properties:"
" %s", str(reverse_hosted_zone_properties) + lineno())
if vpc_id in map(lambda x: x['VPCId'], reverse_hosted_zone_properties['VPCs']):
LOGGER.info("Reverse lookup zone %s is associated \
with VPC %s %s", reverse_lookup_zone_id, vpc_id, lineno())
else:
LOGGER.info("Associating zone %s with VPC %s", reverse_lookup_zone_id, vpc_id)
try:
associate_zone(route53, reverse_lookup_zone_id, region, vpc_id)
except BaseException as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
LOGGER.debug("%s", str(err)+lineno())
else:
LOGGER.info("No matching reverse lookup zone, so we will create one %s", lineno())
# create private hosted zone for reverse lookups
if state == 'running':
create_reverse_lookup_zone(route53, instance, reversed_domain_prefix, region)
reverse_lookup_zone_id = get_zone_id(route53, reversed_lookup_zone)
# Wait a random amount of time. This is a poor-mans back-off
# if a lot of instances are launched all at once.
time.sleep(random.random())
if tag_type == 'cname':
# We must have a cname because we want reverse dns to point to the A record
cname = get_cname_from_tags(tags)
cname_prefix = cname.split('.')[0]
if not cname:
publish_to_sns(
SNS_CLIENT,
ACCOUNT, REGION,
"Must have a CNAME tag for lambda to work. "
"Please add CNAME to instance tags" + lineno()
)
LOGGER.debug("iterating through tags %s", lineno())
# Loop through the instance's tags, looking for the zone and
# cname tags. If either of these tags exist, check
# to make sure that the name is valid. If it is and
# if there's a matching zone in DNS, create A and PTR records.
for tag in tags:
LOGGER.debug("#### tag: %s", str(tag) + lineno())
if 'ZONE' in tag.get('Key', {}).lstrip().upper():
# Simple check to make sure the hostname is valid
if is_valid_hostname(tag.get('Value')):
LOGGER.debug("hostname is valid %s", lineno())
LOGGER.debug("checking if value in private:"
" %s", str(list(private_hosted_zone_collection)) + lineno())
LOGGER.debug("checking if value in public:"
" %s", str(list(public_hosted_zones_collection)) + lineno())
if tag.get('Value').lstrip().lower() in private_hosted_zone_collection:
LOGGER.debug("Private zone found: %s", str(tag.get('Value')) + lineno())
private_hosted_zone_name = tag.get('Value').lstrip().lower()
LOGGER.debug("private_zone_name: %s", str(private_hosted_zone_name) + lineno())
private_hosted_zone_id = get_zone_id(route53, private_hosted_zone_name)
LOGGER.debug("private_hosted_zone_id:"
" %s", str(private_hosted_zone_id) + lineno())
private_hosted_zone_properties = \
get_hosted_zone_properties(route53, private_hosted_zone_id)
LOGGER.debug("private_hosted_zone_properties:"
" %s", str(private_hosted_zone_properties) + lineno())
if state == 'running':
found_vpc_id = False
if 'VPCs' in private_hosted_zone_properties:
for vpc in private_hosted_zone_properties['VPCs']:
if vpc['VPCId'] == vpc_id:
found_vpc_id = True
if found_vpc_id:
LOGGER.info("Private hosted zone %s is associated with \
VPC %s %s", private_hosted_zone_id, vpc_id, lineno())
else:
LOGGER.info("Associating zone %s with \
VPC %s %s", private_hosted_zone_id, vpc_id, lineno())
try:
associate_zone(route53, private_hosted_zone_id, region, vpc_id)
except BaseException as err:
LOGGER.info('You cannot create an association with a VPC \
with an overlapping subdomain.\n', err)
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
exit()
try:
create_resource_record(
route53,
private_hosted_zone_id,
private_host_name,
private_hosted_zone_name,
'A',
private_ip
)
LOGGER.debug("appending to caller response %s", lineno())
caller_response.append('Created A record in zone id: ' +
str(private_hosted_zone_id) +
' for hosted zone ' +
str(private_host_name) + '.' +
str(private_hosted_zone_name) +
' with value: ' +
str(private_ip))
create_resource_record(
route53,
reverse_lookup_zone_id,
reversed_ip_address,
'in-addr.arpa',
'PTR',
private_dns_name
)
caller_response.append('Created PTR record in zone id: ' +
str(reverse_lookup_zone_id) +
' for hosted zone ' +
str(reversed_ip_address) +
'in-addr.arpa with value: ' +
str(private_dns_name))
except BaseException as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
LOGGER.debug("%s", str(err)+lineno())
else:
try:
delete_resource_record(
route53,
private_hosted_zone_id,
private_host_name,
private_hosted_zone_name,
'A',
private_ip
)
caller_response.append('Deleted A record in zone id: ' +
str(private_hosted_zone_id) +
' for hosted zone ' +
str(private_host_name) + '.' +
str(private_hosted_zone_name) +
' with value: ' +
str(private_ip))
delete_resource_record(
route53,
reverse_lookup_zone_id,
reversed_ip_address,
'in-addr.arpa',
'PTR',
private_dns_name
)
caller_response.append('Deleted PTR record in zone id: ' +
str(reverse_lookup_zone_id) +
' for hosted zone ' +
str(reversed_ip_address) + '.' +
str(private_dns_name) +
' with value: ' +
str(private_dns_name))
except BaseException as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
LOGGER.debug("%s", str(err)+lineno())
# create PTR record
elif tag.get('Value').lstrip().lower() in public_hosted_zones_collection:
LOGGER.debug("Public zone found %s", tag.get('Value') + lineno())
public_hosted_zone_name = tag.get('Value').lstrip().lower()
public_hosted_zone_id = get_zone_id(
route53,
public_hosted_zone_name,
private_zone=False
)
# create A record in public zone
if state == 'running':
try:
create_resource_record(
route53,
public_hosted_zone_id,
cname_prefix,
public_hosted_zone_name,
'A',
public_ip
)
caller_response.append('Created A record in zone id: ' +
str(public_hosted_zone_id) +
' for hosted zone ' +
str(cname_prefix) + '.' +
str(public_hosted_zone_name) +
' with value: ' +
str(public_ip))
except BaseException as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
LOGGER.debug("%s", str(err) + lineno())
else:
try:
delete_resource_record(
route53,
public_hosted_zone_id,
cname_prefix,
public_hosted_zone_name,
'A',
public_ip
)
caller_response.append('Deleted A record in zone id: ' +
str(public_hosted_zone_id) +
' for hosted zone ' +
str(cname_prefix) + '.' +
str(public_hosted_zone_name) +
' with value: ' +
str(public_ip))
except BaseException as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
LOGGER.debug("%s", str(err) + lineno())
else:
LOGGER.info("No matching zone found for %s", tag.get('Value'))
else:
LOGGER.info("%s is not a valid host name %s", tag.get('Value'), lineno())
# Consider making this an elif CNAME
else:
LOGGER.debug("The tag \'%s\' is not a zone tag %s", str(tag.get('Key')), lineno())
if 'CNAME' in tag.get('Key', {}).lstrip().upper():
# Simple hostname check
if is_valid_hostname(tag.get('Value')):
LOGGER.debug("CNAME hostname of %s is valid %s", str(tag.get('Value')), lineno())
# convert the cname value to lower case and strip whitespace and newline characters
icname = tag.get('Value').lstrip().lower()
LOGGER.debug("icname: %s", str(icname) + lineno())
# Gets the prefix for the cname
cname_host_name = icname.split('.')[0]
LOGGER.debug("cname_host_name: %s", str(cname_host_name) + lineno())
# Gets suffix
cname_domain_suffix = icname[icname.find('.') + 1:]
LOGGER.debug("cname_domain_suffix: %s", str(cname_domain_suffix) + lineno())
# Try and find the hosted zone with the cname suffix
cname_domain_suffix_id = get_zone_id(route53, cname_domain_suffix)
LOGGER.debug("cname_domain_suffix_id: %s", str(cname_domain_suffix_id))
# Iterate of the private hosted zones
LOGGER.debug("Iterating over private hosted zones %s", lineno())
for cname_private_hosted_zone in private_hosted_zone_collection:
LOGGER.debug("cname for private hosted zone in private hosted \
zone collection: %s", str(cname_private_hosted_zone) + lineno())
cname_private_hosted_zone_id = get_zone_id(route53, cname_private_hosted_zone)
LOGGER.debug("cname_private_hosted_zone_id:"
" %s", str(cname_private_hosted_zone_id) + lineno())
LOGGER.debug("cname_domain_suffix_id:"
" %s", str(cname_domain_suffix_id) + lineno())
if cname_domain_suffix_id == cname_private_hosted_zone_id:
LOGGER.debug("cname_domain_suffix_id:"
" %s", str(cname_domain_suffix_id) + lineno())
if cname.endswith(cname_private_hosted_zone):
LOGGER.debug("cname ends with"
" %s", str(cname_private_hosted_zone) + lineno())
# create CNAME record in private zone
if state == 'running':
try:
LOGGER.debug("creating resource record %s", lineno())
LOGGER.debug("private_dns_name:"
" %s", str(private_dns_name) + lineno())
create_resource_record(
route53,
cname_private_hosted_zone_id,
cname_host_name,
cname_private_hosted_zone,
'CNAME',
private_dns_name
)
caller_response.append('Created CNAME record in zone id: ' +
str(cname_private_hosted_zone_id) +
' for hosted zone ' +
str(cname_host_name) + '.' +
str(cname_private_hosted_zone) +
' with value: ' +
str(private_dns_name))
except BaseException as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION,
"Unexpected error:" + str(err) + lineno())
LOGGER.debug("%s", str(err) + lineno())
else:
try:
LOGGER.debug("deleting resource record %s", lineno())
delete_resource_record(
route53,
cname_private_hosted_zone_id,
cname_host_name,
cname_private_hosted_zone,
'CNAME',
private_dns_name
)
caller_response.append('Deleted CNAME record in zone id: ' +
str(cname_private_hosted_zone_id) +
' for hosted zone ' +
str(cname_host_name) + '.' +
str(cname_private_hosted_zone) +
' with value: ' +
str(private_dns_name))
except BaseException as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION,
"Unexpected error:" + str(err) + lineno())
LOGGER.debug("%s", str(err) + lineno())
# Only do public if there is public ip on instance
if public_dns_name:
# Iterate over the public hosted zones
LOGGER.debug("Iterating over public hosted zones %s", lineno())
for cname_public_hosted_zone in public_hosted_zones_collection:
LOGGER.debug("cname in public hosted zone:"
" %s", str(cname_public_hosted_zone) + lineno())
LOGGER.debug("cname is: %s", str(cname) + lineno())
if cname.endswith(cname_public_hosted_zone):
cname_public_hosted_zone_id = get_zone_id(
route53,
cname_public_hosted_zone,
False
)
LOGGER.debug("cname_public_hosted_zone_id:"
" %s", str(cname_public_hosted_zone_id) + lineno())
# create CNAME record in public zone
if state == 'running':
try:
create_resource_record(
route53,
cname_public_hosted_zone_id,
cname_host_name,
cname_public_hosted_zone,
'CNAME',
public_dns_name
)
caller_response.append('Created CNAME record in zone id: ' +
str(cname_public_hosted_zone_id) +
' for hosted zone ' +
str(cname_host_name) + '.' +
str(cname_public_hosted_zone) +
' with value: ' +
str(public_dns_name))
except BaseException as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION,
"Unexpected error:" + str(err) + lineno())
LOGGER.debug("%s", str(err) + lineno())
else:
try:
delete_resource_record(
route53,
cname_public_hosted_zone_id,
cname_host_name,
cname_public_hosted_zone,
'CNAME',
public_dns_name
)
caller_response.append('Deleted CNAME record in zone id: ' +
str(cname_public_hosted_zone_id) +
' for hosted zone ' +
str(cname_host_name) + '.' +
str(cname_public_hosted_zone) +
' with value: ' +
str(public_dns_name))
except BaseException as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION,
"Unexpected error:" +
str(err) + lineno())
LOGGER.debug("%s", str(err) + lineno())
# Is there a DHCP option set?
# Get DHCP option set configuration
LOGGER.debug("\n#############\nIterate over DHCP option sets %s\n", lineno())
try:
LOGGER.debug("trying to get dhcp option set id %s", lineno())
dhcp_options_id = get_dhcp_option_set_id_for_vpc(compute, vpc_id)
LOGGER.debug("dhcp_options_id: %s", str(dhcp_options_id) + lineno())
dhcp_configurations = get_dhcp_configurations(compute, dhcp_options_id)
LOGGER.debug("dhcp_configurations: %s", str(get_dhcp_configurations) + lineno())
except BaseException as err:
LOGGER.info("No DHCP option set assigned to this VPC %s\n", str(err)+lineno())
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
exit()
# Look to see whether there's a DHCP option set assigned to
# the VPC. If there is, use the value of the domain name
# to create resource records in the appropriate Route 53
# private hosted zone. This will also check to see whether
# there's an association between the instance's VPC and
# the private hosted zone. If there isn't, it will create it.
for configuration in dhcp_configurations:
LOGGER.debug("configuration: %s", str(configuration) + lineno())
LOGGER.debug("private hosted zones: %s", str(private_hosted_zone_collection) + lineno())
if configuration in private_hosted_zone_collection:
private_hosted_zone_name = configuration
LOGGER.debug("Private zone found %s", str(private_hosted_zone_name) + lineno())
private_hosted_zone_id = get_zone_id(route53, private_hosted_zone_name)
LOGGER.debug("Private_hosted_zone_id: %s", str(private_hosted_zone_id) + lineno())
private_hosted_zone_properties = get_hosted_zone_properties(
route53,
private_hosted_zone_id
)
LOGGER.debug("private_hosted_zone_properties:"
" %s", str(private_hosted_zone_properties) + lineno())
# create A records and PTR records
if state == 'running':
if vpc_id in map(lambda x: x['VPCId'], private_hosted_zone_properties['VPCs']):
LOGGER.info("Private hosted zone %s is associated \
with VPC %s %s", private_hosted_zone_id, vpc_id, lineno())
else:
LOGGER.info("Associating zone %s with VPC"
" %s %s", private_hosted_zone_id, vpc_id, lineno())
try:
associate_zone(route53, private_hosted_zone_id, region, vpc_id)
except BaseException as err:
LOGGER.info("You cannot create an association with a \
VPC with an overlapping subdomain. %s\n", str(err))
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
exit()
try:
if not tag_type == 'cname':
LOGGER.debug("Creating resource records %s", lineno())
create_resource_record(
route53,
private_hosted_zone_id,
private_host_name,
private_hosted_zone_name,
'A',
private_ip
)
caller_response.append('Created A record in zone id: ' +
str(private_hosted_zone_id) +
' for hosted zone ' +
str(private_host_name) + '.' +
str(private_hosted_zone_name) +
' with value: ' +
str(private_ip))
create_resource_record(
route53,
reverse_lookup_zone_id,
reversed_ip_address,
'in-addr.arpa',
'PTR',
private_dns_name
)
caller_response.append('Created PTR record in zone id: ' +
str(reverse_lookup_zone_id) +
' for hosted zone ' +
str(reversed_ip_address) +
'in-addr.arpa with value: ' +
str(private_dns_name))
else:
LOGGER.debug("Creating resource records %s", lineno())
create_resource_record(
route53,
private_hosted_zone_id,
cname_prefix,
private_hosted_zone_name,
'A',
private_ip
)
caller_response.append('Created A record in zone id: ' +
str(private_hosted_zone_id) + ' for hosted zone ' +
str(cname_prefix) + '.' +
str(private_hosted_zone_name) + ' with value: ' +
str(private_ip))
create_resource_record(
route53,
reverse_lookup_zone_id,
reversed_ip_address,
'in-addr.arpa',
'PTR',
cname
)
caller_response.append('Created PTR record in zone id: ' +
str(reverse_lookup_zone_id) +
' for hosted zone ' +
str(reversed_ip_address) +
'in-addr.arpa with value: ' +
str(cname))
except BaseException as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
else:
LOGGER.debug("Deleting resource records: %s", lineno())
try:
if not tag_type == 'cname':
delete_resource_record(
route53,
private_hosted_zone_id,
private_host_name,
private_hosted_zone_name,
'A',
private_ip
)
caller_response.append('Deleted A record in zone id: ' +
str(private_hosted_zone_id) + ' for hosted zone ' +
str(private_host_name) + '.' +
str(private_hosted_zone_name) + ' with value: ' +
str(private_ip))
delete_resource_record(
route53,
reverse_lookup_zone_id,
reversed_ip_address,
'in-addr.arpa',
'PTR',
private_dns_name
)
caller_response.append('Deleted PTR record in zone id: ' +
str(reverse_lookup_zone_id) +
' for hosted zone ' +
str(reversed_ip_address) +
'in-addr.arpa with value: ' +
str(private_dns_name))
else:
delete_resource_record(
route53,
private_hosted_zone_id,
cname_prefix,
private_hosted_zone_name,
'A',
private_ip
)
caller_response.append('Deleted A record in zone id: ' +
str(private_hosted_zone_id) + ' for hosted zone ' +
str(cname_prefix) + '.' +
str(private_hosted_zone_name) + ' with value: ' +
str(private_ip))
delete_resource_record(
route53,
reverse_lookup_zone_id,
reversed_ip_address,
'in-addr.arpa',
'PTR',
cname
)
caller_response.append('Deleted PTR record in zone id: ' +
str(reverse_lookup_zone_id) +
' for hosted zone ' +
str(reversed_ip_address) +
'in-addr.arpa with value: ' +
str(cname))
except BaseException as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
else:
LOGGER.debug("No matching zone for %s", str(configuration) + lineno())
# Clean up DynamoDB after deleting records
if state != 'running':
delete_item_from_dynamodb_table(dynamodb_client, 'DDNS', instance_id)
caller_response.insert(0, 'Successfully removed recordsets')
return caller_response
caller_response.insert(0, 'Successfully created recordsets')
return caller_response
def determine_tag_type(tags):
"""
Determine tag type - CNAME or ZONE
:param tags:
:return:
"""
cname = -1
zone = -1
for item in tags:
LOGGER.debug("item: %s", str(item) + lineno())
if item['Key'].lower() == 'cname':
cname = 1
elif item['Key'].lower() == 'zone':
zone = 1
if cname < 0 and zone < 0:
return None
elif cname > 0 and zone < 0:
return 'cname'
elif cname < 0 and zone > 0:
return 'zone'
return 'invalid'
def get_cname_from_tags(tags):
"""
Get the cname prefix from tags
:param tags:
:return:
"""
try:
for tag in tags:
LOGGER.debug("tag: %s", str(tag))
if 'CNAME' in tag.get('Key', {}).lstrip().upper():
cname = tag.get('Value').lstrip().lower()
return cname
return None
except:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(sys.exc_info()[0]) + lineno())
def get_instances(client, instance_id):
"""
Get ec2 instance information
:return:
"""
try:
return client.describe_instances(InstanceIds=[instance_id])
except ClientError as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
def list_hosted_zones(client):
"""
Get route53 hosted zones
:param client:
:return:
"""
try:
return client.list_hosted_zones()
except ClientError as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
def list_tables(client):
"""
List the dynamodb tables
:param client:
:return:
"""
try:
return client.list_tables()
except ClientError as err:
publish_to_sns(SNS_CLIENT, ACCOUNT, REGION, "Unexpected error:" +
str(err) + lineno())
def delete_item_from_dynamodb_table(client, table, instance_id):
"""
Delete the item from dynamodb table