Debian Codegraph @

ansible_collections/amazon/aws/plugins/module_utils/ec2.py

raw
1 # -*- coding: utf-8 -*-
2
3 # This code is part of Ansible, but is an independent component.
4 # This particular file snippet, and this file snippet only, is BSD licensed.
5 # Modules you write using this snippet, which is embedded dynamically by Ansible
6 # still belong to the author of the module, and may assign their own license
7 # to the complete work.
8 #
9 # Copyright (c), Michael DeHaan <[email protected]>, 2012-2013
10 # All rights reserved.
11 #
12 # Redistribution and use in source and binary forms, with or without modification,
13 # are permitted provided that the following conditions are met:
14 #
15 # * Redistributions of source code must retain the above copyright
16 # notice, this list of conditions and the following disclaimer.
17 # * Redistributions in binary form must reproduce the above copyright notice,
18 # this list of conditions and the following disclaimer in the documentation
19 # and/or other materials provided with the distribution.
20 #
21 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
22 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
29 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31
32 """
33 This module adds helper functions for various EC2 specific services.
34
35 It also includes a large number of imports for functions which historically
36 lived here. Most of these functions were not specific to EC2, they ended
37 up in this module because "that's where the AWS code was" (originally).
38 """
39
40 import copy
41 import re
42 from typing import Any
43 from typing import Dict
44 from typing import List
45 from typing import Optional
46 from typing import Union
47
48 import ansible.module_utils.common.warnings as ansible_warnings # pylint: disable=unused-import
49 from ansible.module_utils.ansible_release import __version__
50
51 # Used to live here, moved into ansible.module_utils.common.dict_transformations
52 from ansible.module_utils.common.dict_transformations import _camel_to_snake # pylint: disable=unused-import
53 from ansible.module_utils.common.dict_transformations import _snake_to_camel # pylint: disable=unused-import
54 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict # pylint: disable=unused-import
55 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict # pylint: disable=unused-import
56
57 # Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.arn
58 from .arn import is_outpost_arn as is_outposts_arn # pylint: disable=unused-import
59 from .arn import validate_aws_arn
60
61 # Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.botocore
62 from .botocore import HAS_BOTO3 # pylint: disable=unused-import
63 from .botocore import boto3_conn # pylint: disable=unused-import
64 from .botocore import boto3_inventory_conn # pylint: disable=unused-import
65 from .botocore import boto_exception # pylint: disable=unused-import
66 from .botocore import get_aws_connection_info # pylint: disable=unused-import
67 from .botocore import get_aws_region # pylint: disable=unused-import
68 from .botocore import is_boto3_error_code
69 from .botocore import paginated_query_with_retries
70 from .errors import AWSErrorHandler
71
72 # Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.exceptions
73 from .exceptions import AnsibleAWSError # pylint: disable=unused-import
74 from .iam import list_iam_instance_profiles
75
76 # Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.modules
77 # The names have been changed in .modules to better reflect their applicability.
78 from .modules import _aws_common_argument_spec as aws_common_argument_spec # pylint: disable=unused-import
79 from .modules import aws_argument_spec as ec2_argument_spec # pylint: disable=unused-import
80
81 # Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.policy
82 from .policy import _py3cmp as py3cmp # pylint: disable=unused-import
83 from .policy import compare_policies # pylint: disable=unused-import
84
85 # Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.retries
86 from .retries import AWSRetry # pylint: disable=unused-import
87
88 # Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.tagging
89 from .tagging import ansible_dict_to_boto3_tag_list # pylint: disable=unused-import
90 from .tagging import boto3_tag_list_to_ansible_dict # pylint: disable=unused-import
91 from .tagging import boto3_tag_specifications
92 from .tagging import compare_aws_tags # pylint: disable=unused-import
93
94 # Used to live here, moved into ansible_collections.amazon.aws.plugins.module_utils.transformation
95 from .transformation import ansible_dict_to_boto3_filter_list # pylint: disable=unused-import
96 from .transformation import map_complex_type # pylint: disable=unused-import
97
98 try:
99 import botocore
100 except ImportError:
101 pass # Handled by HAS_BOTO3
102
103
104 class AnsibleEC2Error(AnsibleAWSError):
105 pass
106
107
108 EC2TagSpecifications = Dict[str, Union[str, List[Dict[str, str]]]]
109
110
111 @AWSRetry.jittered_backoff()
112 def describe_availability_zones(
113 client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
114 ) -> List[Dict[str, Union[str, List[Dict[str, str]]]]]:
115 # The paginator does not exist for `describe_availability_zones()`
116 return client.describe_availability_zones(**params)["AvailabilityZones"]
117
118
119 @AWSRetry.jittered_backoff()
120 def describe_regions(
121 client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
122 ) -> List[Dict[str, str]]:
123 # The paginator does not exist for `describe_regions()`
124 return client.describe_regions(**params)["Regions"]
125
126
127 # EC2 VPC Subnets
128 class EC2VpcSubnetErrorHandler(AWSErrorHandler):
129 _CUSTOM_EXCEPTION = AnsibleEC2Error
130
131 @classmethod
132 def _is_missing(cls):
133 return is_boto3_error_code("InvalidSubnetID.NotFound")
134
135
136 @EC2VpcSubnetErrorHandler.deletion_error_handler("delete subnet")
137 @AWSRetry.jittered_backoff()
138 def delete_subnet(client, subnet_id: str) -> bool:
139 client.delete_subnet(SubnetId=subnet_id)
140 return True
141
142
143 @EC2VpcSubnetErrorHandler.list_error_handler("describe subnets", [])
144 @AWSRetry.jittered_backoff()
145 def describe_subnets(
146 client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
147 ) -> List[Dict[str, Any]]:
148 paginator = client.get_paginator("describe_subnets")
149 return paginator.paginate(**params).build_full_result()["Subnets"]
150
151
152 @EC2VpcSubnetErrorHandler.common_error_handler("create subnet")
153 @AWSRetry.jittered_backoff()
154 def create_subnet(client, **params: Dict[str, Union[str, bool, int, EC2TagSpecifications]]) -> Dict[str, Any]:
155 return client.create_subnet(**params)["Subnet"]
156
157
158 @EC2VpcSubnetErrorHandler.common_error_handler("modify subnet")
159 @AWSRetry.jittered_backoff()
160 def modify_subnet_attribute(client, subnet_id: str, **params: Dict[str, Union[str, int, Dict[str, bool]]]) -> bool:
161 client.modify_subnet_attribute(SubnetId=subnet_id, **params)
162 return True
163
164
165 @EC2VpcSubnetErrorHandler.common_error_handler("disassociate subnet cidr block")
166 @AWSRetry.jittered_backoff()
167 def disassociate_subnet_cidr_block(client, association_id: str) -> Dict[str, Union[str, Dict[str, str]]]:
168 return client.disassociate_subnet_cidr_block(AssociationId=association_id)["Ipv6CidrBlockAssociation"]
169
170
171 @EC2VpcSubnetErrorHandler.common_error_handler("associate subnet cidr block")
172 @AWSRetry.jittered_backoff()
173 def associate_subnet_cidr_block(
174 client, subnet_id: str, **params: Dict[str, Union[str, int]]
175 ) -> Dict[str, Union[str, Dict[str, str]]]:
176 return client.associate_subnet_cidr_block(SubnetId=subnet_id, **params)["Ipv6CidrBlockAssociation"]
177
178
179 # EC2 VPC Route table
180 class EC2VpcRouteTableErrorHandler(AWSErrorHandler):
181 _CUSTOM_EXCEPTION = AnsibleEC2Error
182
183 @classmethod
184 def _is_missing(cls):
185 return is_boto3_error_code("InvalidRouteTableID.NotFound")
186
187
188 @EC2VpcRouteTableErrorHandler.list_error_handler("describe route tables", [])
189 @AWSRetry.jittered_backoff()
190 def describe_route_tables(
191 client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
192 ) -> List[Dict[str, Any]]:
193 paginator = client.get_paginator("describe_route_tables")
194 return paginator.paginate(**params).build_full_result()["RouteTables"]
195
196
197 @EC2VpcRouteTableErrorHandler.common_error_handler("disassociate route table")
198 @AWSRetry.jittered_backoff()
199 def disassociate_route_table(client, association_id: str) -> bool:
200 client.disassociate_route_table(AssociationId=association_id)
201 return True
202
203
204 @EC2VpcRouteTableErrorHandler.common_error_handler("associate route table")
205 @AWSRetry.jittered_backoff()
206 def associate_route_table(
207 client, route_table_id: str, **params: Dict[str, str]
208 ) -> Dict[str, Union[str, Dict[str, str]]]:
209 return client.associate_route_table(RouteTableId=route_table_id, **params)
210
211
212 @EC2VpcRouteTableErrorHandler.common_error_handler("enable vgw route propagation")
213 @AWSRetry.jittered_backoff()
214 def enable_vgw_route_propagation(client, gateway_id: str, route_table_id: str) -> bool:
215 client.enable_vgw_route_propagation(RouteTableId=route_table_id, GatewayId=gateway_id)
216 return True
217
218
219 @EC2VpcRouteTableErrorHandler.deletion_error_handler("delete route table")
220 @AWSRetry.jittered_backoff()
221 def delete_route_table(client, route_table_id: str) -> bool:
222 client.delete_route_table(RouteTableId=route_table_id)
223 return True
224
225
226 @EC2VpcRouteTableErrorHandler.common_error_handler("create route table")
227 @AWSRetry.jittered_backoff()
228 def create_route_table(client, vpc_id: str, tags: Optional[Dict[str, str]]) -> Dict[str, Any]:
229 params = {"VpcId": vpc_id}
230 if tags:
231 params["TagSpecifications"] = boto3_tag_specifications(tags, types="route-table")
232 return client.create_route_table(**params)["RouteTable"]
233
234
235 # EC2 VPC Route table Route
236 class EC2VpcRouteTableRouteErrorHandler(AWSErrorHandler):
237 _CUSTOM_EXCEPTION = AnsibleEC2Error
238
239 @classmethod
240 def _is_missing(cls):
241 return is_boto3_error_code("InvalidRoute.NotFound")
242
243
244 @EC2VpcRouteTableRouteErrorHandler.deletion_error_handler("delete route")
245 @AWSRetry.jittered_backoff()
246 def delete_route(client, route_table_id: str, **params: Dict[str, str]) -> bool:
247 client.delete_route(RouteTableId=route_table_id, **params)
248 return True
249
250
251 @EC2VpcRouteTableRouteErrorHandler.common_error_handler("replace route")
252 @AWSRetry.jittered_backoff()
253 def replace_route(client, route_table_id: str, **params: Dict[str, Union[str, bool]]) -> bool:
254 client.replace_route(RouteTableId=route_table_id, **params)
255 return True
256
257
258 @EC2VpcRouteTableRouteErrorHandler.common_error_handler("create route")
259 @AWSRetry.jittered_backoff()
260 def create_route(client, route_table_id: str, **params: Dict[str, str]) -> bool:
261 return client.create_route(RouteTableId=route_table_id, **params)["Return"]
262
263
264 # EC2 VPC
265 class EC2VpcErrorHandler(AWSErrorHandler):
266 _CUSTOM_EXCEPTION = AnsibleEC2Error
267
268 @classmethod
269 def _is_missing(cls):
270 return is_boto3_error_code("InvalidVpcID.NotFound")
271
272
273 @EC2VpcErrorHandler.list_error_handler("describe vpcs", [])
274 @AWSRetry.jittered_backoff()
275 def describe_vpcs(
276 client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
277 ) -> List[Dict[str, Any]]:
278 paginator = client.get_paginator("describe_vpcs")
279 return paginator.paginate(**params).build_full_result()["Vpcs"]
280
281
282 @EC2VpcErrorHandler.deletion_error_handler("delete vpc")
283 @AWSRetry.jittered_backoff()
284 def delete_vpc(client, vpc_id: str) -> bool:
285 client.delete_vpc(VpcId=vpc_id)
286 return True
287
288
289 @EC2VpcErrorHandler.common_error_handler("describe vpc attribute")
290 @AWSRetry.jittered_backoff()
291 def describe_vpc_attribute(client, vpc_id: str, attribute: str) -> Dict[str, Any]:
292 # The paginator does not exist for `describe_vpc_attribute`
293 return client.describe_vpc_attribute(VpcId=vpc_id, Attribute=attribute)
294
295
296 @EC2VpcErrorHandler.common_error_handler("modify vpc attribute")
297 @AWSRetry.jittered_backoff()
298 def modify_vpc_attribute(client, vpc_id: str, **params: Dict[str, Union[str, Dict[str, bool]]]) -> bool:
299 client.modify_vpc_attribute(VpcId=vpc_id, **params)
300 return True
301
302
303 @EC2VpcErrorHandler.common_error_handler("create vpc")
304 @AWSRetry.jittered_backoff()
305 def create_vpc(client, **params: Dict[str, Union[str, bool, int, EC2TagSpecifications]]) -> Dict[str, Any]:
306 return client.create_vpc(**params)["Vpc"]
307
308
309 @EC2VpcErrorHandler.common_error_handler("associate vpc cidr block")
310 @AWSRetry.jittered_backoff()
311 def associate_vpc_cidr_block(client, vpc_id: str, **params: Dict[str, Union[str, bool, int]]) -> Dict[str, Any]:
312 return client.associate_vpc_cidr_block(VpcId=vpc_id, **params)
313
314
315 @EC2VpcErrorHandler.common_error_handler("disassociate vpc cidr block")
316 @AWSRetry.jittered_backoff()
317 def disassociate_vpc_cidr_block(client, association_id: str) -> Dict[str, Any]:
318 return client.disassociate_vpc_cidr_block(AssociationId=association_id)
319
320
321 # EC2 VPC Peering Connection
322 class EC2VpcPeeringErrorHandler(AWSErrorHandler):
323 _CUSTOM_EXCEPTION = AnsibleEC2Error
324
325 @classmethod
326 def _is_missing(cls):
327 return is_boto3_error_code("InvalidVpcPeeringConnectionID.NotFound")
328
329
330 @EC2VpcPeeringErrorHandler.list_error_handler("describe vpc peering", [])
331 @AWSRetry.jittered_backoff()
332 def describe_vpc_peering_connections(client, **params: Dict[str, Any]) -> List[Dict[str, Any]]:
333 paginator = client.get_paginator("describe_vpc_peering_connections")
334 return paginator.paginate(**params).build_full_result()["VpcPeeringConnections"]
335
336
337 @EC2VpcSubnetErrorHandler.common_error_handler("create vpc peering")
338 @AWSRetry.jittered_backoff()
339 def create_vpc_peering_connection(
340 client, **params: Dict[str, Union[str, bool, int, EC2TagSpecifications]]
341 ) -> Dict[str, Any]:
342 return client.create_vpc_peering_connection(**params)["VpcPeeringConnection"]
343
344
345 @EC2VpcSubnetErrorHandler.deletion_error_handler("delete vpc peering")
346 @AWSRetry.jittered_backoff()
347 def delete_vpc_peering_connection(client, peering_id: str) -> bool:
348 client.delete_vpc_peering_connection(VpcPeeringConnectionId=peering_id)
349 return True
350
351
352 @EC2VpcSubnetErrorHandler.deletion_error_handler("accept vpc peering")
353 @AWSRetry.jittered_backoff()
354 def accept_vpc_peering_connection(client, peering_id: str) -> bool:
355 client.accept_vpc_peering_connection(VpcPeeringConnectionId=peering_id)
356 return True
357
358
359 @EC2VpcSubnetErrorHandler.deletion_error_handler("reject vpc peering")
360 @AWSRetry.jittered_backoff()
361 def reject_vpc_peering_connection(client, peering_id: str) -> bool:
362 client.reject_vpc_peering_connection(VpcPeeringConnectionId=peering_id)
363 return True
364
365
366 # EC2 vpn
367 class EC2VpnErrorHandler(AWSErrorHandler):
368 _CUSTOM_EXCEPTION = AnsibleEC2Error
369
370 @classmethod
371 def _is_missing(cls):
372 return is_boto3_error_code(["InvalidVpnConnectionID.NotFound", "InvalidRoute.NotFound"])
373
374
375 @EC2VpcErrorHandler.list_error_handler("describe vpn connections", [])
376 @AWSRetry.jittered_backoff()
377 def describe_vpn_connections(client, **params: Dict[str, Any]) -> List[Dict[str, Any]]:
378 # The paginator does not exist for `describe_vpn_connections`
379 return client.describe_vpn_connections(**params)["VpnConnections"]
380
381
382 @EC2VpcErrorHandler.common_error_handler("create vpn connection route")
383 @AWSRetry.jittered_backoff()
384 def create_vpn_connection_route(client, vpn_connection_id: str, route: Dict[str, Any]) -> bool:
385 client.create_vpn_connection_route(VpnConnectionId=vpn_connection_id, DestinationCidrBlock=route)
386 return True
387
388
389 @EC2VpcErrorHandler.deletion_error_handler("delete vpn connection route")
390 @AWSRetry.jittered_backoff()
391 def delete_vpn_connection_route(client, vpn_connection_id: str, route: Dict[str, Any]) -> bool:
392 client.delete_vpn_connection_route(VpnConnectionId=vpn_connection_id, DestinationCidrBlock=route)
393 return True
394
395
396 @EC2VpcErrorHandler.common_error_handler("create vpn connection")
397 @AWSRetry.jittered_backoff()
398 def create_vpn_connection(client, **params: Dict[str, Any]) -> Dict[str, Any]:
399 return client.create_vpn_connection(**params)["VpnConnection"]
400
401
402 @EC2VpcErrorHandler.deletion_error_handler("delete vpn connection")
403 @AWSRetry.jittered_backoff()
404 def delete_vpn_connection(client, vpn_connection_id: str) -> Dict[str, Any]:
405 client.delete_vpn_connection(VpnConnectionId=vpn_connection_id)
406 return True
407
408
409 # EC2 Internet Gateway
410 class EC2InternetGatewayErrorHandler(AWSErrorHandler):
411 _CUSTOM_EXCEPTION = AnsibleEC2Error
412
413 @classmethod
414 def _is_missing(cls):
415 return is_boto3_error_code("InvalidInternetGatewayID.NotFound")
416
417
418 @EC2InternetGatewayErrorHandler.list_error_handler("describe internet gateways")
419 @AWSRetry.jittered_backoff()
420 def describe_internet_gateways(
421 client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
422 ) -> List[Dict[str, Any]]:
423 paginator = client.get_paginator("describe_internet_gateways")
424 return paginator.paginate(**params).build_full_result()["InternetGateways"]
425
426
427 @EC2InternetGatewayErrorHandler.common_error_handler("create internet gateway")
428 @AWSRetry.jittered_backoff()
429 def create_internet_gateway(client, tags: Optional[List[Dict[str, str]]]) -> Dict[str, Any]:
430 params = {}
431 if tags:
432 params["TagSpecifications"] = boto3_tag_specifications(tags, types="internet-gateway")
433 return client.create_internet_gateway(**params)["InternetGateway"]
434
435
436 @EC2InternetGatewayErrorHandler.common_error_handler("detach internet gateway")
437 @AWSRetry.jittered_backoff()
438 def detach_internet_gateway(client, internet_gateway_id: str, vpc_id: str) -> bool:
439 client.detach_internet_gateway(InternetGatewayId=internet_gateway_id, VpcId=vpc_id)
440 return True
441
442
443 @EC2InternetGatewayErrorHandler.common_error_handler("attach internet gateway")
444 @AWSRetry.jittered_backoff()
445 def attach_internet_gateway(client, internet_gateway_id: str, vpc_id: str) -> bool:
446 client.attach_internet_gateway(InternetGatewayId=internet_gateway_id, VpcId=vpc_id)
447 return True
448
449
450 @EC2InternetGatewayErrorHandler.deletion_error_handler("delete internet gateway")
451 @AWSRetry.jittered_backoff()
452 def delete_internet_gateway(client, internet_gateway_id: str) -> bool:
453 client.delete_internet_gateway(InternetGatewayId=internet_gateway_id)
454 return True
455
456
457 # EC2 NAT Gateway
458 class EC2NatGatewayErrorHandler(AWSErrorHandler):
459 _CUSTOM_EXCEPTION = AnsibleEC2Error
460
461 @classmethod
462 def _is_missing(cls):
463 return is_boto3_error_code("InvalidNatGatewayID.NotFound")
464
465
466 @EC2NatGatewayErrorHandler.list_error_handler("describe nat gateways", [])
467 @AWSRetry.jittered_backoff()
468 def describe_nat_gateways(
469 client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
470 ) -> List[Dict[str, Any]]:
471 paginator = client.get_paginator("describe_nat_gateways")
472 return paginator.paginate(**params).build_full_result()["NatGateways"]
473
474
475 @EC2NatGatewayErrorHandler.deletion_error_handler("delete nat gateway")
476 @AWSRetry.jittered_backoff()
477 def delete_nat_gateway(client, nat_gateway_id: str) -> bool:
478 client.delete_nat_gateway(NatGatewayId=nat_gateway_id)
479 return True
480
481
482 @EC2NatGatewayErrorHandler.common_error_handler("create nat gateway")
483 @AWSRetry.jittered_backoff(catch_extra_error_codes=["InvalidElasticIpID.NotFound"])
484 def create_nat_gateway(
485 client, **params: Dict[str, Union[str, bool, int, EC2TagSpecifications, List[str]]]
486 ) -> Dict[str, Any]:
487 return client.create_nat_gateway(**params)["NatGateway"]
488
489
490 # EC2 Elastic IP
491 class EC2ElasticIPErrorHandler(AWSErrorHandler):
492 _CUSTOM_EXCEPTION = AnsibleEC2Error
493
494 @classmethod
495 def _is_missing(cls):
496 return is_boto3_error_code("InvalidAddress.NotFound")
497
498
499 @EC2ElasticIPErrorHandler.list_error_handler("describe addresses", [])
500 @AWSRetry.jittered_backoff()
501 def describe_addresses(
502 client, **params: Dict[str, Union[List[str], List[Dict[str, Union[str, List[str]]]]]]
503 ) -> List[Dict[str, Union[str, List[Dict[str, str]]]]]:
504 # The paginator does not exist for 'describe_addresses()'
505 return client.describe_addresses(**params)["Addresses"]
506
507
508 @EC2ElasticIPErrorHandler.common_error_handler("release address")
509 @AWSRetry.jittered_backoff()
510 def release_address(client, allocation_id: str, network_border_group: Optional[str] = None) -> bool:
511 params = {"AllocationId": allocation_id}
512 if network_border_group:
513 params["NetworkBorderGroup"] = network_border_group
514 client.release_address(**params)
515 return True
516
517
518 @EC2ElasticIPErrorHandler.common_error_handler("associate address")
519 @AWSRetry.jittered_backoff()
520 def associate_address(client, **params: Dict[str, Union[str, bool]]) -> Dict[str, str]:
521 return client.associate_address(**params)
522
523
524 @EC2ElasticIPErrorHandler.common_error_handler("disassociate address")
525 @AWSRetry.jittered_backoff()
526 def disassociate_address(client, association_id: str) -> bool:
527 client.disassociate_address(AssociationId=association_id)
528 return True
529
530
531 @EC2ElasticIPErrorHandler.common_error_handler("allocate address")
532 @AWSRetry.jittered_backoff()
533 def allocate_address(client, **params: Dict[str, Union[str, EC2TagSpecifications]]) -> Dict[str, str]:
534 return client.allocate_address(**params)
535
536
537 # EC2 VPC Endpoints
538 class EC2VpcEndpointsErrorHandler(AWSErrorHandler):
539 _CUSTOM_EXCEPTION = AnsibleEC2Error
540
541 @classmethod
542 def _is_missing(cls):
543 return is_boto3_error_code(["InvalidVpcEndpoint.NotFound", "InvalidVpcEndpointId.NotFound"])
544
545
546 @EC2VpcEndpointsErrorHandler.list_error_handler("describe vpc endpoints", [])
547 @AWSRetry.jittered_backoff()
548 def describe_vpc_endpoints(
549 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
550 ) -> Dict[str, Any]:
551 paginator = client.get_paginator("describe_vpc_endpoints")
552 return paginator.paginate(**params).build_full_result()["VpcEndpoints"]
553
554
555 @EC2VpcEndpointsErrorHandler.deletion_error_handler("delete vpc endpoints")
556 @AWSRetry.jittered_backoff()
557 def delete_vpc_endpoints(client, vpc_endpoint_ids: str) -> List[Dict[str, Union[str, Dict[str, str]]]]:
558 result = client.delete_vpc_endpoints(VpcEndpointIds=vpc_endpoint_ids)
559 return result.get("Unsuccessful", [])
560
561
562 @EC2ElasticIPErrorHandler.common_error_handler("create vpc endpoint")
563 @AWSRetry.jittered_backoff()
564 def create_vpc_endpoint(
565 client,
566 **params: Dict[
567 str, Union[str, bool, List[str], Dict[str, Union[str, bool]], List[Dict[str, str]], EC2TagSpecifications]
568 ],
569 ) -> Dict[str, Any]:
570 return client.create_vpc_endpoint(**params)["VpcEndpoint"]
571
572
573 # EC2 VPC Endpoint Services
574 class EC2VpcEndpointServiceErrorHandler(AWSErrorHandler):
575 _CUSTOM_EXCEPTION = AnsibleEC2Error
576
577 @classmethod
578 def _is_missing(cls):
579 return is_boto3_error_code("InvalidServiceName")
580
581
582 @EC2VpcEndpointServiceErrorHandler.list_error_handler("describe vpc endpoint services", default_value={})
583 @AWSRetry.jittered_backoff()
584 def describe_vpc_endpoint_services(
585 client, filters: Optional[List[Dict[str, Any]]] = None, service_names: Optional[List[str]] = None
586 ) -> Dict[str, Any]:
587 """
588 Wrap call to the AWS API describe_vpc_endpoint_services (used to describe available
589 services to which you can create a VPC endpoint.)
590 Parameters:
591 client: The boto3 client.
592 filters: Optional filters to pass to the API.
593 service_names: the service names.
594 Returns:
595 results: A dictionnary with keys 'ServiceNames' and 'ServiceDetails'
596 """
597 paginator = client.get_paginator("describe_vpc_endpoint_services")
598 params: dict[str, Any] = {}
599 if filters:
600 params["Filters"] = filters
601
602 if service_names:
603 params["ServiceNames"] = service_names
604
605 results = paginator.paginate(**params).build_full_result()
606 return results
607
608
609 # EC2 VPC DHCP Option
610 class EC2VpcDhcpOptionErrorHandler(AWSErrorHandler):
611 _CUSTOM_EXCEPTION = AnsibleEC2Error
612
613 @classmethod
614 def _is_missing(cls):
615 return is_boto3_error_code(["InvalidDhcpOptionsID.NotFound", "InvalidDhcpOptionID.NotFound"])
616
617
618 @EC2VpcDhcpOptionErrorHandler.list_error_handler("describe dhcp options", [])
619 @AWSRetry.jittered_backoff()
620 def describe_dhcp_options(
621 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
622 ) -> List[Dict[str, Any]]:
623 paginator = client.get_paginator("describe_dhcp_options")
624 return paginator.paginate(**params).build_full_result()["DhcpOptions"]
625
626
627 @EC2VpcDhcpOptionErrorHandler.deletion_error_handler("delete dhcp options")
628 @AWSRetry.jittered_backoff()
629 def delete_dhcp_options(client, dhcp_options_id: str) -> bool:
630 client.delete_dhcp_options(DhcpOptionsId=dhcp_options_id)
631 return True
632
633
634 @EC2VpcDhcpOptionErrorHandler.common_error_handler("associate dhcp options")
635 @AWSRetry.jittered_backoff()
636 def associate_dhcp_options(client, dhcp_options_id: str, vpc_id: str) -> bool:
637 client.associate_dhcp_options(DhcpOptionsId=dhcp_options_id, VpcId=vpc_id)
638 return True
639
640
641 @EC2VpcDhcpOptionErrorHandler.common_error_handler("create dhcp options")
642 @AWSRetry.jittered_backoff()
643 def create_dhcp_options(
644 client, **params: Dict[str, Union[Dict[str, Union[str, List[str]]], EC2TagSpecifications]]
645 ) -> Dict[str, Any]:
646 return client.create_dhcp_options(**params)["DhcpOptions"]
647
648
649 # EC2 vpn Gateways
650 class EC2VpnGatewaysErrorHandler(AWSErrorHandler):
651 _CUSTOM_EXCEPTION = AnsibleEC2Error
652
653 @classmethod
654 def _is_missing(cls):
655 return is_boto3_error_code(["InvalidVpnGatewayID.NotFound", "InvalidVpnGatewayState"])
656
657
658 @EC2VpnGatewaysErrorHandler.list_error_handler("describe vpn gateways", [])
659 @AWSRetry.jittered_backoff()
660 def describe_vpn_gateways(
661 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
662 ) -> List[Dict[str, Any]]:
663 return client.describe_vpn_gateways(**params)["VpnGateways"]
664
665
666 @EC2VpnGatewaysErrorHandler.common_error_handler("create vpn gateway")
667 @AWSRetry.jittered_backoff(catch_extra_error_codes=["VpnGatewayLimitExceeded"])
668 def create_vpn_gateway(
669 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
670 ) -> Dict[str, Any]:
671 return client.create_vpn_gateway(**params)["VpnGateway"]
672
673
674 @EC2VpnGatewaysErrorHandler.deletion_error_handler("delete vpn gateway")
675 @AWSRetry.jittered_backoff()
676 def delete_vpn_gateway(client, vpn_gateway_id: str) -> bool:
677 client.delete_vpn_gateway(VpnGatewayId=vpn_gateway_id)
678 return True
679
680
681 @EC2VpnGatewaysErrorHandler.common_error_handler("attach vpn gateway")
682 @AWSRetry.jittered_backoff()
683 def attach_vpn_gateway(client, vpc_id: str, vpn_gateway_id: str) -> bool:
684 client.attach_vpn_gateway(VpcId=vpc_id, VpnGatewayId=vpn_gateway_id)
685 return True
686
687
688 @EC2VpnGatewaysErrorHandler.common_error_handler("detach vpn gateway")
689 @AWSRetry.jittered_backoff()
690 def detach_vpn_gateway(client, vpc_id: str, vpn_gateway_id: str) -> bool:
691 client.detach_vpn_gateway(VpcId=vpc_id, VpnGatewayId=vpn_gateway_id)
692 return True
693
694
695 # EC2 Volumes
696 class EC2VolumeErrorHandler(AWSErrorHandler):
697 _CUSTOM_EXCEPTION = AnsibleEC2Error
698
699 @classmethod
700 def _is_missing(cls):
701 return is_boto3_error_code("InvalidVolume.NotFound")
702
703
704 @EC2VolumeErrorHandler.list_error_handler("describe volumes", [])
705 @AWSRetry.jittered_backoff()
706 def describe_volumes(
707 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
708 ) -> List[Dict[str, Any]]:
709 paginator = client.get_paginator("describe_volumes")
710 return paginator.paginate(**params).build_full_result()["Volumes"]
711
712
713 @EC2VolumeErrorHandler.deletion_error_handler("delete volume")
714 @AWSRetry.jittered_backoff()
715 def delete_volume(client, volume_id: str) -> bool:
716 client.delete_volume(VolumeId=volume_id)
717 return True
718
719
720 @EC2VolumeErrorHandler.common_error_handler("modify volume")
721 @AWSRetry.jittered_backoff()
722 def modify_volume(client, **params: Dict[str, Union[str, bool, int]]) -> Dict[str, Any]:
723 return client.modify_volume(**params)["VolumeModification"]
724
725
726 @EC2VolumeErrorHandler.common_error_handler("modify volume")
727 @AWSRetry.jittered_backoff()
728 def create_volume(client, **params: Dict[str, Union[str, bool, int, EC2TagSpecifications]]) -> Dict[str, Any]:
729 return client.create_volume(**params)
730
731
732 @EC2VolumeErrorHandler.common_error_handler("attach volume")
733 @AWSRetry.jittered_backoff()
734 def attach_volume(client, device: str, instance_id: str, volume_id: str) -> Dict[str, Any]:
735 return client.attach_volume(Device=device, InstanceId=instance_id, VolumeId=volume_id)
736
737
738 @EC2VolumeErrorHandler.common_error_handler("attach volume")
739 @AWSRetry.jittered_backoff()
740 def detach_volume(client, volume_id: str, **params: Dict[str, Union[str, bool]]) -> Dict[str, Any]:
741 return client.detach_volume(VolumeId=volume_id, **params)
742
743
744 # EC2 Instance
745 EC2_INSTANCE_CATCH_EXTRA_CODES = [
746 "IncorrectState",
747 "InsufficientInstanceCapacity",
748 "InvalidInstanceID.NotFound",
749 ]
750
751
752 class EC2InstanceErrorHandler(AWSErrorHandler):
753 _CUSTOM_EXCEPTION = AnsibleEC2Error
754
755 @classmethod
756 def _is_missing(cls):
757 return is_boto3_error_code("InvalidInstanceID.NotFound")
758
759
760 @EC2InstanceErrorHandler.list_error_handler("describe instances", [])
761 @AWSRetry.jittered_backoff()
762 def describe_instances(
763 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
764 ) -> List[Dict[str, Any]]:
765 paginator = client.get_paginator("describe_instances")
766 return paginator.paginate(**params).build_full_result()["Reservations"]
767
768
769 @EC2InstanceErrorHandler.common_error_handler("modify instance attribute")
770 @AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
771 def modify_instance_attribute(
772 client,
773 instance_id: str,
774 **params: Dict[
775 str,
776 Union[
777 str,
778 List[str],
779 Dict[str, str],
780 Dict[str, bool],
781 Dict[str, bytes],
782 Dict[str, Union[str, Dict[str, Union[str, bool]]]],
783 ],
784 ],
785 ) -> bool:
786 client.modify_instance_attribute(InstanceId=instance_id, **params)
787 return True
788
789
790 @EC2InstanceErrorHandler.list_error_handler("terminate instances", [])
791 @AWSRetry.jittered_backoff()
792 def terminate_instances(client, instance_ids: List[str]) -> List[Dict[str, Any]]:
793 return client.terminate_instances(InstanceIds=instance_ids)["TerminatingInstances"]
794
795
796 @EC2InstanceErrorHandler.list_error_handler("stop instances", [])
797 @AWSRetry.jittered_backoff()
798 def stop_instances(
799 client, instance_ids: List[str], **params: Dict[str, Union[bool, List[str]]]
800 ) -> List[Dict[str, Any]]:
801 return client.stop_instances(InstanceIds=instance_ids, **params)["StoppingInstances"]
802
803
804 @EC2InstanceErrorHandler.list_error_handler("start instances", [])
805 @AWSRetry.jittered_backoff()
806 def start_instances(
807 client, instance_ids: List[str], **params: Dict[str, Union[str, List[str]]]
808 ) -> List[Dict[str, Any]]:
809 return client.start_instances(InstanceIds=instance_ids, **params)["StartingInstances"]
810
811
812 @EC2InstanceErrorHandler.common_error_handler("run instances")
813 @AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
814 def run_instances(client, **params: Dict[str, Any]) -> Dict[str, Any]:
815 return client.run_instances(**params)
816
817
818 @EC2InstanceErrorHandler.common_error_handler("describe instance attribute")
819 @AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
820 def describe_instance_attribute(client, instance_id: str, attribute: str) -> Dict[str, Any]:
821 # The paginator does not exist for describe_instance_attribute()
822 return client.describe_instance_attribute(InstanceId=instance_id, Attribute=attribute)
823
824
825 @EC2InstanceErrorHandler.common_error_handler("describe instance status")
826 @AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
827 def describe_instance_status(
828 client, **params: Dict[str, Union[List[str], bool, int, List[Dict[str, Union[str, List[str]]]]]]
829 ) -> List[Dict[str, Any]]:
830 paginator = client.get_paginator("describe_instance_status")
831 return paginator.paginate(**params).build_full_result()["InstanceStatuses"]
832
833
834 @EC2InstanceErrorHandler.common_error_handler("modify instance metadata options")
835 @AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
836 def modify_instance_metadata_options(
837 client, instance_id: str, **params: Dict[str, Union[str, int]]
838 ) -> Dict[str, Union[int, str]]:
839 return client.modify_instance_metadata_options(InstanceId=instance_id, **params)["InstanceMetadataOptions"]
840
841
842 @EC2InstanceErrorHandler.common_error_handler("describe iam instance profile associations")
843 @AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
844 def describe_iam_instance_profile_associations(
845 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
846 ) -> Dict[str, Any]:
847 paginator = client.get_paginator("describe_iam_instance_profile_associations")
848 return paginator.paginate(**params).build_full_result()["IamInstanceProfileAssociations"]
849
850
851 @EC2InstanceErrorHandler.common_error_handler("replace iam instance profile association")
852 @AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
853 def replace_iam_instance_profile_association(
854 client, iam_instance_profile: Dict[str, str], association_id: str
855 ) -> Dict[str, Union[int, str]]:
856 return client.replace_iam_instance_profile_association(
857 IamInstanceProfile=iam_instance_profile, AssociationId=association_id
858 )["IamInstanceProfileAssociation"]
859
860
861 @EC2InstanceErrorHandler.common_error_handler("associate iam instance profile")
862 @AWSRetry.jittered_backoff(catch_extra_error_codes=EC2_INSTANCE_CATCH_EXTRA_CODES)
863 def associate_iam_instance_profile(client, iam_instance_profile: Dict[str, str], instance_id: str) -> Dict[str, Any]:
864 return client.associate_iam_instance_profile(IamInstanceProfile=iam_instance_profile, InstanceId=instance_id)[
865 "IamInstanceProfileAssociation"
866 ]
867
868
869 # EC2 Instance Types
870 class EC2InstanceTypeErrorHandler(AWSErrorHandler):
871 _CUSTOM_EXCEPTION = AnsibleEC2Error
872
873 # @classmethod
874 # def _is_missing(cls):
875 # return is_boto3_error_code("InvalidInstanceType")
876
877
878 @EC2InstanceTypeErrorHandler.list_error_handler("describe instance types", [])
879 @AWSRetry.jittered_backoff()
880 def describe_instance_types(
881 client, **params: Dict[str, Union[List[str], Dict[str, Union[str, List[str]]]]]
882 ) -> List[Dict[str, Any]]:
883 paginator = client.get_paginator("describe_instance_types")
884 return paginator.paginate(**params).build_full_result()["InstanceTypes"]
885
886
887 # EC2 Key
888 class EC2KeyErrorHandler(AWSErrorHandler):
889 _CUSTOM_EXCEPTION = AnsibleEC2Error
890
891 @classmethod
892 def _is_missing(cls):
893 return is_boto3_error_code("InvalidKeyPair.NotFound")
894
895
896 @EC2KeyErrorHandler.list_error_handler("describe key pairs", [])
897 @AWSRetry.jittered_backoff()
898 def describe_key_pairs(
899 client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
900 ) -> List[Dict[str, Any]]:
901 # The paginator does not exist for `describe_key_pairs()`
902 return client.describe_key_pairs(**params)["KeyPairs"]
903
904
905 @EC2KeyErrorHandler.common_error_handler("import key pair")
906 @AWSRetry.jittered_backoff()
907 def import_key_pair(
908 client, **params: Dict[str, Union[str, bytes, EC2TagSpecifications]]
909 ) -> Dict[str, Union[str, List[Dict[str, str]]]]:
910 return client.import_key_pair(**params)
911
912
913 @EC2KeyErrorHandler.common_error_handler("create key pair")
914 @AWSRetry.jittered_backoff()
915 def create_key_pair(
916 client, **params: Dict[str, Union[str, EC2TagSpecifications]]
917 ) -> Dict[str, Union[str, List[Dict[str, str]]]]:
918 return client.create_key_pair(**params)
919
920
921 @EC2KeyErrorHandler.deletion_error_handler("delete key pair")
922 @AWSRetry.jittered_backoff()
923 def delete_key_pair(client, key_name: Optional[str] = None, key_id: Optional[str] = None) -> bool:
924 params = {}
925 if key_name:
926 params["KeyName"] = key_name
927 if key_id:
928 params["KeyPairId"] = key_id
929 client.delete_key_pair(**params)
930 return True
931
932
933 # EC2 Image
934 class EC2ImageErrorHandler(AWSErrorHandler):
935 _CUSTOM_EXCEPTION = AnsibleEC2Error
936
937 @classmethod
938 def _is_missing(cls):
939 return is_boto3_error_code("InvalidAMIID.Unavailable")
940
941
942 @EC2ImageErrorHandler.list_error_handler("describe images", [])
943 @AWSRetry.jittered_backoff()
944 def describe_images(
945 client, **params: Dict[str, Union[List[str], bool, int, List[Dict[str, Union[str, List[str]]]]]]
946 ) -> List[Dict[str, Any]]:
947 # 'DescribeImages' can be paginated depending on the boto3 version
948 if client.can_paginate("describe_images"):
949 paginator = client.get_paginator("describe_images")
950 return paginator.paginate(**params).build_full_result()["Images"]
951 else:
952 return client.describe_images(**params)["Images"]
953
954
955 @EC2ImageErrorHandler.list_error_handler("describe image attribute", {})
956 @AWSRetry.jittered_backoff()
957 def describe_image_attribute(client, image_id: str, attribute: str) -> Optional[Dict[str, Any]]:
958 # The paginator does not exist for `describe_image_attribute()`
959 return client.describe_image_attribute(Attribute=attribute, ImageId=image_id)
960
961
962 @EC2ImageErrorHandler.deletion_error_handler("deregister image")
963 @AWSRetry.jittered_backoff()
964 def deregister_image(client, image_id: str) -> bool:
965 client.deregister_image(ImageId=image_id)
966 return True
967
968
969 @EC2ImageErrorHandler.common_error_handler("modify image attribute")
970 @AWSRetry.jittered_backoff()
971 def modify_image_attribute(client, image_id: str, **params: Dict[str, Any]) -> bool:
972 client.modify_image_attribute(ImageId=image_id, **params)
973 return True
974
975
976 @EC2ImageErrorHandler.common_error_handler("create image")
977 @AWSRetry.jittered_backoff()
978 def create_image(client, **params: Dict[str, Any]) -> Dict[str, str]:
979 return client.create_image(**params)
980
981
982 @EC2ImageErrorHandler.common_error_handler("register image")
983 @AWSRetry.jittered_backoff()
984 def register_image(client, **params: Dict[str, Any]) -> Dict[str, str]:
985 return client.register_image(**params)
986
987
988 # EC2 Snapshot
989 class EC2SnapshotErrorHandler(AWSErrorHandler):
990 _CUSTOM_EXCEPTION = AnsibleEC2Error
991
992 @classmethod
993 def _is_missing(cls):
994 return is_boto3_error_code("InvalidSnapshot.NotFound")
995
996
997 @EC2SnapshotErrorHandler.deletion_error_handler("delete snapshot")
998 @AWSRetry.jittered_backoff()
999 def delete_snapshot(client, snapshot_id: str) -> bool:
1000 client.delete_snapshot(SnapshotId=snapshot_id)
1001 return True
1002
1003
1004 @EC2SnapshotErrorHandler.list_error_handler("describe snapshots", [])
1005 @AWSRetry.jittered_backoff()
1006 def describe_snapshots(
1007 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
1008 ) -> Dict[str, Any]:
1009 # We do not use paginator here because the `ec2_snapshot_info` module excepts the NextToken to be returned
1010 return client.describe_snapshots(**params)
1011
1012
1013 @EC2SnapshotErrorHandler.common_error_handler("describe snapshot attribute")
1014 @AWSRetry.jittered_backoff()
1015 def describe_snapshot_attribute(
1016 client, snapshot_id: str, attribute: str
1017 ) -> Dict[str, Union[str, List[Dict[str, str]]]]:
1018 return client.describe_snapshot_attribute(Attribute=attribute, SnapshotId=snapshot_id)
1019
1020
1021 @EC2SnapshotErrorHandler.common_error_handler("reset snapshot attribute")
1022 @AWSRetry.jittered_backoff()
1023 def reset_snapshot_attribute(client, snapshot_id: str, attribute: str) -> bool:
1024 client.reset_snapshot_attribute(Attribute=attribute, SnapshotId=snapshot_id)
1025 return True
1026
1027
1028 @EC2SnapshotErrorHandler.common_error_handler("modify snapshot attribute")
1029 @AWSRetry.jittered_backoff()
1030 def modify_snapshot_attribute(client, snapshot_id: str, **params: Dict[str, Any]) -> bool:
1031 client.modify_snapshot_attribute(SnapshotId=snapshot_id, **params)
1032 return True
1033
1034
1035 @EC2SnapshotErrorHandler.common_error_handler("create snapshot")
1036 # Handle SnapshotCreationPerVolumeRateExceeded separately because we need a much
1037 # longer delay than normal
1038 @AWSRetry.jittered_backoff(catch_extra_error_codes=["SnapshotCreationPerVolumeRateExceeded"], delay=15)
1039 def create_snapshot(client, volume_id: str, **params: Dict[str, Any]) -> Dict[str, Any]:
1040 return client.create_snapshot(VolumeId=volume_id, **params)
1041
1042
1043 # EC2 ENI
1044 class EC2NetworkInterfacesErrorHandler(AWSErrorHandler):
1045 _CUSTOM_EXCEPTION = AnsibleEC2Error
1046
1047 @classmethod
1048 def _is_missing(cls):
1049 return is_boto3_error_code("InvalidNetworkInterfaceID.NotFound")
1050
1051
1052 @EC2NetworkInterfacesErrorHandler.list_error_handler("describe network interfaces", [])
1053 @AWSRetry.jittered_backoff()
1054 def describe_network_interfaces(
1055 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
1056 ) -> List[Dict[str, Any]]:
1057 paginator = client.get_paginator("describe_network_interfaces")
1058 return paginator.paginate(**params).build_full_result()["NetworkInterfaces"]
1059
1060
1061 @EC2NetworkInterfacesErrorHandler.deletion_error_handler("delete network interface")
1062 @AWSRetry.jittered_backoff()
1063 def delete_network_interface(client, network_interface_id: str) -> bool:
1064 client.delete_network_interface(NetworkInterfaceId=network_interface_id)
1065 return True
1066
1067
1068 @EC2NetworkInterfacesErrorHandler.common_error_handler("create network interface")
1069 @AWSRetry.jittered_backoff()
1070 def create_network_interface(client, **params: Dict[str, Any]) -> Dict[str, str]:
1071 return client.create_network_interface(**params)["NetworkInterface"]
1072
1073
1074 @EC2NetworkInterfacesErrorHandler.common_error_handler("attach network interface")
1075 @AWSRetry.jittered_backoff()
1076 def attach_network_interface(
1077 client, **params: Dict[str, Union[str, int, Dict[str, Union[bool, Dict[str, bool]]]]]
1078 ) -> Dict[str, Union[str, int]]:
1079 return client.attach_network_interface(**params)
1080
1081
1082 @EC2NetworkInterfacesErrorHandler.common_error_handler("detach network interface")
1083 @AWSRetry.jittered_backoff()
1084 def detach_network_interface(client, attachment_id: str, force: Optional[bool] = None) -> bool:
1085 params = {"AttachmentId": attachment_id}
1086 if force is not None:
1087 params["Force"] = force
1088 client.detach_network_interface(**params)
1089 return True
1090
1091
1092 @EC2NetworkInterfacesErrorHandler.common_error_handler("assign private ip addresses")
1093 @AWSRetry.jittered_backoff()
1094 def assign_private_ip_addresses(
1095 client, **params: Dict[str, Union[bool, int, str, List[str]]]
1096 ) -> Dict[str, Union[str, List[Dict[str, str]]]]:
1097 return client.assign_private_ip_addresses(**params)
1098
1099
1100 @EC2NetworkInterfacesErrorHandler.common_error_handler("unassign private ip addresses")
1101 @AWSRetry.jittered_backoff()
1102 def unassign_private_ip_addresses(client, **params: Dict[str, Union[str, List[str]]]) -> bool:
1103 client.unassign_private_ip_addresses(**params)
1104 return True
1105
1106
1107 @EC2NetworkInterfacesErrorHandler.common_error_handler("modify network interface attribute")
1108 @AWSRetry.jittered_backoff()
1109 def modify_network_interface_attribute(client, **params: Dict[str, Any]) -> bool:
1110 client.modify_network_interface_attribute(**params)
1111 return True
1112
1113
1114 # EC2 Import Image
1115 class EC2ImportImageErrorHandler(AWSErrorHandler):
1116 _CUSTOM_EXCEPTION = AnsibleEC2Error
1117
1118 @classmethod
1119 def _is_missing(cls):
1120 return is_boto3_error_code("InvalidConversionTaskId")
1121
1122
1123 @EC2ImportImageErrorHandler.list_error_handler("describe import image tasks", [])
1124 @AWSRetry.jittered_backoff()
1125 def describe_import_image_tasks(
1126 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
1127 ) -> List[Dict[str, Any]]:
1128 paginator = client.get_paginator("describe_import_image_tasks")
1129 return paginator.paginate(**params).build_full_result()["ImportImageTasks"]
1130
1131
1132 def describe_import_image_tasks_as_snake_dict(
1133 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
1134 ) -> List[Dict[str, Any]]:
1135 result = []
1136 for import_image_info in describe_import_image_tasks(client, **params):
1137 image = copy.deepcopy(import_image_info)
1138 image["Tags"] = boto3_tag_list_to_ansible_dict(image["Tags"])
1139 result.append(camel_dict_to_snake_dict(image, ignore_list=["Tags"]))
1140 return result
1141
1142
1143 @EC2ImportImageErrorHandler.deletion_error_handler("cancel import task")
1144 @AWSRetry.jittered_backoff()
1145 def cancel_import_task(client, import_task_id: str, cancel_reason: Optional[str] = None) -> bool:
1146 params = {"ImportTaskId": import_task_id}
1147 if cancel_reason:
1148 params["CancelReason"] = cancel_reason
1149 client.cancel_import_task(**params)
1150 return True
1151
1152
1153 @EC2ImportImageErrorHandler.common_error_handler("import image")
1154 @AWSRetry.jittered_backoff()
1155 def import_image(client, **params: Dict[str, Any]) -> Dict[str, Any]:
1156 return client.import_image(**params)
1157
1158
1159 # EC2 Spot instance
1160 class EC2SpotInstanceRequestErrorHandler(AWSErrorHandler):
1161 _CUSTOM_EXCEPTION = AnsibleEC2Error
1162
1163 @classmethod
1164 def _is_missing(cls):
1165 return is_boto3_error_code("InvalidSpotInstanceRequestID.NotFound")
1166
1167
1168 @EC2SpotInstanceRequestErrorHandler.list_error_handler("describe spot instance requests", [])
1169 @AWSRetry.jittered_backoff()
1170 def describe_spot_instance_requests(
1171 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
1172 ) -> List[Dict[str, Any]]:
1173 paginator = client.get_paginator("describe_spot_instance_requests")
1174 return paginator.paginate(**params).build_full_result()["SpotInstanceRequests"]
1175
1176
1177 @EC2SpotInstanceRequestErrorHandler.common_error_handler("cancel spot instance requests")
1178 @AWSRetry.jittered_backoff()
1179 def cancel_spot_instance_requests(client, spot_instance_request_ids: List[str]) -> List[Dict[str, str]]:
1180 return client.cancel_spot_instance_requests(SpotInstanceRequestIds=spot_instance_request_ids)[
1181 "CancelledSpotInstanceRequests"
1182 ]
1183
1184
1185 @EC2SpotInstanceRequestErrorHandler.common_error_handler("request spot instances")
1186 @AWSRetry.jittered_backoff()
1187 def request_spot_instances(client, **params: Dict[str, Any]) -> List[Dict[str, Any]]:
1188 return client.request_spot_instances(**params)["SpotInstanceRequests"]
1189
1190
1191 # EC2 Security Groups
1192 class EC2SecurityGroupsErrorHandler(AWSErrorHandler):
1193 _CUSTOM_EXCEPTION = AnsibleEC2Error
1194
1195 @classmethod
1196 def _is_missing(cls):
1197 return is_boto3_error_code("InvalidGroup.NotFound")
1198
1199
1200 @EC2SecurityGroupsErrorHandler.list_error_handler("describe security groups", [])
1201 @AWSRetry.jittered_backoff()
1202 def describe_security_groups(
1203 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
1204 ) -> List[Dict[str, Any]]:
1205 paginator = client.get_paginator("describe_security_groups")
1206 return paginator.paginate(**params).build_full_result()["SecurityGroups"]
1207
1208
1209 @EC2SecurityGroupsErrorHandler.deletion_error_handler("delete security group")
1210 @AWSRetry.jittered_backoff()
1211 def delete_security_group(client, group_id: Optional[str], group_name: Optional[str] = None) -> bool:
1212 params = {}
1213 if group_id:
1214 params["GroupId"] = group_id
1215 if group_name:
1216 params["GroupName"] = group_name
1217 client.delete_security_group(**params)
1218 return True
1219
1220
1221 @EC2SecurityGroupsErrorHandler.common_error_handler("create security group")
1222 @AWSRetry.jittered_backoff()
1223 def create_security_group(client, **params: Dict[str, Union[str, EC2TagSpecifications]]) -> Dict[str, Any]:
1224 return client.create_security_group(**params)
1225
1226
1227 @EC2SecurityGroupsErrorHandler.common_error_handler("update security group rule descriptions egress")
1228 @AWSRetry.jittered_backoff()
1229 def update_security_group_rule_descriptions_egress(client, **params: Dict[str, Any]) -> bool:
1230 return client.update_security_group_rule_descriptions_egress(**params)["Return"]
1231
1232
1233 @EC2SecurityGroupsErrorHandler.common_error_handler("update security group rule descriptions ingress")
1234 @AWSRetry.jittered_backoff()
1235 def update_security_group_rule_descriptions_ingress(client, **params: Dict[str, Any]) -> bool:
1236 return client.update_security_group_rule_descriptions_ingress(**params)["Return"]
1237
1238
1239 @EC2SecurityGroupsErrorHandler.common_error_handler("revoke security group ingress")
1240 @AWSRetry.jittered_backoff()
1241 def revoke_security_group_ingress(client, **params: Dict[str, Any]) -> bool:
1242 return client.revoke_security_group_ingress(**params)["Return"]
1243
1244
1245 @EC2SecurityGroupsErrorHandler.common_error_handler("revoke security group egress")
1246 @AWSRetry.jittered_backoff()
1247 def revoke_security_group_egress(client, **params: Dict[str, Any]) -> bool:
1248 return client.revoke_security_group_egress(**params)["Return"]
1249
1250
1251 @EC2SecurityGroupsErrorHandler.common_error_handler("authorize security group ingress")
1252 @AWSRetry.jittered_backoff()
1253 def authorize_security_group_ingress(client, **params: Dict[str, Any]) -> bool:
1254 return client.authorize_security_group_ingress(**params)["Return"]
1255
1256
1257 @EC2SecurityGroupsErrorHandler.common_error_handler("authorize security group egress")
1258 @AWSRetry.jittered_backoff()
1259 def authorize_security_group_egress(client, **params: Dict[str, Any]) -> bool:
1260 return client.authorize_security_group_egress(**params)["Return"]
1261
1262
1263 # EC2 Egress only internet Gateway
1264 class EC2EgressOnlyInternetGatewayErrorHandler(AWSErrorHandler):
1265 _CUSTOM_EXCEPTION = AnsibleEC2Error
1266
1267 @classmethod
1268 def _is_missing(cls):
1269 return is_boto3_error_code("InvalidGatewayID.NotFound")
1270
1271
1272 @EC2EgressOnlyInternetGatewayErrorHandler.list_error_handler("describe egress only internet gateways", [])
1273 @AWSRetry.jittered_backoff()
1274 def describe_egress_only_internet_gateways(
1275 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
1276 ) -> List[Dict[str, Any]]:
1277 paginator = client.get_paginator("describe_egress_only_internet_gateways")
1278 return paginator.paginate(**params).build_full_result()["EgressOnlyInternetGateways"]
1279
1280
1281 @EC2EgressOnlyInternetGatewayErrorHandler.deletion_error_handler("delete egress only internet gateway")
1282 @AWSRetry.jittered_backoff()
1283 def delete_egress_only_internet_gateway(client, egress_only_internet_gateway_id: str) -> bool:
1284 return client.delete_egress_only_internet_gateway(EgressOnlyInternetGatewayId=egress_only_internet_gateway_id)[
1285 "ReturnCode"
1286 ]
1287
1288
1289 @EC2EgressOnlyInternetGatewayErrorHandler.common_error_handler("create egress only internet gateway")
1290 @AWSRetry.jittered_backoff()
1291 def create_egress_only_internet_gateway(
1292 client, vpc_id: str, tags: Optional[EC2TagSpecifications] = None
1293 ) -> Dict[str, Any]:
1294 params = {"VpcId": vpc_id}
1295 if tags:
1296 params["TagSpecifications"] = boto3_tag_specifications(tags, types="egress-only-internet-gateway")
1297 return client.create_egress_only_internet_gateway(**params)
1298
1299
1300 # EC2 Network ACL
1301 class EC2NetworkAclErrorHandler(AWSErrorHandler):
1302 _CUSTOM_EXCEPTION = AnsibleEC2Error
1303
1304 @classmethod
1305 def _is_missing(cls):
1306 return is_boto3_error_code("InvalidNetworkAclID.NotFound")
1307
1308
1309 @EC2NetworkAclErrorHandler.list_error_handler("describe network acls", [])
1310 @AWSRetry.jittered_backoff()
1311 def describe_network_acls(
1312 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
1313 ) -> List[Dict[str, Any]]:
1314 paginator = client.get_paginator("describe_network_acls")
1315 return paginator.paginate(**params).build_full_result()["NetworkAcls"]
1316
1317
1318 @EC2NetworkAclErrorHandler.common_error_handler("create network acl")
1319 @AWSRetry.jittered_backoff()
1320 def create_network_acl(client, vpc_id: str, tags: Optional[EC2TagSpecifications] = None) -> Dict[str, Any]:
1321 params = {"VpcId": vpc_id}
1322 if tags:
1323 params["TagSpecifications"] = boto3_tag_specifications(tags, types="network-acl")
1324 return client.create_network_acl(**params)["NetworkAcl"]
1325
1326
1327 @EC2NetworkAclErrorHandler.common_error_handler("create network acl entry")
1328 @AWSRetry.jittered_backoff()
1329 def create_network_acl_entry(
1330 client,
1331 network_acl_id: str,
1332 protocol: str,
1333 egress: bool,
1334 rule_action: str,
1335 rule_number: int,
1336 **params: Dict[str, Any],
1337 ) -> bool:
1338 args = {
1339 "Egress": egress,
1340 "NetworkAclId": network_acl_id,
1341 "Protocol": protocol,
1342 "RuleAction": rule_action,
1343 "RuleNumber": rule_number,
1344 }
1345 if params:
1346 args.update(params)
1347 client.create_network_acl_entry(**args)
1348 return True
1349
1350
1351 @EC2NetworkAclErrorHandler.deletion_error_handler("delete network acl")
1352 @AWSRetry.jittered_backoff()
1353 def delete_network_acl(client, network_acl_id: str) -> bool:
1354 client.delete_network_acl(NetworkAclId=network_acl_id)
1355 return True
1356
1357
1358 @EC2NetworkAclErrorHandler.deletion_error_handler("delete network acl entry")
1359 @AWSRetry.jittered_backoff()
1360 def delete_network_acl_entry(client, network_acl_id: str, rule_number: int, egress: bool) -> bool:
1361 client.delete_network_acl_entry(NetworkAclId=network_acl_id, Egress=egress, RuleNumber=rule_number)
1362 return True
1363
1364
1365 @EC2NetworkAclErrorHandler.common_error_handler("replace network acl entry")
1366 @AWSRetry.jittered_backoff()
1367 def replace_network_acl_entry(
1368 client,
1369 network_acl_id: str,
1370 protocol: str,
1371 egress: bool,
1372 rule_action: str,
1373 rule_number: int,
1374 **params: Dict[str, Any],
1375 ) -> Dict[str, Any]:
1376 args = {
1377 "Egress": egress,
1378 "NetworkAclId": network_acl_id,
1379 "Protocol": protocol,
1380 "RuleAction": rule_action,
1381 "RuleNumber": rule_number,
1382 }
1383 if params:
1384 args.update(params)
1385 return client.replace_network_acl_entry(**args)
1386
1387
1388 @EC2NetworkAclErrorHandler.common_error_handler("replace network acl association")
1389 @AWSRetry.jittered_backoff()
1390 def replace_network_acl_association(client, network_acl_id: str, association_id: str) -> str:
1391 return client.replace_network_acl_association(NetworkAclId=network_acl_id, AssociationId=association_id)[
1392 "NewAssociationId"
1393 ]
1394
1395
1396 # EC2 Placement Group
1397 class EC2PlacementGroupErrorHandler(AWSErrorHandler):
1398 _CUSTOM_EXCEPTION = AnsibleEC2Error
1399
1400 @classmethod
1401 def _is_missing(cls):
1402 return is_boto3_error_code("InvalidPlacementGroup.Unknown")
1403
1404
1405 @EC2PlacementGroupErrorHandler.list_error_handler("describe placement group", [])
1406 @AWSRetry.jittered_backoff()
1407 def describe_ec2_placement_groups(
1408 client, **params: Dict[str, Union[List[str], int, List[Dict[str, Union[str, List[str]]]]]]
1409 ) -> List[Dict[str, Any]]:
1410 return client.describe_placement_groups(**params)["PlacementGroups"]
1411
1412
1413 @EC2PlacementGroupErrorHandler.deletion_error_handler("delete placement group")
1414 @AWSRetry.jittered_backoff()
1415 def delete_ec2_placement_group(client, group_name: str) -> bool:
1416 client.delete_placement_group(GroupName=group_name)
1417 return True
1418
1419
1420 @EC2PlacementGroupErrorHandler.common_error_handler("create placement group")
1421 @AWSRetry.jittered_backoff()
1422 def create_ec2_placement_group(client, **params: Dict[str, Union[str, EC2TagSpecifications]]) -> Dict[str, Any]:
1423 return client.create_placement_group(**params)["PlacementGroup"]
1424
1425
1426 # EC2 Launch template
1427 class EC2LaunchTemplateErrorHandler(AWSErrorHandler):
1428 _CUSTOM_EXCEPTION = AnsibleEC2Error
1429
1430 @classmethod
1431 def _is_missing(cls):
1432 return is_boto3_error_code(["InvalidLaunchTemplateName.NotFoundException", "InvalidLaunchTemplateId.NotFound"])
1433
1434
1435 @EC2LaunchTemplateErrorHandler.list_error_handler("describe launch templates", [])
1436 @AWSRetry.jittered_backoff()
1437 def describe_launch_templates(
1438 client,
1439 launch_template_ids: Optional[List[str]] = None,
1440 launch_template_names: Optional[List[str]] = None,
1441 filters: Optional[List[Dict[str, List[str]]]] = None,
1442 ) -> List[Dict[str, Any]]:
1443 params = {}
1444 if launch_template_ids:
1445 params["LaunchTemplateIds"] = launch_template_ids
1446 if launch_template_names:
1447 params["LaunchTemplateNames"] = launch_template_names
1448 if filters:
1449 params["Filters"] = filters
1450 paginator = client.get_paginator("describe_launch_templates")
1451 return paginator.paginate(**params).build_full_result()["LaunchTemplates"]
1452
1453
1454 @EC2LaunchTemplateErrorHandler.common_error_handler("describe launch template versions")
1455 @AWSRetry.jittered_backoff()
1456 def describe_launch_template_versions(client, **params: Dict[str, Any]) -> List[Dict[str, Any]]:
1457 paginator = client.get_paginator("describe_launch_template_versions")
1458 return paginator.paginate(**params).build_full_result()["LaunchTemplateVersions"]
1459
1460
1461 @EC2LaunchTemplateErrorHandler.common_error_handler("delete launch template versions")
1462 @AWSRetry.jittered_backoff()
1463 def delete_launch_template_versions(
1464 client, versions: List[str], launch_template_id: Optional[str] = None, launch_template_name: Optional[str] = None
1465 ) -> Dict[str, Any]:
1466 params = {}
1467 if launch_template_id:
1468 params["LaunchTemplateId"] = launch_template_id
1469 if launch_template_name:
1470 params["LaunchTemplateName"] = launch_template_name
1471 response = {
1472 "UnsuccessfullyDeletedLaunchTemplateVersions": [],
1473 "SuccessfullyDeletedLaunchTemplateVersions": [],
1474 }
1475 # Using this API, You can specify up to 200 launch template version numbers.
1476 for i in range(0, len(versions), 200):
1477 result = client.delete_launch_template_versions(Versions=list(versions[i : i + 200]), **params)
1478 for x in ("SuccessfullyDeletedLaunchTemplateVersions", "UnsuccessfullyDeletedLaunchTemplateVersions"):
1479 response[x] += result.get(x, [])
1480 return response
1481
1482
1483 @EC2LaunchTemplateErrorHandler.common_error_handler("delete launch template")
1484 @AWSRetry.jittered_backoff()
1485 def delete_launch_template(
1486 client, launch_template_id: Optional[str] = None, launch_template_name: Optional[str] = None
1487 ) -> Dict[str, Any]:
1488 params = {}
1489 if launch_template_id:
1490 params["LaunchTemplateId"] = launch_template_id
1491 if launch_template_name:
1492 params["LaunchTemplateName"] = launch_template_name
1493 return client.delete_launch_template(**params)["LaunchTemplate"]
1494
1495
1496 @EC2LaunchTemplateErrorHandler.common_error_handler("create launch template")
1497 @AWSRetry.jittered_backoff()
1498 def create_launch_template(
1499 client,
1500 launch_template_name: str,
1501 launch_template_data: Dict[str, Any],
1502 tags: Optional[EC2TagSpecifications] = None,
1503 **kwargs: Dict[str, Any],
1504 ) -> Dict[str, Any]:
1505 params = {"LaunchTemplateName": launch_template_name, "LaunchTemplateData": launch_template_data}
1506 if tags:
1507 params["TagSpecifications"] = boto3_tag_specifications(tags, types="launch-template")
1508 params.update(kwargs)
1509 return client.create_launch_template(**params)["LaunchTemplate"]
1510
1511
1512 @EC2LaunchTemplateErrorHandler.common_error_handler("create launch template version")
1513 @AWSRetry.jittered_backoff()
1514 def create_launch_template_version(
1515 client, launch_template_data: Dict[str, Any], **params: Dict[str, Any]
1516 ) -> Dict[str, Any]:
1517 return client.create_launch_template_version(LaunchTemplateData=launch_template_data, **params)[
1518 "LaunchTemplateVersion"
1519 ]
1520
1521
1522 @EC2LaunchTemplateErrorHandler.common_error_handler("modify launch template")
1523 @AWSRetry.jittered_backoff()
1524 def modify_launch_template(client, **params: Dict[str, Any]) -> Dict[str, Any]:
1525 return client.modify_launch_template(**params)["LaunchTemplate"]
1526
1527
1528 def get_ec2_security_group_ids_from_names(sec_group_list, ec2_connection, vpc_id=None, boto3=None):
1529 """Return list of security group IDs from security group names. Note that security group names are not unique
1530 across VPCs. If a name exists across multiple VPCs and no VPC ID is supplied, all matching IDs will be returned. This
1531 will probably lead to a boto exception if you attempt to assign both IDs to a resource so ensure you wrap the call in
1532 a try block
1533 """
1534
1535 def get_sg_name(sg):
1536 return str(sg["GroupName"])
1537
1538 def get_sg_id(sg):
1539 return str(sg["GroupId"])
1540
1541 sec_group_id_list = []
1542
1543 if isinstance(sec_group_list, str):
1544 sec_group_list = [sec_group_list]
1545
1546 # Get all security groups
1547 if vpc_id:
1548 filters = [
1549 {
1550 "Name": "vpc-id",
1551 "Values": [
1552 vpc_id,
1553 ],
1554 }
1555 ]
1556 all_sec_groups = ec2_connection.describe_security_groups(Filters=filters)["SecurityGroups"]
1557 else:
1558 all_sec_groups = ec2_connection.describe_security_groups()["SecurityGroups"]
1559
1560 unmatched = set(sec_group_list).difference(str(get_sg_name(all_sg)) for all_sg in all_sec_groups)
1561 sec_group_name_list = list(set(sec_group_list) - set(unmatched))
1562
1563 if len(unmatched) > 0:
1564 # If we have unmatched names that look like an ID, assume they are
1565 sec_group_id_list[:] = [sg for sg in unmatched if re.match("sg-[a-fA-F0-9]+$", sg)]
1566 still_unmatched = [sg for sg in unmatched if not re.match("sg-[a-fA-F0-9]+$", sg)]
1567 if len(still_unmatched) > 0:
1568 raise ValueError(f"The following group names are not valid: {', '.join(still_unmatched)}")
1569
1570 sec_group_id_list += [get_sg_id(all_sg) for all_sg in all_sec_groups if get_sg_name(all_sg) in sec_group_name_list]
1571
1572 return sec_group_id_list
1573
1574
1575 # EC2 Transit Gateway VPC Attachment Error handler
1576 class EC2TransitGatewayVPCAttachmentErrorHandler(AWSErrorHandler):
1577 _CUSTOM_EXCEPTION = AnsibleEC2Error
1578
1579 @classmethod
1580 def _is_missing(cls):
1581 return is_boto3_error_code("InvalidGatewayID.NotFound")
1582
1583
1584 @EC2TransitGatewayVPCAttachmentErrorHandler.common_error_handler("describe transit gateway vpc attachments")
1585 @AWSRetry.jittered_backoff()
1586 def describe_transit_gateway_vpc_attachments(
1587 client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
1588 ) -> List:
1589 paginator = client.get_paginator("describe_transit_gateway_vpc_attachments")
1590 return paginator.paginate(**params).build_full_result()["TransitGatewayVpcAttachments"]
1591
1592
1593 @EC2TransitGatewayVPCAttachmentErrorHandler.common_error_handler("create transit gateway vpc attachment")
1594 @AWSRetry.jittered_backoff()
1595 def create_transit_gateway_vpc_attachment(
1596 client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
1597 ) -> Dict[str, Any]:
1598 return client.create_transit_gateway_vpc_attachment(**params)["TransitGatewayVpcAttachment"]
1599
1600
1601 @EC2TransitGatewayVPCAttachmentErrorHandler.common_error_handler("modify transit gateway vpc attachment")
1602 @AWSRetry.jittered_backoff()
1603 def modify_transit_gateway_vpc_attachment(
1604 client, **params: Dict[str, Union[List[str], bool, List[Dict[str, Union[str, List[str]]]]]]
1605 ) -> Dict[str, Any]:
1606 return client.modify_transit_gateway_vpc_attachment(**params)["TransitGatewayVpcAttachment"]
1607
1608
1609 @EC2TransitGatewayVPCAttachmentErrorHandler.deletion_error_handler("delete transit gateway vpc attachment")
1610 @AWSRetry.jittered_backoff()
1611 def delete_transit_gateway_vpc_attachment(client, transit_gateway_attachment_id: str) -> bool:
1612 client.delete_transit_gateway_vpc_attachment(TransitGatewayAttachmentId=transit_gateway_attachment_id)[
1613 "TransitGatewayVpcAttachment"
1614 ]
1615 return True
1616
1617
1618 def add_ec2_tags(client, module, resource_id, tags_to_set, retry_codes=None):
1619 """
1620 Sets Tags on an EC2 resource.
1621
1622 :param client: an EC2 boto3 client
1623 :param module: an AnsibleAWSModule object
1624 :param resource_id: the identifier for the resource
1625 :param tags_to_set: A dictionary of key/value pairs to set
1626 :param retry_codes: additional boto3 error codes to trigger retries
1627 """
1628
1629 if not tags_to_set:
1630 return False
1631 if module.check_mode:
1632 return True
1633
1634 if not retry_codes:
1635 retry_codes = []
1636
1637 try:
1638 tags_to_add = ansible_dict_to_boto3_tag_list(tags_to_set)
1639 AWSRetry.jittered_backoff(retries=10, catch_extra_error_codes=retry_codes)(client.create_tags)(
1640 Resources=[resource_id], Tags=tags_to_add
1641 )
1642 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
1643 module.fail_json_aws(e, msg=f"Unable to add tags {tags_to_set} to {resource_id}")
1644 return True
1645
1646
1647 def remove_ec2_tags(client, module, resource_id, tags_to_unset, retry_codes=None):
1648 """
1649 Removes Tags from an EC2 resource.
1650
1651 :param client: an EC2 boto3 client
1652 :param module: an AnsibleAWSModule object
1653 :param resource_id: the identifier for the resource
1654 :param tags_to_unset: a list of tag keys to removes
1655 :param retry_codes: additional boto3 error codes to trigger retries
1656 """
1657
1658 if not tags_to_unset:
1659 return False
1660 if module.check_mode:
1661 return True
1662
1663 if not retry_codes:
1664 retry_codes = []
1665
1666 tags_to_remove = [dict(Key=tagkey) for tagkey in tags_to_unset]
1667
1668 try:
1669 AWSRetry.jittered_backoff(retries=10, catch_extra_error_codes=retry_codes)(client.delete_tags)(
1670 Resources=[resource_id], Tags=tags_to_remove
1671 )
1672 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
1673 module.fail_json_aws(e, msg=f"Unable to delete tags {tags_to_unset} from {resource_id}")
1674 return True
1675
1676
1677 def describe_ec2_tags(client, module, resource_id, resource_type=None, retry_codes=None):
1678 """
1679 Performs a paginated search of EC2 resource tags.
1680
1681 :param client: an EC2 boto3 client
1682 :param module: an AnsibleAWSModule object
1683 :param resource_id: the identifier for the resource
1684 :param resource_type: the type of the resource
1685 :param retry_codes: additional boto3 error codes to trigger retries
1686 """
1687 filters = {"resource-id": resource_id}
1688 if resource_type:
1689 filters["resource-type"] = resource_type
1690 filters = ansible_dict_to_boto3_filter_list(filters)
1691
1692 if not retry_codes:
1693 retry_codes = []
1694
1695 try:
1696 retry_decorator = AWSRetry.jittered_backoff(retries=10, catch_extra_error_codes=retry_codes)
1697 results = paginated_query_with_retries(
1698 client, "describe_tags", retry_decorator=retry_decorator, Filters=filters
1699 )
1700 return boto3_tag_list_to_ansible_dict(results.get("Tags", None))
1701 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
1702 module.fail_json_aws(e, msg=f"Failed to describe tags for EC2 Resource: {resource_id}")
1703
1704
1705 def ensure_ec2_tags(client, module, resource_id, resource_type=None, tags=None, purge_tags=True, retry_codes=None):
1706 """
1707 Updates the tags on an EC2 resource.
1708
1709 To remove all tags the tags parameter must be explicitly set to an empty dictionary.
1710
1711 :param client: an EC2 boto3 client
1712 :param module: an AnsibleAWSModule object
1713 :param resource_id: the identifier for the resource
1714 :param resource_type: the type of the resource
1715 :param tags: the Tags to apply to the resource
1716 :param purge_tags: whether tags missing from the tag list should be removed
1717 :param retry_codes: additional boto3 error codes to trigger retries
1718 :return: changed: returns True if the tags are changed
1719 """
1720
1721 if tags is None:
1722 return False
1723
1724 if not retry_codes:
1725 retry_codes = []
1726
1727 changed = False
1728 current_tags = describe_ec2_tags(client, module, resource_id, resource_type, retry_codes)
1729
1730 tags_to_set, tags_to_unset = compare_aws_tags(current_tags, tags, purge_tags)
1731
1732 if purge_tags and not tags:
1733 tags_to_unset = current_tags
1734
1735 changed |= remove_ec2_tags(client, module, resource_id, tags_to_unset, retry_codes)
1736 changed |= add_ec2_tags(client, module, resource_id, tags_to_set, retry_codes)
1737
1738 return changed
1739
1740
1741 def normalize_ec2_vpc_dhcp_config(option_config: List[Dict[str, Any]]) -> Dict[str, Any]:
1742 """
1743 The boto2 module returned a config dict, but boto3 returns a list of dicts
1744 Make the data we return look like the old way, so we don't break users.
1745 This is also much more user-friendly.
1746 boto3:
1747 'DhcpConfigurations': [
1748 {'Key': 'domain-name', 'Values': [{'Value': 'us-west-2.compute.internal'}]},
1749 {'Key': 'domain-name-servers', 'Values': [{'Value': 'AmazonProvidedDNS'}]},
1750 {'Key': 'netbios-name-servers', 'Values': [{'Value': '1.2.3.4'}, {'Value': '5.6.7.8'}]},
1751 {'Key': 'netbios-node-type', 'Values': [1]},
1752 {'Key': 'ntp-servers', 'Values': [{'Value': '1.2.3.4'}, {'Value': '5.6.7.8'}]}
1753 ],
1754 The module historically returned:
1755 "new_options": {
1756 "domain-name": "ec2.internal",
1757 "domain-name-servers": ["AmazonProvidedDNS"],
1758 "netbios-name-servers": ["10.0.0.1", "10.0.1.1"],
1759 "netbios-node-type": "1",
1760 "ntp-servers": ["10.0.0.2", "10.0.1.2"]
1761 },
1762 """
1763 config_data = {}
1764
1765 if len(option_config) == 0:
1766 # If there is no provided config, return the empty dictionary
1767 return config_data
1768
1769 for config_item in option_config:
1770 # Handle single value keys
1771 if config_item["Key"] == "netbios-node-type":
1772 if isinstance(config_item["Values"], int):
1773 config_data["netbios-node-type"] = str((config_item["Values"]))
1774 elif isinstance(config_item["Values"], list):
1775 config_data["netbios-node-type"] = str((config_item["Values"][0]["Value"]))
1776 # Handle actual lists of values
1777 for option in ["domain-name", "domain-name-servers", "ntp-servers", "netbios-name-servers"]:
1778 if config_item["Key"] == option:
1779 config_data[option] = [val["Value"] for val in config_item["Values"]]
1780
1781 return config_data
1782
1783
1784 def determine_iam_arn_from_name(iam_client, name_or_arn: str) -> str:
1785 if validate_aws_arn(name_or_arn, service="iam", resource_type="instance-profile"):
1786 return name_or_arn
1787
1788 iam_instance_profiles = list_iam_instance_profiles(iam_client, name=name_or_arn)
1789 if not iam_instance_profiles:
1790 raise AnsibleEC2Error(message=f"Could not find IAM instance profile {name_or_arn}")
1791 return iam_instance_profiles[0]["Arn"]
1792
1793
1794 # EC2 Transit Gateway
1795 class EC2TransitGatewayErrorHandler(AWSErrorHandler):
1796 _CUSTOM_EXCEPTION = AnsibleEC2Error
1797
1798 @classmethod
1799 def _is_missing(cls):
1800 return is_boto3_error_code("InvalidTransitGatewayID.NotFound")
1801
1802
1803 @EC2TransitGatewayErrorHandler.list_error_handler("describe transit gateway", [])
1804 @AWSRetry.jittered_backoff()
1805 def describe_ec2_transit_gateways(
1806 client, **params: Dict[str, Union[List[str], List[Dict[str, Union[str, List[str]]]]]]
1807 ) -> List[Dict[str, Any]]:
1808 paginator = client.get_paginator("describe_transit_gateways")
1809 return paginator.paginate(**params).build_full_result()["TransitGateways"]
1810
1811
1812 @EC2TransitGatewayErrorHandler.common_error_handler("create transit gateway")
1813 @AWSRetry.jittered_backoff()
1814 def create_ec2_transit_gateway(
1815 client, **params: Dict[str, Union[List[str], List[Dict[str, Union[str, List[str]]]]]]
1816 ) -> Dict[str, Any]:
1817 return client.create_transit_gateway(**params)["TransitGateway"]
1818
1819
1820 @EC2TransitGatewayErrorHandler.deletion_error_handler("delete transit gateway")
1821 @AWSRetry.jittered_backoff()
1822 def delete_ec2_transit_gateway(client, transit_gateway_id: str) -> bool:
1823 client.delete_transit_gateway(TransitGatewayId=transit_gateway_id)
1824 return True
1825
1826
1827 # EC2 Dedicated host
1828 class EC2DedicatedHost(AWSErrorHandler):
1829 _CUSTOM_EXCEPTION = AnsibleEC2Error
1830
1831 @classmethod
1832 def _is_missing(cls):
1833 return is_boto3_error_code("InvalidHostID.NotFound")
1834
1835
1836 @EC2DedicatedHost.list_error_handler("describe dedicated host", [])
1837 @AWSRetry.jittered_backoff()
1838 def describe_ec2_dedicated_hosts(
1839 client, **params: Dict[str, Union[List[str], List[Dict[str, Union[str, List[str]]]]]]
1840 ) -> List[Dict[str, Any]]:
1841 paginator = client.get_paginator("describe_hosts")
1842 return paginator.paginate(**params).build_full_result()["Hosts"]
1843
1844
1845 @EC2DedicatedHost.list_error_handler("describe mac dedicated host", [])
1846 @AWSRetry.jittered_backoff()
1847 def describe_ec2_mac_dedicated_hosts(
1848 client, **params: Dict[str, Union[List[str], List[Dict[str, Union[str, List[str]]]]]]
1849 ) -> List[Dict[str, Any]]:
1850 paginator = client.get_paginator("describe_mac_hosts")
1851 return paginator.paginate(**params).build_full_result()["MacHosts"]
1852
1853
1854 @EC2DedicatedHost.deletion_error_handler("release dedicated host")
1855 @AWSRetry.jittered_backoff()
1856 def release_ec2_dedicated_host(client, host_id: Union[str, List[str]]) -> bool:
1857 host_ids = host_id
1858 if isinstance(host_id, str):
1859 host_ids = [host_id]
1860 client.release_hosts(HostIds=host_ids)
1861 return True
1862
1863
1864 @EC2DedicatedHost.common_error_handler("allocate dedicated hosts")
1865 @AWSRetry.jittered_backoff()
1866 def allocate_ec2_dedicated_hosts(
1867 client, availability_zone: str, **params: Dict[str, Union[List[str], List[Dict[str, Union[str, List[str]]]]]]
1868 ) -> List[str]:
1869 return client.allocate_hosts(AvailabilityZone=availability_zone, **params)["HostIds"]
1870
1871
1872 @EC2DedicatedHost.common_error_handler("modify dedicated hosts")
1873 @AWSRetry.jittered_backoff()
1874 def modify_ec2_dedicated_hosts(
1875 client,
1876 host_id: Union[List[str], str],
1877 **params: Dict[str, Union[List[str], List[Dict[str, Union[str, List[str]]]]]],
1878 ) -> Dict[str, Any]:
1879 host_ids = host_id
1880 if isinstance(host_id, str):
1881 host_ids = [host_id]
1882 return client.modify_hosts(HostIds=host_ids, **params)