Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_vpc_nat_gateway.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: ec2_vpc_nat_gateway
10 version_added: 1.0.0
11 short_description: Manage AWS VPC NAT Gateways
12 description:
13 - Ensure the state of AWS VPC NAT Gateways based on their id, allocation and subnet ids.
14 options:
15 state:
16 description:
17 - Ensure NAT Gateway is present or absent.
18 default: "present"
19 choices: ["present", "absent"]
20 type: str
21 nat_gateway_id:
22 description:
23 - The id AWS dynamically allocates to the NAT Gateway on creation.
24 This is required when the absent option is present.
25 type: str
26 subnet_id:
27 description:
28 - The id of the subnet to create the NAT Gateway in. This is required
29 with the present option.
30 type: str
31 allocation_id:
32 description:
33 - The id of the elastic IP allocation. If this is not passed and the
34 eip_address is not passed. An EIP is generated for this NAT Gateway.
35 type: str
36 connectivity_type:
37 description:
38 - Indicates whether the NAT gateway supports public or private connectivity.
39 choices: ["public", "private"]
40 default: "public"
41 type: str
42 version_added: 5.5.0
43 eip_address:
44 description:
45 - The elastic IP address of the EIP you want attached to this NAT Gateway.
46 If this is not passed and the O(allocation_id) is not passed,
47 an EIP is generated for this NAT Gateway.
48 type: str
49 if_exist_do_not_create:
50 description:
51 - If a NAT Gateway exists already in the O(subnet_id), then do not create a new one.
52 required: false
53 default: false
54 type: bool
55 release_eip:
56 description:
57 - Deallocate the EIP from the VPC.
58 - Option is only valid with the absent state.
59 - You should use this with the wait option. Since you can not release an address while a delete operation is happening.
60 default: false
61 type: bool
62 wait:
63 description:
64 - Wait for operation to complete before returning.
65 default: false
66 type: bool
67 wait_timeout:
68 description:
69 - How many seconds to wait for an operation to complete before timing out.
70 default: 320
71 type: int
72 client_token:
73 description:
74 - Optional unique token to be used during create to ensure idempotency.
75 When specifying this option, ensure you specify the eip_address parameter
76 as well otherwise any subsequent runs will fail.
77 type: str
78 default_create:
79 description:
80 - When O(default_create=true) and O(eip_address) has been set, but not yet
81 allocated, the NAT gateway is created and a new EIP is automatically allocated.
82 - When O(default_create=false) and O(eip_address) has been set, but not yet
83 allocated, the module will fail.
84 - If O(eip_address) has not been set, this parameter has no effect.
85 default: false
86 type: bool
87 version_added: 6.2.0
88 author:
89 - Allen Sanabria (@linuxdynasty)
90 - Jon Hadfield (@jonhadfield)
91 - Karen Cheng (@Etherdaemon)
92 - Alina Buzachis (@alinabuzachis)
93 notes:
94 - Support for O(tags) and O(purge_tags) was added in release 1.4.0.
95 extends_documentation_fragment:
96 - amazon.aws.common.modules
97 - amazon.aws.region.modules
98 - amazon.aws.tags
99 - amazon.aws.boto3
100 """
101
102 EXAMPLES = r"""
103 # Note: These examples do not set authentication details, see the AWS Guide for details.
104
105 - name: Create new nat gateway with client token.
106 amazon.aws.ec2_vpc_nat_gateway:
107 state: present
108 subnet_id: subnet-12345678
109 eip_address: 52.1.1.1
110 region: ap-southeast-2
111 client_token: abcd-12345678
112 register: new_nat_gateway
113
114 - name: Create new nat gateway using an allocation-id and connectivity type.
115 amazon.aws.ec2_vpc_nat_gateway:
116 state: present
117 subnet_id: subnet-12345678
118 allocation_id: eipalloc-12345678
119 connectivity_type: "private"
120 region: ap-southeast-2
121 register: new_nat_gateway
122
123 - name: Create new nat gateway, using an EIP address and wait for available status.
124 amazon.aws.ec2_vpc_nat_gateway:
125 state: present
126 subnet_id: subnet-12345678
127 eip_address: 52.1.1.1
128 wait: true
129 region: ap-southeast-2
130 register: new_nat_gateway
131
132 - name: Create new nat gateway and allocate new EIP.
133 amazon.aws.ec2_vpc_nat_gateway:
134 state: present
135 subnet_id: subnet-12345678
136 wait: true
137 region: ap-southeast-2
138 register: new_nat_gateway
139
140 - name: Create new nat gateway and allocate new EIP if a nat gateway does not yet exist in the subnet.
141 amazon.aws.ec2_vpc_nat_gateway:
142 state: present
143 subnet_id: subnet-12345678
144 wait: true
145 region: ap-southeast-2
146 if_exist_do_not_create: true
147 register: new_nat_gateway
148
149 - name: Delete nat gateway using discovered nat gateways from facts module.
150 amazon.aws.ec2_vpc_nat_gateway:
151 state: absent
152 region: ap-southeast-2
153 wait: true
154 nat_gateway_id: "{{ item.NatGatewayId }}"
155 release_eip: true
156 register: delete_nat_gateway_result
157 loop: "{{ gateways_to_remove.result }}"
158
159 - name: Delete nat gateway and wait for deleted status.
160 amazon.aws.ec2_vpc_nat_gateway:
161 state: absent
162 nat_gateway_id: nat-12345678
163 wait: true
164 wait_timeout: 500
165 region: ap-southeast-2
166
167 - name: Delete nat gateway and release EIP.
168 amazon.aws.ec2_vpc_nat_gateway:
169 state: absent
170 nat_gateway_id: nat-12345678
171 release_eip: true
172 wait: true
173 wait_timeout: 300
174 region: ap-southeast-2
175
176 - name: Create new nat gateway using allocation-id and tags.
177 amazon.aws.ec2_vpc_nat_gateway:
178 state: present
179 subnet_id: subnet-12345678
180 allocation_id: eipalloc-12345678
181 region: ap-southeast-2
182 tags:
183 Tag1: tag1
184 Tag2: tag2
185 register: new_nat_gateway
186
187 - name: Update tags without purge
188 amazon.aws.ec2_vpc_nat_gateway:
189 subnet_id: subnet-12345678
190 allocation_id: eipalloc-12345678
191 region: ap-southeast-2
192 purge_tags: false
193 tags:
194 Tag3: tag3
195 wait: true
196 register: update_tags_nat_gateway
197 """
198
199 RETURN = r"""
200 connectivity_type:
201 description:
202 - Indicates whether the NAT gateway supports public or private connectivity.
203 returned: always
204 type: str
205 sample: public
206 create_time:
207 description: The ISO 8601 date time format in UTC.
208 returned: always
209 type: str
210 sample: "2016-03-05T05:19:20.282000+00:00'"
211 nat_gateway_id:
212 description: Id of the VPC NAT Gateway.
213 returned: always
214 type: str
215 sample: "nat-0d1e3a878585988f8"
216 subnet_id:
217 description: Id of the Subnet.
218 returned: always
219 type: str
220 sample: "subnet-12345"
221 state:
222 description: The current state of the NAT Gateway.
223 returned: always
224 type: str
225 sample: "available"
226 tags:
227 description: The tags associated the VPC NAT Gateway.
228 type: dict
229 returned: When tags are present.
230 sample:
231 tags:
232 "Ansible": "Test"
233 vpc_id:
234 description: Id of the VPC.
235 returned: always
236 type: str
237 sample: "vpc-12345"
238 nat_gateway_addresses:
239 description: List of dictionaries containing the public_ip, network_interface_id, private_ip, and allocation_id.
240 returned: always
241 type: complex
242 contains:
243 allocation_id:
244 description: The allocation ID of the Elastic IP address that's associated with the NAT gateway.
245 returned: always
246 type: str
247 sample: eipalloc-0853e66a40803da76
248 association_id:
249 description: The association ID of the Elastic IP address that is associated with the NAT gateway.
250 returned: always
251 type: str
252 sample: eipassoc-0d6365c7eeb7d4932
253 is_primary:
254 description: Defines if the IP address is the primary address.
255 returned: always
256 type: bool
257 sample: true
258 network_interface_id:
259 description: The ID of the network interface associated with the NAT gateway.
260 returned: always
261 type: str
262 sample: eni-0a37acdbe306c661c
263 private_ip:
264 description: The private IP address associated with the Elastic IP address.
265 returned: always
266 type: str
267 sample: 10.0.238.227
268 public_ip:
269 description: The Elastic IP address associated with the NAT gateway.
270 returned: always
271 type: str
272 sample: 34.204.123.52
273 status:
274 description: The address status.
275 returned: always
276 type: str
277 sample: succeeded
278 sample: [
279 {
280 "allocation_id": "eipalloc-08ec128d03629671d",
281 "association_id": "eipassoc-0d6365c7eeb7d4932",
282 "is_primary": true,
283 "network_interface_id": "eni-095104e630881bad6",
284 "private_ip": "10.1.0.250",
285 "public_ip": "34.202.90.172",
286 "status": "succeeded"
287 }
288 ]
289 """
290
291 import datetime
292 from typing import Any
293 from typing import Dict
294 from typing import List
295 from typing import Optional
296 from typing import Tuple
297
298 try:
299 import botocore
300 except ImportError:
301 pass # Handled by AnsibleAWSModule
302
303 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
304
305 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
306 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import allocate_address
307 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_nat_gateway
308 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_nat_gateway
309 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_addresses
310 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_ec2_tags
311 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_nat_gateways
312 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags
313 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import release_address
314 from ansible_collections.amazon.aws.plugins.module_utils.exceptions import AnsibleAWSError
315 from ansible_collections.amazon.aws.plugins.module_utils.exceptions import is_ansible_aws_error_code
316 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
317 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications
318 from ansible_collections.amazon.aws.plugins.module_utils.waiters import wait_for_resource_state
319
320
321 def wait_for_status(client, module: AnsibleAWSModule, waiter_name: str, nat_gateway_id: str) -> None:
322 wait_timeout = module.params.get("wait_timeout")
323 wait_delay = 5
324 attempts = 1 + int(wait_timeout / wait_delay)
325 wait_for_resource_state(
326 client, module, waiter_name, delay=wait_delay, max_attempts=attempts, NatGatewayIds=[nat_gateway_id]
327 )
328
329
330 def get_nat_gateways(
331 client, subnet_id: Optional[str] = None, nat_gateway_id: Optional[str] = None, states: Optional[List[str]] = None
332 ) -> List[Dict[str, Any]]:
333 """Retrieve a list of NAT Gateways
334 Args:
335 client (botocore.client.EC2): Boto3 client
336 module: AnsibleAWSModule class instance
337
338 Kwargs:
339 subnet_id (str): The subnet_id the nat resides in.
340 nat_gateway_id (str): The Amazon NAT id.
341 states (list): States available (pending, failed, available, deleting, and deleted)
342 default=None
343
344 Basic Usage:
345 >>> client = boto3.client('ec2')
346 >>> module = AnsibleAWSModule(...)
347 >>> subnet_id = 'subnet-12345678'
348 >>> get_nat_gateways(client, module, subnet_id)
349 [
350 {
351 "create_time": "2016-03-05T00:33:21.209000+00:00",
352 "delete_time": "2016-03-05T00:36:37.329000+00:00",
353 "nat_gateway_addresses": [
354 {
355 "public_ip": "55.55.55.55",
356 "network_interface_id": "eni-1234567",
357 "private_ip": "10.0.0.102",
358 "allocation_id": "eipalloc-1234567"
359 }
360 ],
361 "nat_gateway_id": "nat-123456789",
362 "state": "deleted",
363 "subnet_id": "subnet-123456789",
364 "tags": {},
365 "vpc_id": "vpc-12345678"
366 }
367 ]
368
369 Returns:
370 list
371 """
372
373 params: dict[str, Any] = {}
374 if not states:
375 states = ["available", "pending"]
376 if nat_gateway_id:
377 params["NatGatewayIds"] = [nat_gateway_id]
378 else:
379 params["Filter"] = [
380 {"Name": "subnet-id", "Values": [subnet_id]},
381 {"Name": "state", "Values": states},
382 ]
383
384 return [camel_dict_to_snake_dict(gw) for gw in describe_nat_gateways(client, **params) or []]
385
386
387 def gateway_in_subnet_exists(
388 client, subnet_id: str, allocation_id: Optional[str] = None
389 ) -> Tuple[List[Dict[str, Any]], bool]:
390 """Retrieve all NAT Gateways for a subnet.
391 Args:
392 client (botocore.client.EC2): Boto3 client
393 module: AnsibleAWSModule class instance
394 subnet_id (str): The subnet_id the nat resides in.
395
396 Kwargs:
397 allocation_id (str): The EIP Amazon identifier.
398 default = None
399
400 Basic Usage:
401 >>> client = boto3.client('ec2')
402 >>> module = AnsibleAWSModule(...)
403 >>> subnet_id = 'subnet-1234567'
404 >>> allocation_id = 'eipalloc-1234567'
405 >>> gateway_in_subnet_exists(client, module, subnet_id, allocation_id)
406 (
407 [
408 {
409 "create_time": "2016-03-05T00:33:21.209000+00:00",
410 "delete_time": "2016-03-05T00:36:37.329000+00:00",
411 "nat_gateway_addresses": [
412 {
413 "public_ip": "55.55.55.55",
414 "network_interface_id": "eni-1234567",
415 "private_ip": "10.0.0.102",
416 "allocation_id": "eipalloc-1234567"
417 }
418 ],
419 "nat_gateway_id": "nat-123456789",
420 "state": "deleted",
421 "subnet_id": "subnet-123456789",
422 "tags": {},
423 "vpc_id": "vpc-1234567"
424 }
425 ],
426 False
427 )
428
429 Returns:
430 Tuple (list, bool)
431 """
432
433 states = ["available", "pending"]
434 nat_gateways = get_nat_gateways(client, subnet_id=subnet_id, states=states)
435 if not allocation_id:
436 return nat_gateways, False
437
438 allocation_id_exists = False
439 gateways = []
440 for gw in nat_gateways:
441 for address in gw["nat_gateway_addresses"]:
442 if address.get("allocation_id") == allocation_id:
443 allocation_id_exists = True
444 gateways.append(gw)
445
446 return gateways, allocation_id_exists
447
448
449 def get_eip_allocation_id_by_address(client, eip_address: str) -> Tuple[Optional[str], str]:
450 """Release an EIP from your EIP Pool
451 Args:
452 client (botocore.client.EC2): Boto3 client
453 eip_address (str): The Elastic IP Address of the EIP.
454
455 Basic Usage:
456 >>> client = boto3.client('ec2')
457 >>> module = AnsibleAWSModule(...)
458 >>> eip_address = '52.87.29.36'
459 >>> get_eip_allocation_id_by_address(client, eip_address)
460 (
461 'eipalloc-36014da3', ''
462 )
463
464 Returns:
465 Tuple (str, str)
466 """
467
468 params = {
469 "PublicIps": [eip_address],
470 }
471 allocation_id = None
472 msg = ""
473
474 try:
475 allocations = describe_addresses(client, **params)
476 if not allocations:
477 msg = f"EIP {eip_address} does not exist"
478 allocation_id = None
479 return allocation_id, msg
480
481 if len(allocations) == 1:
482 allocation = allocations[0]
483 else:
484 allocation = None
485
486 if allocation:
487 if allocation.get("Domain") != "vpc":
488 msg = f"EIP {eip_address} is a non-VPC EIP, please allocate a VPC scoped EIP"
489 else:
490 allocation_id = allocation.get("AllocationId")
491
492 except is_ansible_aws_error_code("InvalidAddress.Malformed"):
493 raise AnsibleAWSError(message=f"EIP address {eip_address} is invalid.")
494
495 return allocation_id, msg
496
497
498 def allocate_eip_address(client, check_mode: bool) -> Tuple[bool, str, Optional[str]]:
499 """Release an EIP from your EIP Pool
500 Args:
501 client (botocore.client.EC2): Boto3 client
502 module: AnsibleAWSModule class instance
503
504 Basic Usage:
505 >>> client = boto3.client('ec2')
506 >>> module = AnsibleAWSModule(...)
507 >>> allocate_eip_address(client, module)
508 (
509 True, '', ''
510 )
511
512 Returns:
513 Tuple (bool, str, str)
514 """
515
516 new_eip = None
517 msg = ""
518 params = {
519 "Domain": "vpc",
520 }
521
522 if check_mode:
523 ip_allocated = True
524 new_eip = None
525 return ip_allocated, msg, new_eip
526
527 new_eip = allocate_address(client, **params)["AllocationId"]
528 ip_allocated = True
529 msg = f"eipalloc id {new_eip} created"
530
531 return ip_allocated, msg, new_eip
532
533
534 def release_eip_address(client, allocation_id: str, check_mode: bool) -> bool:
535 """Release an EIP from your EIP Pool
536 Args:
537 client (botocore.client.EC2): Boto3 client
538 module: AnsibleAWSModule class instance
539 allocation_id (str): The eip Amazon identifier.
540
541 Basic Usage:
542 >>> client = boto3.client('ec2')
543 >>> module = AnsibleAWSModule(...)
544 >>> allocation_id = "eipalloc-123456"
545 >>> release_address(client, module, allocation_id)
546 True
547
548 Returns:
549 bool
550 """
551
552 changed = False
553 if check_mode:
554 return True
555
556 addresses = describe_addresses(client, AllocationIds=[allocation_id])
557 if addresses:
558 # Release IP address
559 changed = release_address(client, allocation_id=allocation_id)
560
561 return changed
562
563
564 def create(client, module: AnsibleAWSModule, allocation_id: Optional[str]) -> Tuple[bool, str, Dict[str, Any]]:
565 """Create an Amazon NAT Gateway.
566 Args:
567 client (botocore.client.EC2): Boto3 client
568 module: AnsibleAWSModule class instance
569 allocation_id (str): The eip Amazon identifier
570
571 Basic Usage:
572 >>> client = boto3.client('ec2')
573 >>> module = AnsibleAWSModule(...)
574 >>> create(client, module, allocation_id)
575 [
576 true,
577 {
578 "create_time": "2016-03-05T00:33:21.209000+00:00",
579 "delete_time": "2016-03-05T00:36:37.329000+00:00",
580 "nat_gateway_addresses": [
581 {
582 "public_ip": "55.55.55.55",
583 "network_interface_id": "eni-1234567",
584 "private_ip": "10.0.0.102",
585 "allocation_id": "eipalloc-1234567"
586 }
587 ],
588 "nat_gateway_id": "nat-123456789",
589 "state": "deleted",
590 "subnet_id": "subnet-1234567",
591 "tags": {},
592 "vpc_id": "vpc-1234567"
593 },
594 ""
595 ]
596
597 Returns:
598 Tuple (bool, str, list)
599 """
600
601 connectivity_type = module.params.get("connectivity_type")
602 wait = module.params.get("wait")
603 client_token = module.params.get("client_token")
604 subnet_id = module.params.get("subnet_id")
605 tags = module.params.get("tags")
606
607 params = {"SubnetId": subnet_id, "ConnectivityType": connectivity_type}
608
609 if connectivity_type == "public":
610 params.update({"AllocationId": allocation_id})
611
612 request_time = datetime.datetime.now(datetime.timezone.utc)
613 changed = False
614 token_provided = False
615 result: dict[str, Any] = {}
616 msg = ""
617
618 if client_token:
619 token_provided = True
620 params["ClientToken"] = client_token
621
622 if tags:
623 params["TagSpecifications"] = boto3_tag_specifications(tags, ["natgateway"])
624
625 if module.check_mode:
626 changed = True
627 return changed, msg, result
628
629 try:
630 result = create_nat_gateway(client, **params)
631 result = camel_dict_to_snake_dict(result)
632 changed = True
633
634 create_time = result["create_time"].replace(tzinfo=None)
635
636 if token_provided and (request_time > create_time):
637 changed = False
638
639 elif wait and result.get("state") != "available":
640 wait_for_status(client, module, "nat_gateway_available", result["nat_gateway_id"])
641
642 # Get new result
643 result = camel_dict_to_snake_dict(
644 describe_nat_gateways(client, NatGatewayIds=[result["nat_gateway_id"]])[0]
645 )
646
647 except is_ansible_aws_error_code("IdempotentParameterMismatch") as e:
648 msg = "NAT Gateway does not support update and token has already been provided:" + e
649 changed = False
650 result = {}
651
652 if result:
653 result["tags"] = describe_ec2_tags(client, module, result["nat_gateway_id"], resource_type="natgateway")
654
655 return changed, msg, result
656
657
658 def pre_create(
659 client, module: AnsibleAWSModule, allocation_id: Optional[str], eip_address: Optional[str]
660 ) -> Tuple[bool, str, Dict[str, Any]]:
661 """Create an Amazon NAT Gateway.
662 Args:
663 client (botocore.client.EC2): Boto3 client
664 module: AnsibleAWSModule class instance
665
666 Basic Usage:
667 >>> client = boto3.client('ec2')
668 >>> module = AnsibleAWSModule(...)
669 >>> pre_create(client, module)
670 [
671 true,
672 "",
673 {
674 "create_time": "2016-03-05T00:33:21.209000+00:00",
675 "delete_time": "2016-03-05T00:36:37.329000+00:00",
676 "nat_gateway_addresses": [
677 {
678 "public_ip": "52.87.29.36",
679 "network_interface_id": "eni-5579742d",
680 "private_ip": "10.0.0.102",
681 "allocation_id": "eipalloc-36014da3"
682 }
683 ],
684 "nat_gateway_id": "nat-03835afb6e31df79b",
685 "state": "deleted",
686 "subnet_id": "subnet-w4t12897",
687 "tags": {},
688 "vpc_id": "vpc-w68571b5"
689 }
690 ]
691
692 Returns:
693 Tuple (bool, str, list)
694 """
695
696 changed = False
697 msg = ""
698 results = {}
699
700 connectivity_type = module.params.get("connectivity_type")
701 if_exist_do_not_create = module.params.get("if_exist_do_not_create")
702 purge_tags = module.params.get("purge_tags")
703 default_create = module.params.get("default_create")
704 subnet_id = module.params.get("subnet_id")
705 tags = module.params.get("tags")
706
707 if not allocation_id and not eip_address:
708 existing_gateways, allocation_id_exists = gateway_in_subnet_exists(client, subnet_id=subnet_id)
709 if len(existing_gateways) > 0 and if_exist_do_not_create:
710 results = existing_gateways[0]
711 changed |= ensure_ec2_tags(
712 client, module, results["nat_gateway_id"], resource_type="natgateway", tags=tags, purge_tags=purge_tags
713 )
714
715 results["tags"] = describe_ec2_tags(client, module, results["nat_gateway_id"], resource_type="natgateway")
716
717 if changed:
718 return changed, msg, results
719
720 changed = False
721 msg = f"NAT Gateway {existing_gateways[0]['nat_gateway_id']} already exists in subnet_id {subnet_id}"
722 return changed, msg, results
723 else:
724 if connectivity_type == "public":
725 changed, msg, allocation_id = allocate_eip_address(client, module.check_mode)
726
727 if not changed:
728 return changed, msg, {}
729
730 elif eip_address or allocation_id:
731 if eip_address and not allocation_id:
732 allocation_id, msg = get_eip_allocation_id_by_address(client, eip_address)
733 if not allocation_id and not default_create:
734 changed = False
735 module.fail_json(msg=msg)
736 elif not allocation_id and default_create:
737 eip_address = None
738 return pre_create(client, module, allocation_id, eip_address)
739
740 existing_gateways, allocation_id_exists = gateway_in_subnet_exists(
741 client, subnet_id=subnet_id, allocation_id=allocation_id
742 )
743
744 if len(existing_gateways) > 0 and (allocation_id_exists or if_exist_do_not_create):
745 results = existing_gateways[0]
746 changed |= ensure_ec2_tags(
747 client, module, results["nat_gateway_id"], resource_type="natgateway", tags=tags, purge_tags=purge_tags
748 )
749
750 results["tags"] = describe_ec2_tags(client, module, results["nat_gateway_id"], resource_type="natgateway")
751
752 if changed:
753 return changed, msg, results
754
755 changed = False
756 msg = f"NAT Gateway {existing_gateways[0]['nat_gateway_id']} already exists in subnet_id {subnet_id}"
757 return changed, msg, results
758
759 return create(client, module, allocation_id)
760
761
762 def remove(client, module: AnsibleAWSModule) -> Tuple[bool, str, Dict[str, Any]]:
763 """Delete an Amazon NAT Gateway.
764 Args:
765 client (botocore.client.EC2): Boto3 client
766 module: AnsibleAWSModule class instance
767 Kwargs:
768 wait (bool): Wait for the nat to be in the deleted state before returning.
769 release_eip (bool): Once the nat has been deleted, you can deallocate the eip from the vpc.
770 connectivity_type (str): private/public connection type
771
772 Basic Usage:
773 >>> client = boto3.client('ec2')
774 >>> module = AnsibleAWSModule(...)
775 >>> nat_gw_id = 'nat-03835afb6e31df79b'
776 >>> remove(client, module, nat_gw_id, wait=True, release_eip=True, connectivity_type='public')
777 [
778 true,
779 "",
780 {
781 "create_time": "2016-03-05T00:33:21.209000+00:00",
782 "delete_time": "2016-03-05T00:36:37.329000+00:00",
783 "nat_gateway_addresses": [
784 {
785 "public_ip": "52.87.29.36",
786 "network_interface_id": "eni-5579742d",
787 "private_ip": "10.0.0.102",
788 "allocation_id": "eipalloc-36014da3"
789 }
790 ],
791 "nat_gateway_id": "nat-03835afb6e31df79b",
792 "state": "deleted",
793 "subnet_id": "subnet-w4t12897",
794 "tags": {},
795 "vpc_id": "vpc-w68571b5"
796 }
797 ]
798
799 Returns:
800 Tuple (bool, str, list)
801 """
802
803 allocation_id = None
804 changed = False
805 results: dict[str, Any] = {}
806 states = ["pending", "available"]
807 msg = ""
808 nat_gateway_id = module.params.get("nat_gateway_id")
809 wait = module.params.get("wait")
810 release_eip = module.params.get("release_eip")
811 connectivity_type = module.params.get("connectivity_type")
812
813 if module.check_mode:
814 changed = True
815 return changed, msg, results
816
817 gw_list = get_nat_gateways(client, nat_gateway_id=nat_gateway_id, states=states)
818
819 if len(gw_list) == 1:
820 results = gw_list[0]
821 try:
822 changed = delete_nat_gateway(client, nat_gateway_id)
823 except AnsibleEC2Error as e:
824 module.fail_json_aws_error(e)
825 if connectivity_type == "public":
826 allocation_id = results["nat_gateway_addresses"][0]["allocation_id"]
827 msg = f"NAT gateway {nat_gateway_id} is in a deleting state. Delete was successful"
828
829 if wait and results.get("state") != "deleted":
830 wait_for_status(client, module, "nat_gateway_deleted", nat_gateway_id)
831
832 # Get new results
833 results = camel_dict_to_snake_dict(describe_nat_gateways(client, NatGatewayIds=[nat_gateway_id])[0])
834 results["tags"] = describe_ec2_tags(client, module, nat_gateway_id, resource_type="natgateway")
835
836 if release_eip and allocation_id:
837 changed |= release_eip_address(client, allocation_id, module.check_mode)
838
839 return changed, msg, results
840
841
842 def main() -> None:
843 argument_spec = dict(
844 subnet_id=dict(type="str"),
845 eip_address=dict(type="str"),
846 allocation_id=dict(type="str"),
847 connectivity_type=dict(type="str", default="public", choices=["private", "public"]),
848 if_exist_do_not_create=dict(type="bool", default=False),
849 state=dict(default="present", choices=["present", "absent"]),
850 wait=dict(type="bool", default=False),
851 wait_timeout=dict(type="int", default=320, required=False),
852 release_eip=dict(type="bool", default=False),
853 nat_gateway_id=dict(type="str"),
854 client_token=dict(type="str", no_log=False),
855 tags=dict(required=False, type="dict", aliases=["resource_tags"]),
856 purge_tags=dict(default=True, type="bool"),
857 default_create=dict(type="bool", default=False),
858 )
859
860 module = AnsibleAWSModule(
861 argument_spec=argument_spec,
862 supports_check_mode=True,
863 mutually_exclusive=[["allocation_id", "eip_address"]],
864 required_if=[["state", "absent", ["nat_gateway_id"]], ["state", "present", ["subnet_id"]]],
865 )
866
867 try:
868 client = module.client("ec2")
869 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
870 module.fail_json_aws(e, msg="Failed to connect to AWS.")
871
872 changed = False
873 msg = ""
874 state = module.params.get("state")
875
876 try:
877 if state == "present":
878 allocation_id = module.params.get("allocation_id")
879 eip_address = module.params.get("eip_address")
880 changed, msg, results = pre_create(client, module, allocation_id, eip_address)
881 else:
882 changed, msg, results = remove(client, module)
883 except AnsibleAWSError as e:
884 module.fail_json_aws_error(e)
885
886 module.exit_json(msg=msg, changed=changed, **results)
887
888
889 if __name__ == "__main__":
890 main()