Debian Codegraph @

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

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from copy import deepcopy
7
8 try:
9 from botocore.exceptions import WaiterError
10 except ImportError:
11 pass
12
13 from typing import Any
14 from typing import Dict
15 from typing import List
16 from typing import Optional
17 from typing import Tuple
18
19 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
20
21 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
22 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_transit_gateway_vpc_attachment
23 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_transit_gateway_vpc_attachment
24 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_subnets
25 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_transit_gateway_vpc_attachments
26 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags
27 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import modify_transit_gateway_vpc_attachment
28 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
29 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
30 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications
31 from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list
32 from ansible_collections.amazon.aws.plugins.module_utils.transformation import boto3_resource_to_ansible_dict
33 from ansible_collections.amazon.aws.plugins.module_utils.waiters import get_waiter
34
35
36 def get_states() -> List[str]:
37 return [
38 "available",
39 "deleting",
40 "failed",
41 "failing",
42 "initiatingRequest",
43 "modifying",
44 "pendingAcceptance",
45 "pending",
46 "rollingBack",
47 "rejected",
48 "rejecting",
49 ]
50
51
52 def subnets_to_vpc(
53 client, module: AnsibleAWSModule, subnets: List[str], subnet_details: Optional[List[Dict[str, Any]]] = None
54 ) -> Optional[str]:
55 if not subnets:
56 return None
57
58 if subnet_details is None:
59 try:
60 subnet_details = describe_subnets(client, SubnetIds=list(subnets))
61 except AnsibleEC2Error as e:
62 module.fail_json_aws_error(e)
63
64 vpcs = [s.get("VpcId") for s in subnet_details]
65 if len(set(vpcs)) > 1:
66 module.fail_json(
67 msg="Attachment subnets may only be in one VPC, multiple VPCs found",
68 vpcs=list(set(vpcs)),
69 subnets=subnet_details,
70 )
71
72 return vpcs[0]
73
74
75 def find_existing_attachment(
76 client, module: AnsibleAWSModule, filters: Optional[Dict[str, Any]] = None, attachment_id: Optional[str] = None
77 ) -> Optional[Dict[str, Any]]:
78 """Find an existing transit gateway attachment based on filters or attachment ID.
79
80 Args:
81 client: The AWS client used to interact with the EC2 service.
82 module: The Ansible module instance used for error handling.
83 filters (Optional[Dict[str, Any]]): A dictionary of filters to apply when searching for attachments.
84 attachment_id (Optional[str]): The ID of a specific attachment to find.
85
86 Returns:
87 Optional[Dict[str, Any]]: The found attachment details or None if not found.
88
89 Raises:
90 ValueError: If multiple attachments match the criteria.
91 """
92 # Find an existing attachment based on filters
93 params = {}
94
95 if attachment_id:
96 params["TransitGatewayAttachmentIds"] = [attachment_id]
97 elif filters:
98 params["Filters"] = ansible_dict_to_boto3_filter_list(filters)
99
100 try:
101 attachments = describe_transit_gateway_vpc_attachments(client, **params)
102 except AnsibleEC2Error as e:
103 module.fail_json_aws_error(e)
104
105 if len(attachments) > 1:
106 raise ValueError("Multiple matching attachments found, provide an ID.")
107
108 return attachments[0] if attachments else None
109
110
111 class TransitGatewayAttachmentStateManager:
112 def __init__(self, client, module: AnsibleAWSModule, attachment_id: str) -> None:
113 self.client = client
114 self.module = module
115 self.attachment_id = attachment_id
116
117 @property
118 def waiter_config(self) -> Dict[str, Any]:
119 params: Dict[str, Any] = {}
120
121 delay = min(5, self.module.params.get("wait_timeout"))
122 max_attempts = self.module.params.get("wait_timeout") // delay
123 config = dict(Delay=delay, MaxAttempts=max_attempts)
124 params["WaiterConfig"] = config
125
126 return params
127
128 def create_attachment(self, params: Dict[str, Any]) -> str:
129 """
130 Create a new transit gateway attachment.
131
132 Args:
133 params (Dict[str, Any]): A dictionary containing the parameters needed to
134 create the transit gateway attachment.
135
136 Returns:
137 str: The ID of the newly created transit gateway attachment.
138
139 Raises:
140 AnsibleEC2Error: If there is an error while creating the VPC attachment,
141 it will fail the module and provide an error message.
142 """
143 try:
144 tags = params.pop("Tags")
145 except KeyError:
146 tags = None
147
148 if tags:
149 params["TagSpecifications"] = boto3_tag_specifications(tags, types=["transit-gateway-attachment"])
150
151 try:
152 response = create_transit_gateway_vpc_attachment(self.client, **params)
153 except AnsibleEC2Error as e:
154 self.module.fail_json_aws_error(e)
155
156 self.attachment_id = response["TransitGatewayAttachmentId"]
157
158 return response["TransitGatewayAttachmentId"]
159
160 def delete_attachment(self) -> bool:
161 # Delete the transit gateway attachment
162
163 if not self.attachment_id:
164 return False
165
166 if not self.module.check_mode:
167 try:
168 delete_transit_gateway_vpc_attachment(self.client, self.attachment_id)
169 except AnsibleEC2Error as e:
170 self.module.fail_json_aws_error(e)
171
172 return True
173
174 def wait_for_state_change(self, desired_state: str) -> None:
175 # Wait until attachment reaches the desired state
176 params = {"TransitGatewayAttachmentIds": [self.attachment_id]}
177 params.update(self.waiter_config)
178 waiter = get_waiter(self.client, f"transit_gateway_vpc_attachment_{desired_state}")
179
180 try:
181 waiter.wait(**params)
182 except WaiterError as e:
183 self.module.fail_json_aws(e, "Timeout waiting for State change")
184
185
186 class AttachmentConfigurationManager:
187 def __init__(self, client, module: AnsibleAWSModule, attachment_id: str, existing: Dict[str, Any]) -> None:
188 self.client = client
189 self.module = module
190 self.attachment_id = attachment_id
191
192 self.existing = existing or {}
193 self._resource_updates = {}
194 self._subnets_to_add = []
195 self._subnets_to_remove = []
196
197 @property
198 def resource_updates(self) -> Dict[str, Any]:
199 return self._resource_updates
200
201 @property
202 def subnets_to_add(self) -> List[str]:
203 return self._subnets_to_add
204
205 @property
206 def subnets_to_remove(self) -> List[str]:
207 return self._subnets_to_remove
208
209 def set_subnets(self, subnets: Optional[List[str]] = None, purge: bool = True) -> None:
210 """
211 Set or update the subnets associated with the transit gateway attachment.
212
213 Args:
214 subnets (Optional[List[str]]): A list of subnet IDs to associate with
215 the attachment.
216 purge (bool): If True, the existing subnets will be replaced with the
217 specified subnets.
218 """
219 # Set or update the subnets associated with the attachment
220 if subnets is None:
221 return
222
223 current_subnets = set(self.existing.get("SubnetIds", []))
224 desired_subnets = set(subnets)
225 if not purge:
226 desired_subnets = desired_subnets.union(current_subnets)
227
228 # We'll pull the VPC ID from the subnets, no point asking for
229 # information we 'know'.
230 try:
231 subnet_details = describe_subnets(self.client, SubnetIds=list(desired_subnets))
232 except AnsibleEC2Error as e:
233 self.module.fail_json_aws_error(e)
234 vpc_id = subnets_to_vpc(self.client, self.module, desired_subnets, subnet_details)
235 self._set_resource_value("VpcId", vpc_id, immutable=True)
236
237 # Only one subnet per-AZ is permitted
238 azs = [s.get("AvailabilityZoneId") for s in subnet_details]
239 if len(azs) != len(set(azs)):
240 self.module.fail_json(
241 msg="Only one attachment subnet per availability zone may be set.",
242 availability_zones=azs,
243 subnets=subnet_details,
244 )
245
246 self._subnets_to_add = list(desired_subnets.difference(current_subnets))
247 self._subnets_to_remove = list(current_subnets.difference(desired_subnets))
248 self._set_resource_value("SubnetIds", list(desired_subnets))
249
250 def set_dns_support(self, value):
251 return self._set_option("DnsSupport", value)
252
253 def set_ipv6_support(self, value):
254 return self._set_option("Ipv6Support", value)
255
256 def set_appliance_mode_support(self, value):
257 return self._set_option("ApplianceModeSupport", value)
258
259 def set_transit_gateway(self, tgw_id: str):
260 return self._set_resource_value("TransitGatewayId", tgw_id)
261
262 def set_vpc(self, vpc_id: str):
263 return self._set_resource_value("VpcId", vpc_id)
264
265 def set_tags(self, tags, purge_tags):
266 current_tags = boto3_tag_list_to_ansible_dict(self.existing.get("Tags", None))
267
268 if purge_tags:
269 desired_tags = deepcopy(tags)
270 else:
271 desired_tags = {**current_tags, **tags}
272
273 self._set_resource_value("Tags", desired_tags)
274
275 def _get_resource_value(self, key, default=None):
276 default_value = self.existing.get(key, default)
277 return self._resource_updates.get(key, default_value)
278
279 def _set_option(self, name: str, value: Optional[bool]) -> bool:
280 """
281 Set a VPC attachment option to either enable or disable.
282
283 Args:
284 name (str): The name of the option to be updated.
285 value (Optional[bool]): A boolean indicating whether to enable (True)
286 or disable (False) the specified option. If None, no action is
287 taken.
288
289 Returns:
290 bool: Returns True if the option was successfully set, or False if
291 no update was made (because the value was None).
292 """
293 if value is None:
294 return False
295
296 # For now VPC Attachment options are all enable/disable
297 value = "enable" if value else "disable"
298
299 options = deepcopy(self.existing.get("Options", dict()))
300 options.update(self._resource_updates.get("Options", dict()))
301 options[name] = value
302
303 return self._set_resource_value("Options", options)
304
305 def _set_resource_value(self, key, value, description: Optional[str] = None, immutable: bool = False) -> bool:
306 """
307 Set a value for a resource attribute and track changes.
308
309 Args:
310 key (str): The attribute key to be updated.
311 value (Any): The new value to set for the specified key.
312 description (Optional[str], optional): A human-readable description of the
313 resource attribute.
314 immutable (bool, optional): A flag indicating whether the attribute is
315 immutable. If True, and the resource exists, an error will be raised
316 if attempting to change the value. Defaults to False.
317
318 Returns:
319 bool: Returns True if the value was successfully set, or False if no
320 update was made.
321 """
322 if value is None or value == self._get_resource_value(key):
323 return False
324
325 if immutable and self.existing:
326 description = description or key
327 self.module.fail_json(msg=f"{description} can not be updated after creation")
328
329 self.resource_updates[key] = value
330
331 return True
332
333 def filter_immutable_resource_attributes(self, resource: Dict[str, Any]) -> Dict[str, Any]:
334 """
335 Filter out immutable resource attributes from the given resource dictionary.
336
337 Args:
338 resource (Dict[str, Any]): A dictionary representing the resource, which
339 may contain various attributes, including both mutable and immutable ones.
340
341 Returns:
342 Dict[str, Any]: A new dictionary containing only the mutable attributes
343 of the resource.
344 """
345 immutable_options = ["TransitGatewayId", "VpcId", "VpcOwnerId", "State", "SubnetIds", "CreationTime", "Tags"]
346 return {key: value for key, value in resource.items() if key not in immutable_options}
347
348
349 class TransitGatewayVpcAttachmentManager:
350 def __init__(
351 self, client, module: AnsibleAWSModule, existing: Dict[str, Any], attachment_id: Optional[str] = None
352 ) -> None:
353 self.client = client
354 self.module = module
355 self.attachment_id = attachment_id
356 self.existing = existing or {}
357 self.updated = {}
358 self.changed = False
359
360 self.state_manager = TransitGatewayAttachmentStateManager(client, module, attachment_id)
361 self.config_manager = AttachmentConfigurationManager(client, module, attachment_id, existing)
362
363 def merge_resource_changes(self, filter_immutable: bool = True) -> Dict[str, Any]:
364 """Merge existing resource attributes with updates, optionally filtering out immutable attributes.
365
366 Args:
367 filter_immutable (bool): Whether to filter out immutable resource attributes. Defaults to True.
368
369 Returns:
370 Dict[str, Any]: The merged resource attributes.
371 """
372 resource = deepcopy(self.existing)
373 resource.update(self.config_manager.resource_updates)
374
375 if filter_immutable:
376 resource = self.config_manager.filter_immutable_resource_attributes(resource)
377
378 return resource
379
380 def apply_configuration(self):
381 """Apply configuration changes to the transit gateway attachment.
382
383 Returns:
384 bool: True if configuration changes were applied, False otherwise.
385 """
386 # Apply any configuration changes to the attachment
387 if not self.attachment_id:
388 return False
389
390 updates = self.config_manager.filter_immutable_resource_attributes(self.config_manager.resource_updates)
391
392 subnets_to_add = self.config_manager.subnets_to_add
393 subnets_to_remove = self.config_manager.subnets_to_remove
394
395 # Check if there are no changes to apply
396 if not updates and not subnets_to_add and not subnets_to_remove:
397 return False
398
399 if subnets_to_add:
400 updates["AddSubnetIds"] = subnets_to_add
401 if subnets_to_remove:
402 updates["RemoveSubnetIds"] = subnets_to_remove
403
404 updates["TransitGatewayAttachmentId"] = self.attachment_id
405
406 if not self.module.check_mode:
407 try:
408 modify_transit_gateway_vpc_attachment(self.client, **updates)
409 except AnsibleEC2Error as e:
410 self.module.fail_json_aws_error(e)
411 return True
412
413 def _set_configuration_parameters(self) -> None:
414 """Set configuration parameters for the transit gateway attachment."""
415 self.config_manager.set_transit_gateway(self.module.params.get("transit_gateway"))
416 self.config_manager.set_subnets(self.module.params["subnets"], self.module.params.get("purge_subnets", True))
417 self.config_manager.set_dns_support(self.module.params.get("dns_support"))
418 self.config_manager.set_ipv6_support(self.module.params.get("ipv6_support"))
419 self.config_manager.set_appliance_mode_support(self.module.params.get("appliance_mode_support"))
420
421 def _prepare_tags(self) -> Tuple[Optional[Dict[str, str]], bool]:
422 """Prepare and return the tags and purge flag.
423
424 Returns:
425 Tuple[Optional[Dict[str, str]], bool]: A tuple containing the tags dictionary and the purge flag.
426 """
427 tags = self.module.params.get("tags")
428 purge_tags = self.module.params.get("purge_tags")
429
430 if self.module.params.get("name"):
431 new_tags = {"Name": self.module.params["name"]}
432 if tags is None:
433 purge_tags = False
434 else:
435 new_tags.update(tags)
436 tags = new_tags
437
438 return {} if tags is None else tags, purge_tags
439
440 def _create_attachment(self) -> None:
441 """Create a new transit gateway attachment."""
442 if not self.module.check_mode:
443 params = self.merge_resource_changes(filter_immutable=False)
444 self.attachment_id = self.state_manager.create_attachment(params)
445
446 if self.module.params.get("wait"):
447 self.state_manager.wait_for_state_change("available")
448
449 self.changed = True
450
451 def _update_attachment(self, tags: Dict[str, Any], purge_tags: bool) -> None:
452 """Update an existing transit gateway attachment."""
453 if self.existing.get("State") == "pending":
454 # Wait for resources to finish creating before updating
455 self.state_manager.wait_for_state_change("available")
456 elif self.existing.get("State") == "deleting":
457 self.module.fail_json(
458 msg="Deletion in progress, unable to update",
459 attachments=[boto3_resource_to_ansible_dict(self.existing)],
460 )
461
462 # Apply the configuration
463 if self.apply_configuration():
464 self.changed = True
465 if self.module.params.get("wait"):
466 self.state_manager.wait_for_state_change("available")
467
468 # Ensure tags are applied
469 self.changed |= ensure_ec2_tags(
470 self.client,
471 self.module,
472 self.attachment_id,
473 resource_type="transit-gateway-attachment",
474 tags=tags,
475 purge_tags=purge_tags,
476 )
477
478 def create_or_modify_attachment(self):
479 """Create or modify a transit gateway attachment based on the provided parameters."""
480
481 # Set the configuration parameters
482 self._set_configuration_parameters()
483
484 # Handle tags
485 tags, purge_tags = self._prepare_tags()
486
487 # Set tags in the configuration manager
488 self.config_manager.set_tags(tags, purge_tags)
489
490 if not self.existing:
491 self._create_attachment()
492 else:
493 self._update_attachment(tags, purge_tags)
494
495 # Handle check mode updates
496 if self.module.check_mode:
497 self.updated = camel_dict_to_snake_dict(
498 self.merge_resource_changes(filter_immutable=False), ignore_list=["Tags"]
499 )
500 else:
501 self.updated = boto3_resource_to_ansible_dict(
502 find_existing_attachment(self.client, self.module, attachment_id=self.attachment_id)
503 )
504
505 def delete_attachment(self):
506 """Delete attachment"""
507 if self.existing.get("State") == "deleting":
508 if self.module.params.get("wait"):
509 self.state_manager.wait_for_state_change("deleted")
510 self.change = False
511 else:
512 self.changed |= self.state_manager.delete_attachment()
513 if self.module.params.get("wait"):
514 self.state_manager.wait_for_state_change("deleted")