forked from linuxdynasty/ld-ansible-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathec2_vpc_route_table.py
1586 lines (1439 loc) · 51 KB
/
ec2_vpc_route_table.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
#!/usr/bin/python
#
# This is a free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This Ansible library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this library. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: ec2_vpc_route_table
short_description: Manage route tables for AWS virtual private clouds
description:
- Manage route tables for AWS virtual private clouds
version_added: "2.2"
author: Robert Estelle (@erydo), Rob White (@wimnat), Allen Sanabria (@linuxdynasty)
options:
lookup:
description:
- "This option is deprecated. Tags are manadatory when creating a route
table. If a route table id is specified, then that will be use. Otherwise, this module will perform an exact match for all the tags applied. If a match is not found, it will than search by tag Name."
- "Look up route table by either tags or by route table ID. Non-unique
tag lookup will fail. If no tags are specifed then no lookup for an existing route table is performed and a new route table will be created. To change tags of a route table, you must look up by id."
required: false
default: tag
choices: [ 'tag', 'id' ]
propagating_vgw_ids:
description:
- "Enable route propagation from virtual gateways specified by ID. Only 1 virtual gateway can only be applied to a vpc at a time."
default: None
required: false
route_table_id:
description:
- "The ID of the route table to update or delete."
required: false
default: null
routes:
description:
- "List of routes in the route table. Routes are specified as dicts
containing the keys 'dest' and one of 'gateway_id', 'instance_id', 'nat_gateway_id', interface_id', or 'vpc_peering_connection_id'. If 'gateway_id' is specified, you can refer to the VPC's IGW by using the value 'igw'."
required: true
state:
description:
- "Create or destroy the VPC route table"
required: false
default: present
choices: [ 'present', 'absent' ]
subnets:
description:
- "An array of subnets to add to this route table. Subnets may be specified by either subnet ID, Name tag, or by a CIDR such as '10.0.0.0/24'."
required: true
tags:
description:
- "A dictionary of resource tags of the form: { tag1: value1, tag2: value2 }. Tags are used to uniquely identify route tables within a VPC when the route_table_id is not supplied."
required: false
default: null
aliases: [ "resource_tags" ]
vpc_id:
description:
- "VPC ID of the VPC in which to create the route table."
required: true
extends_documentation_fragment:
- aws
- ec2
'''
EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.
# Basic creation example:
- name: Set up public subnet route table
ec2_vpc_route_table:
vpc_id: vpc-1245678
region: us-west-1
tags:
Name: Public
subnets:
- "{{ jumpbox_subnet.subnet.id }}"
- "{{ frontend_subnet.subnet.id }}"
- "{{ vpn_subnet.subnet_id }}"
routes:
- dest: 0.0.0.0/0
gateway_id: "{{ igw.gateway_id }}"
register: public_route_table
- name: Set up NAT-protected route table
ec2_vpc_route_table:
vpc_id: vpc-1245678
region: us-west-1
tags:
Name: Internal
subnets:
- "{{ application_subnet.subnet.id }}"
- 'Database Subnet'
- '10.0.0.0/8'
routes:
- dest: 0.0.0.0/0
instance_id: "{{ nat.instance_id }}"
register: nat_route_table
'''
RETURN = '''
associations:
description: List of subnets attached to this route table with its association id.
returned: success
type: string
sample: [
{
"subnet_id": "subnet-12345667",
"route_table_id": "rtb-1234567",
"main": false,
"route_table_association_id": "rtbassoc-1234567"
},
{
"subnet_id": "subnet-78654321",
"route_table_id": "rtb-78654321",
"main": false,
"route_table_association_id": "rtbassoc-78654321"
}
]
propagating_vgws:
description: List of virtual gateways applied to the route table.
returned: success
type: string
sample: [
{
'gateway_id': 'vgw-1234567'
}
]
routes:
description: List of tags applied to the route table.
returned: success
type: string
sample: [
{
"gateway_id": "local",
"origin": "CreateRouteTable",
"state": "active",
"destination_cidr_block": "10.100.0.0/16"
},
{
"origin": "CreateRoute",
"state": "active",
"nat_gateway_id": "nat-12345678",
"destination_cidr_block": "0.0.0.0/0"
}
]
tags:
description: List of tags applied to the route table.
returned: success
type: string
sample: [
{
"key": "Name",
"value": "dev_route_table"
},
{
"key": "env",
"value": "development"
}
]
route_table_id:
description: The resource id of an Amazon route table.
returned: success
type: string
sample: "rtb-1234567"
vpc_id:
description: id of the VPC.
returned: In all cases.
type: string
sample: "vpc-12345"
'''
try:
import botocore
import boto3
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
import re
import datetime
from functools import reduce
DRY_RUN_MATCH = re.compile(r'DryRun flag is set')
def convert_to_lower(data):
"""Convert all uppercase keys in dict with lowercase_
Args:
data (dict): Dictionary with keys that have upper cases in them
Example.. NatGatewayAddresses == nat_gateway_addresses
if a val is of type datetime.datetime, it will be converted to
the ISO 8601
Basic Usage:
>>> test = {'NatGatewaysAddresses': []}
>>> test = convert_to_lower(test)
{
'nat_gateways_addresses': []
}
Returns:
Dictionary
"""
results = dict()
if isinstance(data, dict):
for key, val in data.items():
key = re.sub(r'(([A-Z]{1,3}){1})', r'_\1', key).lower()
if key[0] == '_':
key = key[1:]
if isinstance(val, datetime.datetime):
results[key] = val.isoformat()
elif isinstance(val, dict):
results[key] = convert_to_lower(val)
elif isinstance(val, list):
converted = list()
for item in val:
converted.append(convert_to_lower(item))
results[key] = converted
else:
results[key] = val
return results
GATEWAY_MAP = {
'gateway_id': 'GatewayId',
'instance_id': 'InstanceId',
'network_interface_id': 'NetworkInterfaceId',
'vpc_peering_connection_id': 'VpcPeeringConnectionId',
'nat_gateway_id': 'NatGatewayId',
}
def valid_gateway_types():
"""List of currently supported gateway types in Boto3
Basic Usage
>>> valid_gateway_types()
Returns:
List
"""
return [
'gateway_id',
'instance_id',
'network_interface_id',
'vpc_peering_connection_id',
'nat_gateway_id'
]
def valid_route_type(route):
"""Validate if dictionary contains a valid gateway key.
Args:
route (dict): Dictionary containing the route information.
Basic Usage:
>>> route = {'dest': '0.0.0.0/0', 'nat_gateway_id': 'ngw-123456789'}
>>> success, key = valid_route_type(route)
Returns:
Tuple (bool, str)
"""
success = False
for key, val in route.items():
if key != 'dest' and key in valid_gateway_types():
success = True
return success, key
elif key != 'dest' and key not in valid_gateway_types():
return success, key
def validate_routes(routes):
"""Validate if all of the routes contain valid gateway keys.
Args:
routes (list): List of routes.
Basic Usage:
>>> routes = [{'dest': '0.0.0.0/0', 'nat_gateway_id': 'ngw-123456789'}]
>>> success, err_msg = validate_routes(routes)
Returns:
Tuple (bool, str)
"""
success = True
err_msg = ''
for route in routes:
success, route_type = valid_route_type(route)
if not success:
err_msg = '{0} is not a valid gateway type'.format(route_type)
return success, err_msg
def route_keys(client, vpc_id, routes, check_mode=False):
"""Return a new list containing updated keys.
Args:
client (botocore.client.EC2): Boto3 client.
vpc_id (str): The vpc_id of the vpc.
routes (list): List of routes.
Basic Usage:
>>> client = boto3.client('ec2')
>>> vpc_id = 'vpc-1234567'
>>> routes = [{'dest': '0.0.0.0/0', 'nat_gateway_id': 'ngw-123456789'}]
>>> new_routes = route_keys(client, vpc_id, routes)
[
{
'dest': '0.0.0.0/0',
'id': 'ngw-123456789',
'gateway_type': 'nat_gateway_id'
}
]
Returns:
List
"""
new_routes = list()
for route in routes:
info = dict()
for key, val in route.items():
if key != 'dest' and key in valid_gateway_types():
if key == 'gateway_id' and val == 'igw':
igw_success, igw_msg, igw_id = (
find_igw(client, vpc_id, check_mode=check_mode)
)
if igw_success and igw_id:
val = igw_id
info['id'] = val
info['gateway_type'] = key
elif key == 'dest':
info['dest'] = val
new_routes.append(info)
return new_routes
def make_tags_in_proper_format(tags):
"""Take a list of tags and convert them into a proper dictionary.
Args:
tags (list): The tags you want applied.
Basic Usage:
>>> tags = [{u'Key': 'env', u'Value': 'development'}]
>>> make_tags_in_proper_format(tags)
[
{
"env": "development"
}
]
Returns:
Dict
"""
formatted_tags = dict()
for tag in tags:
formatted_tags[tag.get('Key')] = tag.get('Value')
return formatted_tags
def make_tags_in_aws_format(tags):
"""Take a dictionary of tags and convert them into the AWS Tags format.
Args:
tags (dict): The tags you want applied.
Basic Usage:
>>> tags = {'env': 'development', 'service': 'web'}
>>> make_tags_in_proper_format(tags)
[
{
"Value": "web",
"Key": "service"
},
{
"Value": "development",
"key": "env"
}
]
Returns:
List
"""
formatted_tags = list()
for key, val in tags.items():
formatted_tags.append({
'Key': key,
'Value': val
})
return formatted_tags
def find_igw(client, vpc_id, check_mode=False):
"""Find an Internet Gateway for a VPC.
Args:
client (botocore.client.EC2): Boto3 client.
vpc_id (str): The vpc_id of the vpc.
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('ec2')
>>> vpc_id = 'vpc-1234567'
>>> find_igw(client, vpc_id)
Returns:
Tuple (bool, str, str)
"""
err_msg = ''
success = False
igw_id = None
params = {
'DryRun': check_mode,
'Filters': [
{
'Name': 'attachment.vpc-id',
'Values': [vpc_id],
}
]
}
try:
results = (
client.describe_internet_gateways(**params)['InternetGateways']
)
if len(results) == 1:
success = True
igw_id = results[0]['InternetGatewayId']
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
success = True
err_msg = e.message
else:
err_msg = str(e)
return success, err_msg, igw_id
def find_subnet_associations(client, vpc_id, subnet_ids, check_mode=False):
"""Find all route tables that contain the subnet_ids within vpc_id.
Args:
client (botocore.client.EC2): Boto3 client.
vpc_id (str): The vpc_id of the vpc.
subnet_ids (list): List of subnet_ids.
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('ec2')
>>> vpc_id = 'vpc-1234567'
>>> subnet_ids = ['subnet-1234567', 'subnet-7654321']
>>> find_subnet_associations(client, vpc_id, subnet_ids)
Returns:
Tuple (bool, str, list)
"""
err_msg = ''
success = False
results = list()
params = {
'DryRun': check_mode,
'Filters': [
{
'Name': 'vpc-id',
'Values': [vpc_id],
},
{
'Name': 'association.subnet-id',
'Values': subnet_ids
}
]
}
try:
results = client.describe_route_tables(**params)['RouteTables']
success = True
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
success = True
err_msg = e.message
else:
err_msg = str(e)
return success, err_msg, results
def find_route_table(client, vpc_id, tags=None, route_table_id=None,
check_mode=False):
"""Find a route table in a vpc by either the route_table_id or by matching
the exact list of tags that were passed.
Args:
client (botocore.client.EC2): Boto3 client.
vpc_id (str): The vpc_id of the vpc.
Kwargs:
tags (dict): Dictionary containing the tags you want to search by.
route_table_id (str): The route table id.
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('ec2')
>>> vpc_id = 'vpc-1234567'
>>> tags = {'Name': 'Public-Route-Table-A'}
>>> find_route_table(client, vpc_id, tags=tags)
Returns:
Tuple (bool, str, list)
"""
err_msg = ''
success = False
results = dict()
params = {
'DryRun': check_mode,
'Filters': [
{
'Name': 'vpc-id',
'Values': [vpc_id],
}
]
}
if tags and not route_table_id:
for key, val in tags.items():
params['Filters'].append(
{
'Name': 'tag:{0}'.format(key),
'Values': [ val ]
}
)
elif route_table_id and not tags:
params['RouteTableIds'] = [route_table_id]
elif route_table_id and tags:
#If route table id is passed with tags, use route_table_id
params['RouteTableIds'] = [route_table_id]
else:
err_msg = 'Must lookup by tag or by id'
try:
results = client.describe_route_tables(**params)['RouteTables']
if len(results) == 1:
results = results[0]
success = True
elif len(results) > 1:
err_msg = 'More than 1 route found'
else:
err_msg = 'No routes found'
success = True
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
success = True
err_msg = e.message
else:
err_msg = str(e)
return success, err_msg, results
def tags_action(client, resource_id, tags, action='create', check_mode=False):
"""Create or delete multiple tags from an Amazon resource id
Args:
client (botocore.client.EC2): Boto3 client.
resource_id (str): The Amazon resource id.
tags (list): List of dictionaries.
examples.. [{Name: "", Values: [""]}]
Kwargs:
action (str): The action to perform.
valid actions == create and delete
default=create
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('ec2')
>>> resource_id = 'pcx-123345678'
>>> tags = [{'Name': 'env', 'Values': ['Development']}]
>>> update_tags(client, resource_id, tags)
[True, '']
Returns:
List (bool, str)
"""
success = False
err_msg = ""
params = {
'Resources': [resource_id],
'Tags': tags,
'DryRun': check_mode
}
try:
if action == 'create':
client.create_tags(**params)
success = True
elif action == 'delete':
client.delete_tags(**params)
success = True
else:
err_msg = 'Invalid action {0}'.format(action)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
success = True
err_msg = e.message
else:
err_msg = str(e)
return success, err_msg
def recreate_tags_from_list(list_of_tags):
"""Recreate tags from a list of tuples into the Amazon Tag format.
Args:
list_of_tags (list): List of tuples.
Basic Usage:
>>> list_of_tags = [('Env', 'Development')]
>>> recreate_tags_from_list(list_of_tags)
[
{
"Value": "Development",
"Key": "Env"
}
]
Returns:
List
"""
tags = list()
i = 0
list_of_tags = list_of_tags
for i in range(len(list_of_tags)):
key_name = list_of_tags[i][0]
key_val = list_of_tags[i][1]
tags.append(
{
'Key': key_name,
'Value': key_val
}
)
return tags
def update_tags(client, resource_id, current_tags, tags, check_mode=False):
"""Update tags for an amazon resource.
Args:
resource_id (str): The Amazon resource id.
current_tags (list): List of dictionaries.
examples.. [{Name: "", Values: [""]}]
tags (list): List of dictionaries.
examples.. [{Name: "", Values: [""]}]
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('ec2')
>>> resource_id = 'pcx-123345678'
>>> tags = [{'Name': 'env', 'Values': ['Development']}]
>>> update_tags(client, resource_id, tags)
[True, '']
Return:
Tuple (bool, str)
"""
success = False
err_msg = ''
if current_tags:
current_tags_set = (
set(
reduce(
lambda x, y: x + y,
[x.items() for x in make_tags_in_proper_format(current_tags)]
)
)
)
new_tags_set = (
set(
reduce(
lambda x, y: x + y,
[x.items() for x in make_tags_in_proper_format(tags)]
)
)
)
tags_to_delete = list(current_tags_set.difference(new_tags_set))
tags_to_update = list(new_tags_set.difference(current_tags_set))
if tags_to_delete:
tags_to_delete = recreate_tags_from_list(tags_to_delete)
delete_success, delete_msg = (
tags_action(
client, resource_id, tags_to_delete, action='delete',
check_mode=check_mode
)
)
if not delete_success:
return delete_success, delete_msg
if tags_to_update:
tags = recreate_tags_from_list(tags_to_update)
else:
return True, 'Tags do not need to be updated'
if tags:
create_success, create_msg = (
tags_action(
client, resource_id, tags, action='create',
check_mode=check_mode
)
)
return create_success, create_msg
return success, err_msg
def vgw_action(client, route_table_id, vgw_id, action='create'):
"""Enable or disable multiple a virtual gateway from an Amazon route table.
Args:
client (botocore.client.EC2): Boto3 client.
route_table_id (str): The Amazon resource id.
vgw_id (str): The virtual gateway id.
Kwargs:
action (str): The action to perform.
valid actions == create and delete
default=create
Basic Usage:
>>> client = boto3.client('ec2')
>>> route_table_id = 'rtb-123345678'
>>> vgw_id = 'vgw-1234567'
>>> vgw_action(client, route_table_id, vgw_id, 'create')
[True, '']
Returns:
List (bool, str)
"""
success = False
err_msg = ''
params = {
'GatewayId': vgw_id,
'RouteTableId': route_table_id,
}
try:
if action == 'create':
client.enable_vgw_route_propagation(**params)
success = True
elif action == 'delete':
client.disable_vgw_route_propagation(**params)
success = True
else:
err_msg = 'Invalid action {0}'.format(action)
except botocore.exceptions.ClientError as e:
err_msg = str(e)
return success, err_msg
def update_vgw(client, route_table_id, current_vgws, vgw_id=None):
"""Update the virtual gateway status on an Amazon route table.
Args:
client (botocore.client.EC2): Boto3 client.
route_table_id (str): The Amazon resource id.
current_vgws (list): List, containing enabled virtual gateways.
vgw_id (str): The virtual gateway id you want to keep enabled.
Basic Usage:
>>> client = boto3.client('ec2')
>>> route_table_id = 'rtb-123345678'
>>> current_vgws = [{u'GatewayId': 'vgw-1234567'}]
>>> vgw_id = 'vgw-1234567'
>>> update_vgw(client, route_table_id, current_vgws, vgw_id)
[True, '']
Returns:
List (bool, str)
"""
success = True
err_msg = ''
if current_vgws:
for vgws in current_vgws:
for vgw in vgws.values():
if vgw != vgw_id or not vgw_id:
if not vgw_id:
vgw_to_delete_id = vgw
else:
vgw_to_delete_id = vgw_id
disable_success, disable_msg = (
vgw_action(
client, route_table_id, vgw_to_delete_id, 'delete'
)
)
if vgw_id and disable_success:
enable_success, enable_msg = (
vgw_action(client, route_table_id, vgw_id)
)
return enable_success, enable_msg
else:
return disable_success, disable_msg
elif not current_vgws and vgw_id:
enable_success, enable_msg = (
vgw_action(client, route_table_id, vgw_id)
)
return enable_success, enable_msg
return success, err_msg
def subnet_action(client, route_table_id, subnet_id=None, association_id=None,
action='create', check_mode=False):
"""Associate or Disasscoiate subnet_id from an Amazon route table.
Args:
client (botocore.client.EC2): Boto3 client.
route_table_id (str): The Amazon resource id for a route table.
Kwargs:
subnet_id (str): The Amazon resource id for a subnet.
association_id (str): The Amazon resource id for an association.
action (str): The action to perform.
valid actions == create and delete
default=create
Basic Usage:
>>> client = boto3.client('ec2')
>>> route_table_id = 'rtb-123345678'
>>> subnet_id = 'subnet-1234567'
>>> subnet_action(client, route_table_id, subnet_id, 'create')
[True, '']
Returns:
List (bool, str)
"""
success = False
err_msg = ''
params = {
'DryRun': check_mode
}
try:
if action == 'create':
params['SubnetId'] = subnet_id
params['RouteTableId'] = route_table_id
client.associate_route_table(**params)
success = True
elif action == 'delete':
params['AssociationId'] = association_id
client.disassociate_route_table(**params)
success = True
else:
err_msg = 'Invalid action {0}'.format(action)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'DryRunOperation':
success = True
err_msg = e.message
else:
del routes_to_match[i]
# NOTE: As of boto==2.38.0, the origin of a route is not available
# (for example, whether it came from a gateway with route propagation
# enabled). Testing for origin == 'EnableVgwRoutePropagation' is more
# correct than checking whether the route uses a propagating VGW.
# The current logic will leave non-propagated routes using propagating
# VGWs in place.
routes_to_delete = [r for r in routes_to_match
if r.gateway_id != 'local'
and (propagating_vgw_ids is not None
and r.gateway_id not in propagating_vgw_ids)]
changed = routes_to_delete or route_specs_to_create
if changed:
for route_spec in route_specs_to_create:
try:
vpc_conn.create_route(route_table.id,
dry_run=check_mode,
**route_spec)
except EC2ResponseError as e:
if e.error_code == 'DryRunOperation':
pass
for route in routes_to_delete:
try:
vpc_conn.delete_route(route_table.id,
route.destination_cidr_block,
dry_run=check_mode)
except EC2ResponseError as e:
if e.error_code == 'DryRunOperation':
pass
return {'changed': bool(changed)}
def update_subnets(client, vpc_id, route_table_id, current_subnets,
new_subnet_ids, check_mode=False):
"""Update the associated subnets on an Amazon route table.
Args:
client (botocore.client.EC2): Boto3 client.
vpc_id (str): The Amazon resource id of the vpc.
route_table_id (str): The Amazon resource id of the route table.
current_subnets (list): List, containing the current subnets.
new_subnet_ids (str): List, containing the new subnet ids you want
associated with this route table.
Kwargs:
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('ec2')
>>> vpc_id = 'vpc-1234567'
>>> route_table_id = 'rtb-123345678'
>>> current_subnets = [
{
u'SubnetId': 'subnet-1234567',
u'RouteTableAssociationId': 'rtbassoc-1234567',
u'Main': False,
u'RouteTableId': 'rtb-1234567'
}
]
>>> subnet_ids = ['subnet-7654321', 'subnet-243567']
>>> update_subnets(client, vpc_id, route_table_id, current_subnets, subnet_ids)
[True, '']
Returns:
List (bool, str)
"""
current_subnet_ids = (
map(
lambda subnet: subnet['SubnetId'], current_subnets
)
)
subnet_ids_to_add = (
list(set(new_subnet_ids).difference(current_subnet_ids))
)
subnet_ids_to_remove = (
list(set(current_subnet_ids).difference(new_subnet_ids))
)
association_ids_to_remove = list()
for subnet_id in subnet_ids_to_remove:
for subnet in current_subnets:
subnet = convert_to_lower(subnet)
if subnet_id == subnet['subnet_id']:
association_ids_to_remove.append(
subnet['route_table_association_id']
)
success, err_msg, routes = (
find_subnet_associations(
client, vpc_id, subnet_ids_to_add, check_mode=check_mode
)
)
association_ids_to_remove_before_adding = list()
if success:
for route in routes:
for association in route['Associations']:
association_ids_to_remove_before_adding.append(
association['RouteTableAssociationId']
)
for association_id in association_ids_to_remove_before_adding:
delete_success, delete_msg = (
subnet_action(
client, route_table_id, association_id=association_id,
action='delete', check_mode=check_mode
)
)
if not delete_success:
return delete_success, delete_msg
for subnet_id in subnet_ids_to_add:
create_success, create_msg = (
subnet_action(
client, route_table_id, subnet_id, action='create',
check_mode=check_mode
)
)
if not create_success:
return create_success, create_msg
for association_id in association_ids_to_remove:
delete_success, delete_msg = (
subnet_action(
client, route_table_id, association_id=association_id,
action='delete', check_mode=False
)
)
if not delete_success:
return delete_success, delete_msg
return True, ''
def route_table_action(client, vpc_id=None, route_table_id=None,
action='create', check_mode=False):
"""Create or Delete an Amazon route table.
Args:
client (botocore.client.EC2): Boto3 client.
Kwargs:
vpc_id (str): The Amazon resource id for a vpc.
route_table_id (str): The Amazon resource id for a route table.
action (str): The action to perform.
valid actions == create and delete
default=create
check_mode (bool): This will pass DryRun as one of the parameters to the aws api.
default=False
Basic Usage:
>>> client = boto3.client('ec2')
>>> vpc_id = 'vpc-123345678'
>>> route_table_action(client, vpc_id, 'create')