-
Notifications
You must be signed in to change notification settings - Fork 341
/
ec2.py
1818 lines (1371 loc) · 69.6 KB
/
ec2.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
# -*- coding: utf-8 -*-
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# Copyright (c), Michael DeHaan <[email protected]>, 2012-2013
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
This module adds helper functions for various EC2 specific services.
It also includes a large number of imports for functions which historically
lived here. Most of these functions were not specific to EC2, they ended
up in this module because "that's where the AWS code was" (originally).
"""
import copy
import re
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
import ansible.module_utils.common.warnings as ansible_warnings
from ansible.module_utils.ansible_release import __version__
# Used to live here, moved into ansible.module_utils.common.dict_transformations
from ansible.module_utils.common.dict_transformations import _camel_to_snake # pylint: disable=unused-import
from ansible.module_utils.common.dict_transformations import _snake_to_camel # pylint: disable=unused-import
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict # pylint: disable=unused-import
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict # pylint: disable=unused-import
from ansible.module_utils.six import integer_types
from ansible.module_utils.six import string_types
# Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.arn
from .arn import is_outpost_arn as is_outposts_arn # pylint: disable=unused-import
from .arn import validate_aws_arn
# Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.botocore
from .botocore import HAS_BOTO3 # pylint: disable=unused-import
from .botocore import boto3_conn # pylint: disable=unused-import
from .botocore import boto3_inventory_conn # pylint: disable=unused-import
from .botocore import boto_exception # pylint: disable=unused-import
from .botocore import get_aws_connection_info # pylint: disable=unused-import
from .botocore import get_aws_region # pylint: disable=unused-import
from .botocore import is_boto3_error_code
from .botocore import paginated_query_with_retries
from .errors import AWSErrorHandler
# Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.exceptions
from .exceptions import AnsibleAWSError # pylint: disable=unused-import
from .iam import list_iam_instance_profiles
# Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.modules
# The names have been changed in .modules to better reflect their applicability.
from .modules import _aws_common_argument_spec as aws_common_argument_spec # pylint: disable=unused-import
from .modules import aws_argument_spec as ec2_argument_spec # pylint: disable=unused-import
# Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.policy
from .policy import _py3cmp as py3cmp # pylint: disable=unused-import
from .policy import compare_policies # pylint: disable=unused-import
# Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.retries
from .retries import AWSRetry # pylint: disable=unused-import
# Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.tagging
from .tagging import ansible_dict_to_boto3_tag_list # pylint: disable=unused-import
from .tagging import boto3_tag_list_to_ansible_dict # pylint: disable=unused-import
from .tagging import boto3_tag_specifications
from .tagging import compare_aws_tags # pylint: disable=unused-import
# Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.transformation
from .transformation import ansible_dict_to_boto3_filter_list # pylint: disable=unused-import
from .transformation import map_complex_type # pylint: disable=unused-import
try:
import botocore
except ImportError:
pass # Handled by HAS_BOTO3
class AnsibleEC2Error(AnsibleAWSError):
pass
EC2TagSpecifications = Dict[str, Union[str, List[Dict[str, str]]]]
@AWSRetry.jittered_backoff()
def describe_availability_zones(
client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Union[str, List[Dict[str, str]]]]]:
# The paginator does not exist for `describe_availability_zones()`
return client.describe_availability_zones(**params)["AvailabilityZones"]
@AWSRetry.jittered_backoff()
def describe_regions(
client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, str]]:
# The paginator does not exist for `describe_regions()`
return client.describe_regions(**params)["Regions"]
# EC2 VPC Subnets
class EC2VpcSubnetErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidSubnetID.NotFound")
@EC2VpcSubnetErrorHandler.deletion_error_handler("delete subnet")
@AWSRetry.jittered_backoff()
def delete_subnet(client, subnet_id: str) -> bool:
client.delete_subnet(SubnetId=subnet_id)
return True
@EC2VpcSubnetErrorHandler.list_error_handler("describe subnets", [])
@AWSRetry.jittered_backoff()
def describe_subnets(
client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Any]]:
paginator = client.get_paginator("describe_subnets")
return paginator.paginate(**params).build_full_result()["Subnets"]
@EC2VpcSubnetErrorHandler.common_error_handler("create subnet")
@AWSRetry.jittered_backoff()
def create_subnet(client, **params: Dict[str, Union[str, bool, int, EC2TagSpecifications]]) -> Dict[str, Any]:
return client.create_subnet(**params)["Subnet"]
@EC2VpcSubnetErrorHandler.common_error_handler("modify subnet")
@AWSRetry.jittered_backoff()
def modify_subnet_attribute(client, subnet_id: str, **params: Dict[str, Union[str, int, Dict[str, bool]]]) -> bool:
client.modify_subnet_attribute(SubnetId=subnet_id, **params)
return True
@EC2VpcSubnetErrorHandler.common_error_handler("disassociate subnet cidr block")
@AWSRetry.jittered_backoff()
def disassociate_subnet_cidr_block(client, association_id: str) -> Dict[str, Union[str, Dict[str, str]]]:
return client.disassociate_subnet_cidr_block(AssociationId=association_id)["Ipv6CidrBlockAssociation"]
@EC2VpcSubnetErrorHandler.common_error_handler("associate subnet cidr block")
@AWSRetry.jittered_backoff()
def associate_subnet_cidr_block(
client, subnet_id: str, **params: Dict[str, Union[str, int]]
) -> Dict[str, Union[str, Dict[str, str]]]:
return client.associate_subnet_cidr_block(SubnetId=subnet_id, **params)["Ipv6CidrBlockAssociation"]
# EC2 VPC Route table
class EC2VpcRouteTableErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidRouteTableID.NotFound")
@EC2VpcRouteTableErrorHandler.list_error_handler("describe route tables", [])
@AWSRetry.jittered_backoff()
def describe_route_tables(
client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Any]]:
paginator = client.get_paginator("describe_route_tables")
return paginator.paginate(**params).build_full_result()["RouteTables"]
@EC2VpcRouteTableErrorHandler.common_error_handler("disassociate route table")
@AWSRetry.jittered_backoff()
def disassociate_route_table(client, association_id: str) -> bool:
client.disassociate_route_table(AssociationId=association_id)
return True
@EC2VpcRouteTableErrorHandler.common_error_handler("associate route table")
@AWSRetry.jittered_backoff()
def associate_route_table(
client, route_table_id: str, **params: Dict[str, str]
) -> Dict[str, Union[str, Dict[str, str]]]:
return client.associate_route_table(RouteTableId=route_table_id, **params)
@EC2VpcRouteTableErrorHandler.common_error_handler("enable vgw route propagation")
@AWSRetry.jittered_backoff()
def enable_vgw_route_propagation(client, gateway_id: str, route_table_id: str) -> bool:
client.enable_vgw_route_propagation(RouteTableId=route_table_id, GatewayId=gateway_id)
return True
@EC2VpcRouteTableErrorHandler.deletion_error_handler("delete route table")
@AWSRetry.jittered_backoff()
def delete_route_table(client, route_table_id: str) -> bool:
client.delete_route_table(RouteTableId=route_table_id)
return True
@EC2VpcRouteTableErrorHandler.common_error_handler("create route table")
@AWSRetry.jittered_backoff()
def create_route_table(client, vpc_id: str, tags: Optional[Dict[str, str]]) -> Dict[str, Any]:
params = {"VpcId": vpc_id}
if tags:
params["TagSpecifications"] = boto3_tag_specifications(tags, types="route-table")
return client.create_route_table(**params)["RouteTable"]
# EC2 VPC Route table Route
class EC2VpcRouteTableRouteErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidRoute.NotFound")
@EC2VpcRouteTableRouteErrorHandler.deletion_error_handler("delete route")
@AWSRetry.jittered_backoff()
def delete_route(client, route_table_id: str, **params: Dict[str, str]) -> bool:
client.delete_route(RouteTableId=route_table_id, **params)
return True
@EC2VpcRouteTableRouteErrorHandler.common_error_handler("replace route")
@AWSRetry.jittered_backoff()
def replace_route(client, route_table_id: str, **params: Dict[str, Union[str, bool]]) -> bool:
client.replace_route(RouteTableId=route_table_id, **params)
return True
@EC2VpcRouteTableRouteErrorHandler.common_error_handler("create route")
@AWSRetry.jittered_backoff()
def create_route(client, route_table_id: str, **params: Dict[str, str]) -> bool:
return client.create_route(RouteTableId=route_table_id, **params)["Return"]
# EC2 VPC
class EC2VpcErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidVpcID.NotFound")
@EC2VpcErrorHandler.list_error_handler("describe vpcs", [])
@AWSRetry.jittered_backoff()
def describe_vpcs(
client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Any]]:
paginator = client.get_paginator("describe_vpcs")
return paginator.paginate(**params).build_full_result()["Vpcs"]
@EC2VpcErrorHandler.deletion_error_handler("delete vpc")
@AWSRetry.jittered_backoff()
def delete_vpc(client, vpc_id: str) -> bool:
client.delete_vpc(VpcId=vpc_id)
return True
@EC2VpcErrorHandler.common_error_handler("describe vpc attribute")
@AWSRetry.jittered_backoff()
def describe_vpc_attribute(client, vpc_id: str, attribute: str) -> Dict[str, Any]:
# The paginator does not exist for `describe_vpc_attribute`
return client.describe_vpc_attribute(VpcId=vpc_id, Attribute=attribute)
@EC2VpcErrorHandler.common_error_handler("modify vpc attribute")
@AWSRetry.jittered_backoff()
def modify_vpc_attribute(client, vpc_id: str, **params: Dict[str, Union[str, Dict[str, bool]]]) -> bool:
client.modify_vpc_attribute(VpcId=vpc_id, **params)
return True
@EC2VpcErrorHandler.common_error_handler("create vpc")
@AWSRetry.jittered_backoff()
def create_vpc(client, **params: Dict[str, Union[str, bool, int, EC2TagSpecifications]]) -> Dict[str, Any]:
return client.create_vpc(**params)["Vpc"]
@EC2VpcErrorHandler.common_error_handler("associate vpc cidr block")
@AWSRetry.jittered_backoff()
def associate_vpc_cidr_block(client, vpc_id: str, **params: Dict[str, Union[str, bool, int]]) -> Dict[str, Any]:
return client.associate_vpc_cidr_block(VpcId=vpc_id, **params)
@EC2VpcErrorHandler.common_error_handler("disassociate vpc cidr block")
@AWSRetry.jittered_backoff()
def disassociate_vpc_cidr_block(client, association_id: str) -> Dict[str, Any]:
return client.disassociate_vpc_cidr_block(AssociationId=association_id)
# EC2 VPC Peering Connection
class EC2VpcPeeringErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidVpcPeeringConnectionID.NotFound")
@EC2VpcPeeringErrorHandler.list_error_handler("describe vpc peering", [])
@AWSRetry.jittered_backoff()
def describe_vpc_peering_connections(client, **params: Dict[str, Any]) -> List[Dict[str, Any]]:
paginator = client.get_paginator("describe_vpc_peering_connections")
return paginator.paginate(**params).build_full_result()["VpcPeeringConnections"]
@EC2VpcSubnetErrorHandler.common_error_handler("create vpc peering")
@AWSRetry.jittered_backoff()
def create_vpc_peering_connection(
client, **params: Dict[str, Union[str, bool, int, EC2TagSpecifications]]
) -> Dict[str, Any]:
return client.create_vpc_peering_connection(**params)["VpcPeeringConnection"]
@EC2VpcSubnetErrorHandler.deletion_error_handler("delete vpc peering")
@AWSRetry.jittered_backoff()
def delete_vpc_peering_connection(client, peering_id: str) -> bool:
client.delete_vpc_peering_connection(VpcPeeringConnectionId=peering_id)
return True
@EC2VpcSubnetErrorHandler.deletion_error_handler("accept vpc peering")
@AWSRetry.jittered_backoff()
def accept_vpc_peering_connection(client, peering_id: str) -> bool:
client.accept_vpc_peering_connection(VpcPeeringConnectionId=peering_id)
return True
@EC2VpcSubnetErrorHandler.deletion_error_handler("reject vpc peering")
@AWSRetry.jittered_backoff()
def reject_vpc_peering_connection(client, peering_id: str) -> bool:
client.reject_vpc_peering_connection(VpcPeeringConnectionId=peering_id)
return True
# EC2 vpn
class EC2VpnErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code(["InvalidVpnConnectionID.NotFound", "InvalidRoute.NotFound"])
@EC2VpcErrorHandler.list_error_handler("describe vpn connections", [])
@AWSRetry.jittered_backoff()
def describe_vpn_connections(client, **params: Dict[str, Any]) -> List[Dict[str, Any]]:
# The paginator does not exist for `describe_vpn_connections`
return client.describe_vpn_connections(**params)["VpnConnections"]
@EC2VpcErrorHandler.common_error_handler("create vpn connection route")
@AWSRetry.jittered_backoff()
def create_vpn_connection_route(client, vpn_connection_id: str, route: Dict[str, Any]) -> bool:
client.create_vpn_connection_route(VpnConnectionId=vpn_connection_id, DestinationCidrBlock=route)
return True
@EC2VpcErrorHandler.deletion_error_handler("delete vpn connection route")
@AWSRetry.jittered_backoff()
def delete_vpn_connection_route(client, vpn_connection_id: str, route: Dict[str, Any]) -> bool:
client.delete_vpn_connection_route(VpnConnectionId=vpn_connection_id, DestinationCidrBlock=route)
return True
@EC2VpcErrorHandler.common_error_handler("create vpn connection")
@AWSRetry.jittered_backoff()
def create_vpn_connection(client, **params: Dict[str, Any]) -> Dict[str, Any]:
return client.create_vpn_connection(**params)["VpnConnection"]
@EC2VpcErrorHandler.deletion_error_handler("delete vpn connection")
@AWSRetry.jittered_backoff()
def delete_vpn_connection(client, vpn_connection_id: str) -> Dict[str, Any]:
client.delete_vpn_connection(VpnConnectionId=vpn_connection_id)
return True
# EC2 Internet Gateway
class EC2InternetGatewayErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidInternetGatewayID.NotFound")
@EC2InternetGatewayErrorHandler.list_error_handler("describe internet gateways")
@AWSRetry.jittered_backoff()
def describe_internet_gateways(
client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Any]]:
paginator = client.get_paginator("describe_internet_gateways")
return paginator.paginate(**params).build_full_result()["InternetGateways"]
@EC2InternetGatewayErrorHandler.common_error_handler("create internet gateway")
@AWSRetry.jittered_backoff()
def create_internet_gateway(client, tags: Optional[List[Dict[str, str]]]) -> Dict[str, Any]:
params = {}
if tags:
params["TagSpecifications"] = boto3_tag_specifications(tags, types="internet-gateway")
return client.create_internet_gateway(**params)["InternetGateway"]
@EC2InternetGatewayErrorHandler.common_error_handler("detach internet gateway")
@AWSRetry.jittered_backoff()
def detach_internet_gateway(client, internet_gateway_id: str, vpc_id: str) -> bool:
client.detach_internet_gateway(InternetGatewayId=internet_gateway_id, VpcId=vpc_id)
return True
@EC2InternetGatewayErrorHandler.common_error_handler("attach internet gateway")
@AWSRetry.jittered_backoff()
def attach_internet_gateway(client, internet_gateway_id: str, vpc_id: str) -> bool:
client.attach_internet_gateway(InternetGatewayId=internet_gateway_id, VpcId=vpc_id)
return True
@EC2InternetGatewayErrorHandler.deletion_error_handler("delete internet gateway")
@AWSRetry.jittered_backoff()
def delete_internet_gateway(client, internet_gateway_id: str) -> bool:
client.delete_internet_gateway(InternetGatewayId=internet_gateway_id)
return True
# EC2 NAT Gateway
class EC2NatGatewayErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidNatGatewayID.NotFound")
@EC2NatGatewayErrorHandler.list_error_handler("describe nat gateways", [])
@AWSRetry.jittered_backoff()
def describe_nat_gateways(
client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Any]]:
paginator = client.get_paginator("describe_nat_gateways")
return paginator.paginate(**params).build_full_result()["NatGateways"]
@EC2NatGatewayErrorHandler.deletion_error_handler("delete nat gateway")
@AWSRetry.jittered_backoff()
def delete_nat_gateway(client, nat_gateway_id: str) -> bool:
client.delete_nat_gateway(NatGatewayId=nat_gateway_id)
return True
@EC2NatGatewayErrorHandler.common_error_handler("create nat gateway")
@AWSRetry.jittered_backoff()
def create_nat_gateway(
client, **params: Dict[str, Union[str, bool, int, EC2TagSpecifications, List[str]]]
) -> Dict[str, Any]:
return client.create_nat_gateway(**params)["NatGateway"]
# EC2 Elastic IP
class EC2ElasticIPErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidAddress.NotFound")
@EC2ElasticIPErrorHandler.list_error_handler("describe addresses", [])
@AWSRetry.jittered_backoff()
def describe_addresses(
client, **params: Dict[str, Union[List[str], List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Union[str, List[Dict[str, str]]]]]:
# The paginator does not exist for 'describe_addresses()'
return client.describe_addresses(**params)["Addresses"]
@EC2ElasticIPErrorHandler.common_error_handler("release address")
@AWSRetry.jittered_backoff()
def release_address(client, allocation_id: str, network_border_group: Optional[str] = None) -> bool:
params = {"AllocationId": allocation_id}
if network_border_group:
params["NetworkBorderGroup"] = network_border_group
client.release_address(**params)
return True
@EC2ElasticIPErrorHandler.common_error_handler("associate address")
@AWSRetry.jittered_backoff()
def associate_address(client, **params: Dict[str, Union[str, bool]]) -> Dict[str, str]:
return client.associate_address(**params)
@EC2ElasticIPErrorHandler.common_error_handler("disassociate address")
@AWSRetry.jittered_backoff()
def disassociate_address(client, association_id: str) -> bool:
client.disassociate_address(AssociationId=association_id)
return True
@EC2ElasticIPErrorHandler.common_error_handler("allocate address")
@AWSRetry.jittered_backoff()
def allocate_address(client, **params: Dict[str, Union[str, EC2TagSpecifications]]) -> Dict[str, str]:
return client.allocate_address(**params)
# EC2 VPC Endpoints
class EC2VpcEndpointsErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code(["InvalidVpcEndpoint.NotFound", "InvalidVpcEndpointId.NotFound"])
@EC2VpcEndpointsErrorHandler.list_error_handler("describe vpc endpoints", [])
@AWSRetry.jittered_backoff()
def describe_vpc_endpoints(
client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
) -> Dict[str, Any]:
paginator = client.get_paginator("describe_vpc_endpoints")
return paginator.paginate(**params).build_full_result()["VpcEndpoints"]
@EC2VpcEndpointsErrorHandler.deletion_error_handler("delete vpc endpoints")
@AWSRetry.jittered_backoff()
def delete_vpc_endpoints(client, vpc_endpoint_ids: str) -> List[Dict[str, Union[str, Dict[str, str]]]]:
result = client.delete_vpc_endpoints(VpcEndpointIds=vpc_endpoint_ids)
return result.get("Unsuccessful", [])
@EC2ElasticIPErrorHandler.common_error_handler("create vpc endpoint")
@AWSRetry.jittered_backoff()
def create_vpc_endpoint(
client,
**params: Dict[
str, Union[str, bool, List[str], Dict[str, Union[str, bool]], List[Dict[str, str]], EC2TagSpecifications]
],
) -> Dict[str, Any]:
return client.create_vpc_endpoint(**params)["VpcEndpoint"]
# EC2 VPC Endpoint Services
class EC2VpcEndpointServiceErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidServiceName")
@EC2VpcEndpointServiceErrorHandler.list_error_handler("describe vpc endpoint services", default_value={})
@AWSRetry.jittered_backoff()
def describe_vpc_endpoint_services(
client, filters: Optional[List[Dict[str, Any]]] = None, service_names: Optional[List[str]] = None
) -> Dict[str, Any]:
"""
Wrap call to the AWS API describe_vpc_endpoint_services (used to describe available
services to which you can create a VPC endpoint.)
Parameters:
client: The boto3 client.
filters: Optional filters to pass to the API.
service_names: the service names.
Returns:
results: A dictionnary with keys 'ServiceNames' and 'ServiceDetails'
"""
paginator = client.get_paginator("describe_vpc_endpoint_services")
params: dict[str, Any] = {}
if filters:
params["Filters"] = filters
if service_names:
params["ServiceNames"] = service_names
results = paginator.paginate(**params).build_full_result()
return results
# EC2 VPC DHCP Option
class EC2VpcDhcpOptionErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code(["InvalidDhcpOptionsID.NotFound", "InvalidDhcpOptionID.NotFound"])
@EC2VpcDhcpOptionErrorHandler.list_error_handler("describe dhcp options", [])
@AWSRetry.jittered_backoff()
def describe_dhcp_options(
client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Any]]:
paginator = client.get_paginator("describe_dhcp_options")
return paginator.paginate(**params).build_full_result()["DhcpOptions"]
@EC2VpcDhcpOptionErrorHandler.deletion_error_handler("delete dhcp options")
@AWSRetry.jittered_backoff()
def delete_dhcp_options(client, dhcp_options_id: str) -> bool:
client.delete_dhcp_options(DhcpOptionsId=dhcp_options_id)
return True
@EC2VpcDhcpOptionErrorHandler.common_error_handler("associate dhcp options")
@AWSRetry.jittered_backoff()
def associate_dhcp_options(client, dhcp_options_id: str, vpc_id: str) -> bool:
client.associate_dhcp_options(DhcpOptionsId=dhcp_options_id, VpcId=vpc_id)
return True
@EC2VpcDhcpOptionErrorHandler.common_error_handler("create dhcp options")
@AWSRetry.jittered_backoff()
def create_dhcp_options(
client, **params: Dict[str, Union[Dict[str, Union[str, List[str]]], EC2TagSpecifications]]
) -> Dict[str, Any]:
return client.create_dhcp_options(**params)["DhcpOptions"]
# EC2 vpn Gateways
class EC2VpnGatewaysErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code(["InvalidVpnGatewayID.NotFound", "InvalidVpnGatewayState"])
@EC2VpnGatewaysErrorHandler.list_error_handler("describe vpn gateways", [])
@AWSRetry.jittered_backoff()
def describe_vpn_gateways(
client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Any]]:
return client.describe_vpn_gateways(**params)["VpnGateways"]
@EC2VpnGatewaysErrorHandler.common_error_handler("create vpn gateway")
@AWSRetry.jittered_backoff(catch_extra_error_codes=["VpnGatewayLimitExceeded"])
def create_vpn_gateway(
client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
) -> Dict[str, Any]:
return client.create_vpn_gateway(**params)["VpnGateway"]
@EC2VpnGatewaysErrorHandler.deletion_error_handler("delete vpn gateway")
@AWSRetry.jittered_backoff()
def delete_vpn_gateway(client, vpn_gateway_id: str) -> bool:
client.delete_vpn_gateway(VpnGatewayId=vpn_gateway_id)
return True
@EC2VpnGatewaysErrorHandler.common_error_handler("attach vpn gateway")
@AWSRetry.jittered_backoff()
def attach_vpn_gateway(client, vpc_id: str, vpn_gateway_id: str) -> bool:
client.attach_vpn_gateway(VpcId=vpc_id, VpnGatewayId=vpn_gateway_id)
return True
@EC2VpnGatewaysErrorHandler.common_error_handler("detach vpn gateway")
@AWSRetry.jittered_backoff()
def detach_vpn_gateway(client, vpc_id: str, vpn_gateway_id: str) -> bool:
client.detach_vpn_gateway(VpcId=vpc_id, VpnGatewayId=vpn_gateway_id)
return True
# EC2 Volumes
class EC2VolumeErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidVolume.NotFound")
@EC2VolumeErrorHandler.list_error_handler("describe volumes", [])
@AWSRetry.jittered_backoff()
def describe_volumes(
client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Any]]:
paginator = client.get_paginator("describe_volumes")
return paginator.paginate(**params).build_full_result()["Volumes"]
@EC2VolumeErrorHandler.deletion_error_handler("delete volume")
@AWSRetry.jittered_backoff()
def delete_volume(client, volume_id: str) -> bool:
client.delete_volume(VolumeId=volume_id)
return True
@EC2VolumeErrorHandler.common_error_handler("modify volume")
@AWSRetry.jittered_backoff()
def modify_volume(client, **params: Dict[str, Union[str, bool, int]]) -> Dict[str, Any]:
return client.modify_volume(**params)["VolumeModification"]
@EC2VolumeErrorHandler.common_error_handler("modify volume")
@AWSRetry.jittered_backoff()
def create_volume(client, **params: Dict[str, Union[str, bool, int, EC2TagSpecifications]]) -> Dict[str, Any]:
return client.create_volume(**params)
@EC2VolumeErrorHandler.common_error_handler("attach volume")
@AWSRetry.jittered_backoff()
def attach_volume(client, device: str, instance_id: str, volume_id: str) -> Dict[str, Any]:
return client.attach_volume(Device=device, InstanceId=instance_id, VolumeId=volume_id)
@EC2VolumeErrorHandler.common_error_handler("attach volume")
@AWSRetry.jittered_backoff()
def detach_volume(client, volume_id: str, **params: Dict[str, Union[str, bool]]) -> Dict[str, Any]:
return client.detach_volume(VolumeId=volume_id, **params)
# EC2 Instance
EC2_INSTANCE_CATCH_EXTRA_CODES = [
"IncorrectState",
"InsuffienctInstanceCapacity",
"InvalidInstanceID.NotFound",
]
class EC2InstanceErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidInstanceID.NotFound")
@EC2InstanceErrorHandler.list_error_handler("describe instances", [])
@AWSRetry.jittered_backoff()
def describe_instances(
client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Any]]:
paginator = client.get_paginator("describe_instances")
return paginator.paginate(**params).build_full_result()["Reservations"]
@EC2InstanceErrorHandler.common_error_handler("modify instance attribute")
@AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
def modify_instance_attribute(
client,
instance_id: str,
**params: Dict[
str,
Union[
str,
List[str],
Dict[str, str],
Dict[str, bool],
Dict[str, bytes],
Dict[str, Union[str, Dict[str, Union[str, bool]]]],
],
],
) -> bool:
client.modify_instance_attribute(InstanceId=instance_id, **params)
return True
@EC2InstanceErrorHandler.list_error_handler("terminate instances", [])
@AWSRetry.jittered_backoff()
def terminate_instances(client, instance_ids: List[str]) -> List[Dict[str, Any]]:
return client.terminate_instances(InstanceIds=instance_ids)["TerminatingInstances"]
@EC2InstanceErrorHandler.list_error_handler("stop instances", [])
@AWSRetry.jittered_backoff()
def stop_instances(
client, instance_ids: List[str], **params: Dict[str, Union[bool, List[str]]]
) -> List[Dict[str, Any]]:
return client.stop_instances(InstanceIds=instance_ids, **params)["StoppingInstances"]
@EC2InstanceErrorHandler.list_error_handler("start instances", [])
@AWSRetry.jittered_backoff()
def start_instances(
client, instance_ids: List[str], **params: Dict[str, Union[str, List[str]]]
) -> List[Dict[str, Any]]:
return client.start_instances(InstanceIds=instance_ids, **params)["StartingInstances"]
@EC2InstanceErrorHandler.common_error_handler("run instances")
@AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
def run_instances(client, **params: Dict[str, Any]) -> Dict[str, Any]:
return client.run_instances(**params)
@EC2InstanceErrorHandler.common_error_handler("describe instance attribute")
@AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
def describe_instance_attribute(client, instance_id: str, attribute: str) -> Dict[str, Any]:
# The paginator does not exist for describe_instance_attribute()
return client.describe_instance_attribute(InstanceId=instance_id, Attribute=attribute)
@EC2InstanceErrorHandler.common_error_handler("describe instance status")
@AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
def describe_instance_status(
client, **params: Dict[str, Union[List[str], bool, int, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Any]]:
paginator = client.get_paginator("describe_instance_status")
return paginator.paginate(**params).build_full_result()["InstanceStatuses"]
@EC2InstanceErrorHandler.common_error_handler("modify instance metadata options")
@AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
def modify_instance_metadata_options(
client, instance_id: str, **params: Dict[str, Union[str, int]]
) -> Dict[str, Union[int, str]]:
return client.modify_instance_metadata_options(InstanceId=instance_id, **params)["InstanceMetadataOptions"]
@EC2InstanceErrorHandler.common_error_handler("describe iam instance profile associations")
@AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
def describe_iam_instance_profile_associations(
client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
) -> Dict[str, Any]:
paginator = client.get_paginator("describe_iam_instance_profile_associations")
return paginator.paginate(**params).build_full_result()["IamInstanceProfileAssociations"]
@EC2InstanceErrorHandler.common_error_handler("replace iam instance profile association")
@AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
def replace_iam_instance_profile_association(
client, iam_instance_profile: Dict[str, str], association_id: str
) -> Dict[str, Union[int, str]]:
return client.replace_iam_instance_profile_association(
IamInstanceProfile=iam_instance_profile, AssociationId=association_id
)["IamInstanceProfileAssociation"]
@EC2InstanceErrorHandler.common_error_handler("associate iam instance profile")
@AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
def associate_iam_instance_profile(client, iam_instance_profile: Dict[str, str], instance_id: str) -> Dict[str, Any]:
return client.associate_iam_instance_profile(IamInstanceProfile=iam_instance_profile, InstanceId=instance_id)[
"IamInstanceProfileAssociation"
]
# EC2 Key
class EC2KeyErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidKeyPair.NotFound")
@EC2KeyErrorHandler.list_error_handler("describe key pairs", [])
@AWSRetry.jittered_backoff()
def describe_key_pairs(
client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Any]]:
# The paginator does not exist for `describe_key_pairs()`
return client.describe_key_pairs(**params)["KeyPairs"]
@EC2KeyErrorHandler.common_error_handler("import key pair")
@AWSRetry.jittered_backoff()
def import_key_pair(
client, **params: Dict[str, Union[str, bytes, EC2TagSpecifications]]
) -> Dict[str, Union[str, List[Dict[str, str]]]]:
return client.import_key_pair(**params)
@EC2KeyErrorHandler.common_error_handler("create key pair")
@AWSRetry.jittered_backoff()
def create_key_pair(
client, **params: Dict[str, Union[str, EC2TagSpecifications]]
) -> Dict[str, Union[str, List[Dict[str, str]]]]:
return client.create_key_pair(**params)
@EC2KeyErrorHandler.deletion_error_handler("delete key pair")
@AWSRetry.jittered_backoff()
def delete_key_pair(client, key_name: Optional[str] = None, key_id: Optional[str] = None) -> bool:
params = {}
if key_name:
params["KeyName"] = key_name
if key_id:
params["KeyPairId"] = key_id
client.delete_key_pair(**params)
return True
# EC2 Image
class EC2ImageErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidAMIID.Unavailable")
@EC2ImageErrorHandler.list_error_handler("describe images", [])
@AWSRetry.jittered_backoff()
def describe_images(
client, **params: Dict[str, Union[List[str], bool, int, List[Dict[str, Union[str, List[str]]]]]]
) -> List[Dict[str, Any]]:
# 'DescribeImages' can be paginated depending on the boto3 version
if client.can_paginate("describe_images"):
paginator = client.get_paginator("describe_images")
return paginator.paginate(**params).build_full_result()["Images"]
else:
return client.describe_images(**params)["Images"]
@EC2ImageErrorHandler.list_error_handler("describe image attribute", {})
@AWSRetry.jittered_backoff()
def describe_image_attribute(client, image_id: str, attribute: str) -> Optional[Dict[str, Any]]:
# The paginator does not exist for `describe_image_attribute()`
return client.describe_image_attribute(Attribute=attribute, ImageId=image_id)
@EC2ImageErrorHandler.deletion_error_handler("deregister image")
@AWSRetry.jittered_backoff()
def deregister_image(client, image_id: str) -> bool:
client.deregister_image(ImageId=image_id)
return True
@EC2ImageErrorHandler.common_error_handler("modify image attribute")
@AWSRetry.jittered_backoff()
def modify_image_attribute(client, image_id: str, **params: Dict[str, Any]) -> bool:
client.modify_image_attribute(ImageId=image_id, **params)
return True
@EC2ImageErrorHandler.common_error_handler("create image")
@AWSRetry.jittered_backoff()
def create_image(client, **params: Dict[str, Any]) -> Dict[str, str]:
return client.create_image(**params)
@EC2ImageErrorHandler.common_error_handler("register image")
@AWSRetry.jittered_backoff()
def register_image(client, **params: Dict[str, Any]) -> Dict[str, str]:
return client.register_image(**params)
# EC2 Snapshot
class EC2SnapshotErrorHandler(AWSErrorHandler):
_CUSTOM_EXCEPTION = AnsibleEC2Error
@classmethod
def _is_missing(cls):
return is_boto3_error_code("InvalidSnapshot.NotFound")
@EC2SnapshotErrorHandler.deletion_error_handler("delete snapshot")
@AWSRetry.jittered_backoff()
def delete_snapshot(client, snapshot_id: str) -> bool:
client.delete_snapshot(SnapshotId=snapshot_id)
return True
@EC2SnapshotErrorHandler.list_error_handler("describe snapshots", [])
@AWSRetry.jittered_backoff()
def describe_snapshots(
client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
) -> Dict[str, Any]:
# We do not use paginator here because the `ec2_snapshot_info` module excepts the NextToken to be returned
return client.describe_snapshots(**params)
@EC2SnapshotErrorHandler.common_error_handler("describe snapshot attribute")
@AWSRetry.jittered_backoff()
def describe_snapshot_attribute(
client, snapshot_id: str, attribute: str