-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathec2_vpc_peer.py
1544 lines (1408 loc) · 48.6 KB
/
ec2_vpc_peer.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 file is part of Ansible
#
# Ansible is 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
module: ec2_vpc_peer
short_description: create, delete, accept, and reject VPC peering connections between two VPCs.
description:
- Read the AWS documentation for VPC Peering Connections
U(http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-peering.html)
version_added: "2.2"
author: Allen Sanabria(@linuxdynasty)
extends_documentation_fragment: aws
requirements: [boto3, botocore]
options:
accept_peer:
description:
- If set to yes, the newly created peering connection will be accepted.
required: false
accept_with_profile:
description:
- The boto3 profile to use when you are auto accepting a cross account peer.
required: false
accepter_routes:
description:
- List of route table ids. These route tables will be updated with the
- CIDR block of the vpc_id using the vpc_peering_id that is generated when the peer is created.
required: false
requester_routes:
description:
- List of route table ids. These route tables will be updated with the
- CIDR block of the vpc_peer_id using the vpc_peering_id that is generated when the peer is created.
required: false
resource_tags:
description:
- Dictionary of Tags to apply to the newly created peer.
required: false
vpc_id:
description:
- VPC id of the requesting VPC.
required: false
peer_vpc_id:
description:
- VPC id of the accepting VPC.
required: false
peer_owner_id:
description:
- The AWS account number for cross account peering.
required: false
state:
description:
- Create, delete, accept, reject a peering connection.
required: false
default: present
choices: ['present', 'absent', 'accept', 'reject']
'''
EXAMPLES = '''
# Complete example to create and accept a local peering connection and auto accept.
- name: Create local account VPC peering Connection and auto accept
ec2_vpc_peer:
region: us-west-2
vpc_id: vpc-12345678
peer_vpc_id: vpc-87654321
state: present
accept_peer: yes
resource_tags:
- Name: new_peer
- Env: development
register: vpc_peer
# Complete example to create and accept a local peering connection and auto
# accept as well as add routes to the requester CIDR (The CIDR block of the vpc_id)
# using the newly created peering connection id.
- name: Create local account VPC peering Connection and auto accept and add routes
ec2_vpc_peer:
region: us-west-2
vpc_id: vpc-12345678
peer_vpc_id: vpc-87654321
state: present
accept_peer: yes
requester_routes:
- rtb-12345678
- rtb-98765432
resource_tags:
- Name: new_peer
- Env: development
register: vpc_peer
# Complete example to create and accept a local peering connection and auto
# accept as well as add routes to the accepter CIDR (The CIDR block of the vpc_peer_id)
# using the newly created peering connection id.
- name: Create local account VPC peering Connection and auto accept and add routes
ec2_vpc_peer:
region: us-west-2
vpc_id: vpc-12345678
peer_vpc_id: vpc-87654321
state: present
accept_peer: yes
accepter_routes:
- rtb-12345678
- rtb-98765432
resource_tags:
- Name: new_peer
- Env: development
register: vpc_peer
# Complete example to create and accept a cross account peering connection and auto accept.
# Boto3 profile for the other account must exist in ~/.aws/credentials
- name: Create cross account VPC peering Connection and auto accept
ec2_vpc_peer:
region: us-west-2
vpc_id: vpc-12345678
peer_vpc_id: vpc-87654321
state: present
accept_with_profile: boto3_profile_goes_here
peer_owner_id: 12345678910
resource_tags:
- Name: new_peer
- Env: development
register: vpc_peer
# Complete example to delete a local account peering connection.
# Boto3 profile for the other account must exist in ~/.aws/credentials
- name: Create cross account VPC peering Connection and auto accept
ec2_vpc_peer:
region: us-west-2
vpc_id: vpc-12345678
peer_vpc_id: vpc-87654321
state: present
resource_tags:
- Name: new_peer
- Env: development
register: vpc_peer
- name: delete a VPC peering Connection
ec2_vpc_peer:
region: us-west-2
peering_id: "{{ vpc_peer.vpc_peering_connection_id }}"
state: absent
register: vpc_peer
# Complete example to delete a cross account peering connection.
# Boto3 profile for the other account must exist in ~/.aws/credentials
- name: Create cross account VPC peering Connection and auto accept
ec2_vpc_peer:
region: us-west-2
vpc_id: vpc-12345678
peer_vpc_id: vpc-87654321
state: present
accept_with_profile: boto3_profile_goes_here
peer_owner_id: 12345678910
resource_tags:
- Name: new_peer
- Env: development
register: vpc_peer
- name: delete a cross account VPC peering Connection
ec2_vpc_peer:
region: us-west-2
peering_id: "{{ vpc_peer.vpc_peering_connection_id }}"
state: absent
profile: boto3_profile_goes_here
register: vpc_peer
# Complete example to reject a local account peering connection.
# Boto3 profile for the other account must exist in ~/.aws/credentials
- name: Create VPC peering Connection.
ec2_vpc_peer:
region: us-west-2
vpc_id: vpc-12345678
peer_vpc_id: vpc-87654321
state: present
resource_tags:
- Name: new_peer
- Env: development
register: vpc_peer
- name: Reject a VPC peering Connection
ec2_vpc_peer:
region: us-west-2
peering_id: "{{ vpc_peer.vpc_peering_connection_id }}"
state: reject
register: vpc_peer
# Complete example to reject a cross account peering connection.
# Boto3 profile for the other account must exist in ~/.aws/credentials
- name: Create cross account VPC peering Connection.
ec2_vpc_peer:
region: us-west-2
vpc_id: vpc-12345678
peer_vpc_id: vpc-87654321
state: present
peer_owner_id: 12345678910
resource_tags:
- Name: new_peer
- Env: development
register: vpc_peer
- name: Reject a cross account VPC peering Connection
ec2_vpc_peer:
region: us-west-2
peering_id: "{{ vpc_peer.vpc_peering_connection_id }}"
state: reject
profile: boto3_profile_goes_here
register: vpc_peer
'''
RETURN = '''
success:
description: Returns true if all succeeded and false if it failed.
returned: In all cases.
type: bool
sample: true
changed:
description: Returns true if action made a changed and false if it didn't.
returned: In all cases.
type: bool
sample: true
status:
description: Dictionary containing the message and code.
returned: Success.
type: dictionary
sample:
{
"message": "Active",
"code": "active"
}
tags:
description: List of dictionaries containing the key, val of each tag.
returned: Success.
type: list
sample:
[
{
"value": "web",
"key": "service"
}
]
accepter_vpc_info:
description: Dictionary containing the owner_id, vpc_id, and cidr_block.
returned: Success.
type: dictionary
sample:
{
"owner_id": "12345678910",
"vpc_id": "vpc-12345678",
"cidr_block": "172.31.0.0/16"
}
vpc_peering_connection_id:
description: The peering connection id.
returned: Success.
type: string
sample: pcx-12345678
requester_vpc_info:
description: Dictionary containing the owner_id, vpc_id, and cidr_block.
returned: Success.
type: dictionary
sample:
{
"owner_id": "12345678910",
"vpc_id": "vpc-12345678",
"cidr_block": "10.100.0.0/16"
}
'''
try:
import botocore
import boto3
import boto3.session
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
import datetime
import re
def create_client_with_profile(profile_name, region, resource_name='ec2'):
""" Create a new boto3 client with a boto3 profile in ~/.aws/credentials
Args:
profile_name (str): The name of the profile that you have set in your
~/.aws/credentials profile.
region (str): The aws region you want to connect to.
resource_name (str): Valid aws resource.
default=ec2
Basic Usage:
>>> client, err_msg = create_client_with_profile('lab01', 'us-west-2')
Returns:
Tuple (botocore.client.EC2, str)
"""
client = None
err_msg = ''
try:
session = (
boto3.session.Session(
profile_name=profile_name, region_name=region
)
)
client = session.client(resource_name)
except Exception as e:
err_msg = str(e)
return client, err_msg
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('([A-Z]{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
def find_tags(client, resource_id, check_mode=False):
"""Retrieve all tags for an Amazon resource id
Args:
client (botocore.client.EC2): Boto3 client
resource_id (str): The Amazon resource id.
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 = 'rtb-123456'
>>> success, msg, tags = find_tags(client, resource_id)
(
True,
'',
[
{
u'Value': 'Test-Private-Zone-A',
u'Key': 'Name'
}
]
)
Returns:
Tuple (bool, str, list)
"""
success = False
err_msg = ''
current_tags = list()
search_params = {
'Filters': [
{
'Name': 'resource-id',
'Values': [resource_id]
}
],
'DryRun': check_mode
}
try:
current_tags = client.describe_tags(**search_params)['Tags']
success = True
if current_tags:
for i in range(len(current_tags)):
current_tags[i].pop('ResourceType')
current_tags[i].pop('ResourceId')
except botocore.exceptions.ClientError, e:
if e.response['Error']['Code'] == 'DryRunOperation':
success = True
err_msg = e.message
else:
err_msg = str(e)
return success, err_msg, current_tags
def describe_peering_connections(client, vpc_id=None, vpc_peer_id=None,
vpc_peering_id=None, status_codes=None,
check_mode=False):
"""Retrieve peering connection info by peering_id or by searching by requestor and accepter.
Args:
client (botocore.client.EC2): Boto3 client
Kwargs:
vpc_id (str): The requestor vpc_id.
vpc_peer_id (str): The accepter vpc_id.
vpc_peering_id (str): The vpc peering connection id.
status_codes (list): The codes to filter on.
valid status codes = [
pending-acceptance, failed, expired, provisioning,
active, deleted, rejected
]
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-d18571b5'
>>> vpc_peer_id='vpc-68da9d0d'
>>> describe_peering_connections(client, vpc_id, vpc_peer_id)
[
True,
"",
[
{
"Status": {
"Message": "Active",
"Code": "active"
},
"Tags": [
{
"Value": "env",
"Key": "Management"
},
{
"Value": "Management to Production",
"Key": "Name"
}
],
"AccepterVpcInfo": {
"OwnerId": "12345678910",
"VpcId": "vpc-123456789",
"CidrBlock": "172.31.0.0/16"
},
"VpcPeeringConnectionId": "pcx-12345678",
"RequesterVpcInfo": {
"OwnerId": "12345678910",
"VpcId": "vpc-12345678",
"CidrBlock": "172.32.0.0/16"
}
}
]
]
Returns:
Tuple (bool, str, list)
"""
success = False
err_msg = ''
params = {
'DryRun': check_mode
}
result = list()
if vpc_id and vpc_peer_id:
params['Filters'] = [
{
'Name': 'requester-vpc-info.vpc-id',
'Values': [vpc_id],
},
{
'Name': 'accepter-vpc-info.vpc-id',
'Values': [vpc_peer_id],
}
]
if status_codes:
params['Filters'].append(
{
'Name': 'status-code',
'Values': status_codes
}
)
elif vpc_peering_id:
params['VpcPeeringConnectionIds'] = [vpc_peering_id]
if status_codes:
params['Filters'] = [
{
'Name': 'status-code',
'Values': status_codes
}
]
try:
result = (
client.describe_vpc_peering_connections(**params)
['VpcPeeringConnections']
)
success = True
except botocore.exceptions.ClientError, e:
if e.response['Error']['Code'] == 'DryRunOperation':
success = True
err_msg = e.message
else:
err_msg = str(e)
return success, err_msg, result
def is_active(peering_conn):
return peering_conn['status']['code'] == 'active'
def is_deleted(peering_conn):
return peering_conn['status']['code'] == 'deleted'
def is_expired(peering_conn):
return peering_conn['status']['code'] == 'expired'
def is_failed(peering_conn):
return peering_conn['status']['code'] == 'failed'
def is_initiating_request(peering_conn):
return peering_conn['status']['code'] == 'initiating-request'
def is_pending(peering_conn):
return peering_conn['status']['code'] == 'pending-acceptance'
def is_provisioning(peering_conn):
return peering_conn['status']['code'] == 'provisioning'
def is_rejected(peering_conn):
return peering_conn['status']['code'] == 'rejected'
def make_tags_in_proper_format(tags):
"""Take a list of aws tags and convert them into a list of dictionaries.
Where the key is the actual key and not Key.
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:
List
"""
formatted_tags = list()
for tag in tags:
formatted_tags.append(
{
tag.get('Key'): tag.get('Value')
}
)
return formatted_tags
def convert_list_of_tags(tags):
"""Convert a list of AWS Tag dictionaries into a dictionary.
Args:
tags (list): The tags you want applied.
Basic Usage:
>>> tags = [{u'Key': 'env', u'Value': 'development'}]
>>> convert_list_of_tags(tags)
{
"env": "development",
}
Returns:
Dict
"""
converted_tags = dict()
for tag in tags:
tag = convert_to_lower(tag)
converted_tags[tag.get('key')] = tag.get('value')
return converted_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_aws_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 tags_action(client, resource_id, tags, action='create', check_mode=False):
"""Create or Delete tags for 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, 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_routes(client, vpc_peering_id, cidr, route_table_ids,
check_mode=False):
"""Update routes in multiple route tables.
Args:
client (botocore.client.EC2): Boto3 client.
vpc_peering_id (str): The vpc peering connection id.
cidr (str): The dest cidr block.
example.. 0.0.0.0/0
route_table_ids (list): List of route table 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_peering_id = 'vpx-1234567'
>>> cidr = '0.0.0.0/0'
>>> route_table_ids = ['rtb-1234567', 'rtb-7654321']
[
True,
True,
''
]
Returns:
Tuple (bool, bool, str)
"""
success = False
changed = False
err_msg = ''
for route_table_id in route_table_ids:
params = {
'RouteTableId': route_table_id,
'DestinationCidrBlock': cidr,
'VpcPeeringConnectionId': vpc_peering_id,
'DryRun': check_mode,
}
try:
completed = client.create_route(**params)
if completed.get('Return') == True:
success, changed = True, True
except botocore.exceptions.ClientError, e:
err_msg = str(e)
if e.response['Error']['Code'] == 'DryRunOperation':
success = True
err_msg = e.message
elif re.search('RouteAlreadyExists', err_msg):
success = True
return success, changed, err_msg
def pre_update_routes(client, peer_info, accepter_routes=None,
requester_routes=None, check_mode=False):
"""Does the pre work before updating a route.
Args:
client (botocore.client.EC2): Boto3 client.
peer_info (dict): This contains the output of describe_peering_connections
Kwargs:
accepter_routes (list): list of route table ids that you want
to add routes to the cidr that belongs to the peer of the newly
created peering_connection
default=None
requester_routes (list): list of route table ids that you want
to add routes to the cidr that belongs to the vpc that is
initiating the creation of the newly created peering_connection
default=None
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_peer_info = describe_peering_connections(
client, vpc_peering_id='vpx-1234567'
)
>>> accepter_routes = ['rtb-1234567', 'rtb-7654321']
>>> pre_update_routes(client, vpc_peer_info[0], accepter_routes)
[
True,
True,
''
]
Returns:
Tuple (bool, bool, str)
"""
success = False
changed = False
err_msg = 'Need to pass either accepter_routes or requester_routes.'
vpc_peering_id = peer_info['vpc_peering_connection_id']
if accepter_routes and peer_info['accepter_vpc_info'].get('cidr_block', None):
routes = accepter_routes
cidr = peer_info['accepter_vpc_info']['cidr_block']
success, changed, err_msg = (
update_routes(client, vpc_peering_id, cidr, routes)
)
if requester_routes and peer_info['requester_vpc_info'].get('cidr_block', None):
routes = requester_routes
cidr = peer_info['requester_vpc_info']['cidr_block']
success, changed, err_msg = (
update_routes(client, vpc_peering_id, cidr, routes)
)
return success, changed, err_msg
def update_tags(client, resource_id, tags, check_mode=False):
"""Update tags for an amazon resource. This will delete any tag that is
not part of the tags parameter and update|create.
Args:
resource_id (str): The Amazon resource id.
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 = ''
find_success, find_err, current_tags = (
find_tags(client, resource_id, check_mode=check_mode)
)
if find_success:
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=False
)
)
if not delete_success:
return delete_success, delete_msg
if tags_to_update:
tags = recreate_tags_from_list(tags_to_update)
if not tags:
return delete_success, delete_msg
if tags:
create_success, create_msg = (
tags_action(
client, resource_id, tags, action='create',
check_mode=False
)
)
return create_success, create_msg
return success, err_msg
def runner(client, state, params):
"""Generic function that will handle the calls to create, delete, reject and accept.
This function should not be called directly, except by the run function.
Args:
client (botocore.client.EC2): Boto3 client.
state (str): valid states. [accept, reject, absent, present].
params (dict): Params contains the parameters to perform the aws request.
Kwargs:
boto3_profile (str): The name of the boto3 profile to use when
making a cross account request.
default=None
Basic Usage:
>>> client = boto3.client('ec2')
>>> state = 'accept'
>>> vpc_peering_id = 'pcx-12345'
>>> params = {'VpcPeeringConnectionId': vpc_peering_id}
>>> runner(client, state, params)
[
True,
False,
"",
{
"status": {
"message": "Active",
"code": "active"
},
"tags": [
{
"value": "web",
"key": "service"
},
{
"value": "Shaolin Allen",
"key": "Name"
},
{
"value": "development",
"key": "env"
}
],
"accepter_vpc_info": {
"owner_id": "12345678910",
"vpc_id": "vpc-12345678",
"cidr_block": "172.31.0.0/16"
},
"vpc_peering_connection_id": "pcx-12345678",
"requester_vpc_info": {
"owner_id": "12345678910",
"vpc_id": "vpc-12345678",
"cidr_block": "10.100.0.0/16"
}
}
]
Return:
Tuple (bool, bool, str, dict)
"""
success = False
changed = False
err_msg = ''
result = dict()
invocations = {
'accept': client.accept_vpc_peering_connection,
'reject': client.reject_vpc_peering_connection,
'absent': client.delete_vpc_peering_connection,
'present': client.create_vpc_peering_connection,
}
if state not in ['accept', 'reject', 'absent', 'present']:
return success, changed, err_msg, result
try:
result = invocations[state](**params)
response = result.pop('ResponseMetadata')
if result.get('VpcPeeringConnection', {}):
result = result.pop('VpcPeeringConnection')
if response['HTTPStatusCode'] == 200:
changed = True
success = True
else:
err_msg = "Failure occured, please check aws console"
result = convert_to_lower(result)
except botocore.exceptions.ClientError, e:
if e.response['Error']['Code'] == 'DryRunOperation':
success = True
err_msg = e.message
else:
err_msg = str(e)
return success, changed, err_msg, result
def run(client, vpc_peering_id, state, check_mode=False):
"""Generic function for ensuring the various states for a peering connection.
This function is called by create, accept, reject, and delete.
Args:
client (botocore.client.EC2): Boto3 client.
vpc_peering_id (str): The vpc peering connection id.
state (str): valid states. [accept, reject, absent, present].
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')
>>> state = 'accept'
>>> vpc_peering_id = 'pcx-12345'
>>> run(client, state, params)