Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_vpc_vgw.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 module: ec2_vpc_vgw
9 short_description: Create and delete AWS VPN Virtual Gateways
10 version_added: 1.0.0
11 version_added_collection: community.aws
12 description:
13 - Creates AWS VPN Virtual Gateways.
14 - Deletes AWS VPN Virtual Gateways.
15 - Attaches Virtual Gateways to VPCs.
16 - Detaches Virtual Gateways from VPCs.
17 options:
18 state:
19 description:
20 - V(present) to ensure resource is created.
21 - V(absent) to remove resource.
22 default: present
23 choices: [ "present", "absent"]
24 type: str
25 name:
26 description:
27 - Name of the VGW to be created or deleted.
28 type: str
29 type:
30 description:
31 - Type of the virtual gateway to be created.
32 choices: [ "ipsec.1" ]
33 default: "ipsec.1"
34 type: str
35 vpn_gateway_id:
36 description:
37 - VPN gateway ID of an existing virtual gateway.
38 type: str
39 vpc_id:
40 description:
41 - The ID of a VPC to attach or detach to the VGW.
42 type: str
43 asn:
44 description:
45 - The BGP ASN on the Amazon side.
46 type: int
47 wait_timeout:
48 description:
49 - Number of seconds to wait for status during VPC attach and detach.
50 default: 320
51 type: int
52 notes:
53 - Support for O(purge_tags) was added in release 4.0.0.
54 author:
55 - Nick Aslanidis (@naslanidis)
56 extends_documentation_fragment:
57 - amazon.aws.common.modules
58 - amazon.aws.region.modules
59 - amazon.aws.tags
60 - amazon.aws.boto3
61 """
62
63 EXAMPLES = r"""
64 - name: Create a new VGW attached to a specific VPC
65 amazon.aws.ec2_vpc_vgw:
66 state: present
67 region: ap-southeast-2
68 profile: personal
69 vpc_id: vpc-12345678
70 name: personal-testing
71 type: ipsec.1
72
73 - name: Create a new unattached VGW
74 amazon.aws.ec2_vpc_vgw:
75 state: present
76 region: ap-southeast-2
77 profile: personal
78 name: personal-testing
79 type: ipsec.1
80 tags:
81 environment: production
82 owner: ABC
83
84 - name: Remove a new VGW using the name
85 amazon.aws.ec2_vpc_vgw:
86 state: absent
87 region: ap-southeast-2
88 profile: personal
89 name: personal-testing
90 type: ipsec.1
91
92 - name: Remove a new VGW using the vpn_gateway_id
93 amazon.aws.ec2_vpc_vgw:
94 state: absent
95 region: ap-southeast-2
96 profile: personal
97 vpn_gateway_id: vgw-3a9aa123
98
99 - name: Detach vpn gateway from VPC
100 amazon.aws.ec2_vpc_vgw:
101 state: present
102 name: "{{ vgw_name }}"
103 register: vgw
104
105 - name: Delete vpn gateway
106 amazon.aws.ec2_vpc_vgw:
107 state: absent
108 vpn_gateway_id: '{{ vgw.vgw.id | default(vgw_id) }}'
109 ignore_errors: true
110 """
111
112 RETURN = r"""
113 vgw:
114 description: Information about the virtual private gateway.
115 returned: success
116 type: dict
117 contains:
118 id:
119 description: The ID of the virtual private gateway.
120 type: str
121 returned: success
122 sample: "vgw-0123456789abcdef0"
123 state:
124 description: The current state of the virtual private gateway.
125 type: str
126 returned: success
127 sample: "available"
128 tags:
129 description: A dictionary representing the tags attached to the virtual private gateway.
130 type: dict
131 returned: success
132 sample: {
133 "Name": "ansible-test-ec2-vpc-vgw",
134 "Env": "Dev_Test_001"
135 }
136 type:
137 description: The type of VPN connection the virtual private gateway supports.
138 type: str
139 returned: success
140 sample: "ipsec.1"
141 vpc_id:
142 description: The ID of the VPC.
143 type: str
144 returned: success
145 sample: "vpc-123456789abcdef01"
146 """
147
148 try:
149 import botocore
150 except ImportError:
151 pass # Handled by AnsibleAWSModule
152
153 from typing import Any
154 from typing import Dict
155 from typing import List
156 from typing import Optional
157 from typing import Tuple
158 from typing import Union
159
160 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
161 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import attach_vpn_gateway
162 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_vpn_gateway
163 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_vpn_gateway
164 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_vpcs
165 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_vpn_gateways
166 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import detach_vpn_gateway
167 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags
168 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
169 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
170 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
171 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications
172 from ansible_collections.amazon.aws.plugins.module_utils.waiters import get_waiter
173 from ansible_collections.amazon.aws.plugins.module_utils.waiters import wait_for_resource_state
174
175
176 # AWS uses VpnGatewayLimitExceeded for both 'Too many VGWs' and 'Too many concurrent changes'
177 # we need to look at the mesage to tell the difference.
178 class VGWRetry(AWSRetry):
179 @staticmethod
180 def status_code_from_exception(error: Any) -> Tuple[str, str]:
181 return (
182 error.response["Error"]["Code"],
183 error.response["Error"]["Message"],
184 )
185
186 @staticmethod
187 def found(response_code: Union[str, Tuple[str, ...]], catch_extra_error_codes: Optional[List[str]] = None) -> bool:
188 retry_on = ["The maximum number of mutating objects has been reached."]
189
190 if catch_extra_error_codes:
191 retry_on.extend(catch_extra_error_codes)
192 if not isinstance(response_code, tuple):
193 response_code = (response_code,)
194
195 for code in response_code:
196 if super(VGWRetry, VGWRetry).found(response_code, catch_extra_error_codes):
197 return True
198
199 return False
200
201
202 def format_vgw_info(vgw: Dict) -> Optional[Dict[str, Any]]:
203 # to handle check mode case where vgw passed to this function is {}
204 if not vgw:
205 return
206
207 vgw_info = {
208 "id": vgw["VpnGatewayId"],
209 "type": vgw["Type"],
210 "state": vgw["State"],
211 "vpc_id": None,
212 "tags": dict(),
213 }
214
215 if vgw["Tags"]:
216 vgw_info["tags"] = boto3_tag_list_to_ansible_dict(vgw["Tags"])
217
218 if len(vgw["VpcAttachments"]) != 0 and vgw["VpcAttachments"][0]["State"] == "attached":
219 vgw_info["vpc_id"] = vgw["VpcAttachments"][0]["VpcId"]
220
221 return vgw_info
222
223
224 def wait_for_status(client, module: AnsibleAWSModule, vpn_gateway_id: str, desired_status: str) -> Tuple[bool, Any]:
225 polling_increment_secs = 15
226 max_retries = module.params.get("wait_timeout") // polling_increment_secs
227 try:
228 wait_for_resource_state(client, module, "vpn_gateway_exists", VpnGatewayIds=[vpn_gateway_id])
229 if desired_status not in ("attached", "detached"):
230 module.fail_json(msg=f"Unsupported status: {desired_status}")
231 wait_for_resource_state(
232 client,
233 module,
234 f"vpn_gateway_{desired_status}",
235 VpnGatewayIds=[vpn_gateway_id],
236 delay=polling_increment_secs,
237 max_attempts=max_retries,
238 )
239
240 response = find_vgw(client, module, vpn_gateway_id)
241 status_achieved = response[0]["VpcAttachments"][0]["State"] == desired_status
242
243 except AnsibleEC2Error as e:
244 module.fail_json_aws(e)
245
246 return status_achieved, response
247
248
249 def attach_vgw_to_vpc(client, module: AnsibleAWSModule, vpn_gateway_id: str) -> bool:
250 if module.check_mode:
251 return True
252 response = None
253 vpc_id = module.params.get("vpc_id")
254 response = attach_vpn_gateway(client, vpc_id, vpn_gateway_id)
255 status_achieved, vgw = wait_for_status(client, module, vpn_gateway_id, "attached")
256
257 if not status_achieved:
258 module.fail_json(msg="Error waiting for VPC to attach to VGW - please check the AWS console")
259
260 return response
261
262
263 def detach_vgw(client, module: AnsibleAWSModule, vpn_gateway_id: str, vpc_id: Optional[str] = None) -> bool:
264 if module.check_mode:
265 return True
266 response = None
267 vpc_id = vpc_id or module.params.get("vpc_id")
268
269 response = detach_vpn_gateway(client, vpc_id, vpn_gateway_id)
270
271 status_achieved, vgw = wait_for_status(client, module, vpn_gateway_id, "detached")
272 if not status_achieved:
273 module.fail_json(msg="Error waiting for vpc to detach from vgw - please check the AWS console")
274
275 return response
276
277
278 def create_vgw(client, module: AnsibleAWSModule) -> Dict:
279 if module.check_mode:
280 return {}
281
282 params = {
283 "Type": module.params.get("type"),
284 "TagSpecifications": boto3_tag_specifications(
285 {**(module.params.get("tags") or {}), "Name": module.params.get("name")}, ["vpn-gateway"]
286 ),
287 }
288
289 if module.params.get("asn"):
290 params["AmazonSideAsn"] = module.params.get("asn")
291
292 try:
293 create_vgw_result = create_vpn_gateway(client, **params)
294 get_waiter(client, "vpn_gateway_exists").wait(VpnGatewayIds=[create_vgw_result["VpnGatewayId"]])
295 except botocore.exceptions.WaiterError as e:
296 module.fail_json_aws(
297 e, msg=f"Failed to wait for Vpn Gateway {create_vgw_result['VpnGatewayId']} to be available"
298 )
299
300 return create_vgw_result
301
302
303 def delete_vgw(client, module: AnsibleAWSModule, vpn_gateway_id: str) -> Optional[str]:
304 delete_vpn_gateway(client, vpn_gateway_id)
305
306 # return the deleted VpnGatewayId as this is not included in the above response
307 result = vpn_gateway_id
308 return result
309
310
311 def find_vpc(client, module: AnsibleAWSModule) -> Optional[Any]:
312 response = None
313 params = dict()
314 vpc_id = module.params.get("vpc_id")
315
316 if vpc_id:
317 params["VpcIds"] = [vpc_id]
318 response = describe_vpcs(client, **params)
319
320 return response
321
322
323 def find_vgw(client, module: AnsibleAWSModule, vpn_gateway_id: Optional[str] = None) -> List[Dict[str, Any]]:
324 params = dict()
325 if vpn_gateway_id:
326 params["VpnGatewayIds"] = [vpn_gateway_id]
327 else:
328 params["Filters"] = [
329 {"Name": "type", "Values": [module.params.get("type")]},
330 {"Name": "tag:Name", "Values": [module.params.get("name")]},
331 ]
332 if module.params.get("state") == "present":
333 params["Filters"].append({"Name": "state", "Values": ["pending", "available"]})
334
335 response = describe_vpn_gateways(client, **params)
336
337 return sorted(response, key=lambda k: k["VpnGatewayId"])
338
339
340 def ensure_vgw_present(client, module: AnsibleAWSModule) -> Tuple[bool, Dict[str, Any]]:
341 changed = False
342 vgw = {}
343
344 # Check if provided vgw already exists
345 existing_vgw = find_vgw(client, module, module.params.get("vpn_gateway_id"))
346
347 # if existing vgw, handle changes as required
348 if existing_vgw:
349 changed |= handle_existing_vgw(client, module, existing_vgw[0])
350 vgw = find_vgw(client, module, existing_vgw[0]["VpnGatewayId"])[
351 0
352 ] # [0] as find_vgw returns list[dict] i.e. [{vgw_info}] as it is possible to have multiple vgw with same names
353 # if not existing vgw, create new and return
354 else:
355 changed = True
356 if not module.check_mode:
357 vgw = create_vgw(client, module)
358 # if vpc_id provided, attach vgw to vpc
359 if module.params.get("vpc_id"):
360 attach_vgw_to_vpc(client, module, vgw["VpnGatewayId"])
361 vgw = find_vgw(client, module, vgw["VpnGatewayId"])[0]
362
363 return changed, format_vgw_info(vgw)
364
365
366 def handle_existing_vgw(client, module: AnsibleAWSModule, existing_vgw: dict) -> bool:
367 changed = False
368 vpn_gateway_id = existing_vgw["VpnGatewayId"]
369 provided_vpc_id = module.params.get("vpc_id")
370
371 # Update tags
372 desired_tags = module.params.get("tags")
373 purge_tags = module.params.get("purge_tags")
374 if desired_tags is None:
375 desired_tags = dict()
376 purge_tags = False
377 tags = dict(Name=module.params.get("name"))
378 tags.update(desired_tags)
379 # check_mode is handled by esure_ec2_tags()
380 changed |= ensure_ec2_tags(
381 client, module, vpn_gateway_id, resource_type="vpn-gateway", tags=tags, purge_tags=purge_tags
382 )
383
384 # Manage VPC attachments
385 current_vpc_attachments = existing_vgw["VpcAttachments"]
386 if provided_vpc_id:
387 # if vgw is attached to a vpc
388 if current_vpc_attachments and current_vpc_attachments[0]["State"] == "attached":
389 # if provided vpc is differenct than current vpc, then detach current vpc, attach new vpc
390 if provided_vpc_id != current_vpc_attachments[0]["VpcId"]:
391 if module.check_mode:
392 return True
393 detach_vgw(client, module, vpn_gateway_id, current_vpc_attachments[0]["VpcId"])
394 get_waiter(client, "vpn_gateway_detached").wait(VpnGatewayIds=[vpn_gateway_id])
395 attach_vgw_to_vpc(client, module, vpn_gateway_id)
396 changed = True
397 # if vgw is not currently attached to a vpc, attach it to provided vpc
398 else:
399 if module.check_mode:
400 return True
401 attach_vgw_to_vpc(client, module, vpn_gateway_id)
402 changed = True
403 # if vpc_id not provided, then detach vgw from vpc
404 else:
405 if current_vpc_attachments and current_vpc_attachments[0]["State"] == "attached":
406 if module.check_mode:
407 return True
408 detach_vgw(client, module, vpn_gateway_id, current_vpc_attachments[0]["VpcId"])
409 changed = True
410
411 return changed
412
413
414 def ensure_vgw_absent(client, module: AnsibleAWSModule) -> Tuple[bool, Optional[str]]:
415 # If an existing vgw name and type matches our args, then a match is considered to have been
416 # found and we will take steps to delete it.
417
418 changed = False
419 params = dict()
420 result = dict()
421 deleted_vgw = None
422 params["Name"] = module.params.get("name")
423 params["VpcId"] = module.params.get("vpc_id")
424 params["Type"] = module.params.get("type")
425 params["Tags"] = module.params.get("tags")
426 params["VpnGatewayIds"] = module.params.get("vpn_gateway_id")
427 vpn_gateway_id = module.params.get("vpn_gateway_id")
428
429 # check if a gateway matching our module args already exists
430 if params["VpnGatewayIds"]:
431 existing_vgw_with_id = find_vgw(client, module, module.params.get("vpn_gateway_id"))
432 if existing_vgw_with_id != [] and existing_vgw_with_id[0]["State"] != "deleted":
433 if module.check_mode:
434 return True, existing_vgw_with_id[0]["VpnGatewayId"]
435 existing_vgw = existing_vgw_with_id
436 if existing_vgw[0]["VpcAttachments"] != [] and existing_vgw[0]["VpcAttachments"][0]["State"] == "attached":
437 if params["VpcId"]:
438 if params["VpcId"] != existing_vgw[0]["VpcAttachments"][0]["VpcId"]:
439 module.fail_json(
440 msg="The vpc-id provided does not match the vpc-id currently attached - please check the AWS console"
441 )
442
443 else:
444 # detach the vpc from the vgw
445 detach_vgw(client, module, params["VpnGatewayIds"], params["VpcId"])
446 deleted_vgw = delete_vgw(client, module, params["VpnGatewayIds"])
447 changed = True
448
449 else:
450 # attempt to detach any attached vpcs
451 for vpc in existing_vgw[0]["VpcAttachments"]:
452 detach_vgw(client, module, vpn_gateway_id, vpc["VpcId"])
453 deleted_vgw = delete_vgw(client, module, params["VpnGatewayIds"])
454 changed = True
455
456 else:
457 # no vpc's are attached so attempt to delete the vgw
458 deleted_vgw = delete_vgw(client, module, params["VpnGatewayIds"])
459 changed = True
460
461 else:
462 changed = False
463 deleted_vgw = "Nothing to do"
464
465 else:
466 # Check that a name and type argument has been supplied if no vgw-id
467 if not module.params.get("name") or not module.params.get("type"):
468 module.fail_json(msg="A name and type is required when no vgw-id and a status of 'absent' is supplied")
469
470 existing_vgw = find_vgw(client, module)
471 if existing_vgw != [] and existing_vgw[0]["State"] != "deleted":
472 vpn_gateway_id = existing_vgw[0]["VpnGatewayId"]
473 if existing_vgw[0]["VpcAttachments"] != [] and existing_vgw[0]["VpcAttachments"][0]["State"] == "attached":
474 if params["VpcId"]:
475 if params["VpcId"] != existing_vgw[0]["VpcAttachments"][0]["VpcId"]:
476 module.fail_json(
477 msg="The vpc-id provided does not match the vpc-id currently attached - please check the AWS console"
478 )
479
480 else:
481 if module.check_mode:
482 return True, None
483 # detach the vpc from the vgw
484 detach_vgw(client, module, vpn_gateway_id, params["VpcId"])
485
486 # now that the vpc has been detached, delete the vgw
487 deleted_vgw = delete_vgw(client, module, vpn_gateway_id)
488 changed = True
489
490 else:
491 if module.check_mode:
492 return True, vpn_gateway_id
493 # attempt to detach any attached vpcs
494 vpc_to_detach = existing_vgw[0]["VpcAttachments"][0]["VpcId"]
495 detach_vgw(client, module, vpn_gateway_id, vpc_to_detach)
496 changed = True
497
498 # now that the vpc has been detached, delete the vgw
499 deleted_vgw = delete_vgw(client, module, vpn_gateway_id)
500
501 else:
502 if module.check_mode:
503 return True, vpn_gateway_id
504 # no vpc's are attached so attempt to delete the vgw
505 deleted_vgw = delete_vgw(client, module, vpn_gateway_id)
506 changed = True
507
508 else:
509 changed = False
510 deleted_vgw = None
511
512 result = deleted_vgw
513 return changed, result
514
515
516 def main():
517 argument_spec = dict(
518 state=dict(default="present", choices=["present", "absent"]),
519 name=dict(),
520 vpn_gateway_id=dict(),
521 vpc_id=dict(),
522 asn=dict(type="int"),
523 wait_timeout=dict(type="int", default=320),
524 type=dict(default="ipsec.1", choices=["ipsec.1"]),
525 tags=dict(default=None, required=False, type="dict", aliases=["resource_tags"]),
526 purge_tags=dict(default=True, type="bool"),
527 )
528 module = AnsibleAWSModule(
529 argument_spec=argument_spec,
530 required_if=[["state", "present", ["name"]]],
531 supports_check_mode=True,
532 )
533 state = module.params.get("state").lower()
534
535 client = module.client("ec2")
536
537 if state == "present":
538 (changed, results) = ensure_vgw_present(client, module)
539 else:
540 (changed, results) = ensure_vgw_absent(client, module)
541 module.exit_json(changed=changed, vgw=results)
542
543
544 if __name__ == "__main__":
545 main()