Debian Codegraph @

ansible_collections/community/aws/plugins/modules/directconnect_virtual_interface.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2017 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: directconnect_virtual_interface
10 version_added: 1.0.0
11 short_description: Manage Direct Connect virtual interfaces
12 description:
13 - Create, delete, or modify a Direct Connect public or private virtual interface.
14 - Prior to release 5.0.0 this module was called C(community.aws.aws_direct_connect_virtual_interface).
15 The usage did not change.
16 author:
17 - "Sloane Hertel (@s-hertel)"
18 options:
19 state:
20 description:
21 - The desired state of the Direct Connect virtual interface.
22 choices: [present, absent]
23 type: str
24 required: true
25 id_to_associate:
26 description:
27 - The ID of the link aggregation group or connection to associate with the virtual interface.
28 aliases: [link_aggregation_group_id, connection_id]
29 type: str
30 required: true
31 public:
32 description:
33 - The type of virtual interface.
34 type: bool
35 name:
36 description:
37 - The name of the virtual interface.
38 type: str
39 vlan:
40 description:
41 - The VLAN ID.
42 default: 100
43 type: int
44 bgp_asn:
45 description:
46 - The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration.
47 default: 65000
48 type: int
49 authentication_key:
50 description:
51 - The authentication key for BGP configuration.
52 type: str
53 amazon_address:
54 description:
55 - The amazon address CIDR with which to create the virtual interface.
56 type: str
57 customer_address:
58 description:
59 - The customer address CIDR with which to create the virtual interface.
60 type: str
61 address_type:
62 description:
63 - The type of IP address for the BGP peer.
64 type: str
65 cidr:
66 description:
67 - A list of route filter prefix CIDRs with which to create the public virtual interface.
68 type: list
69 elements: str
70 virtual_gateway_id:
71 description:
72 - The virtual gateway ID required for creating a private virtual interface.
73 - To create a private virtual interface I(virtual_gateway_id) or I(direct_connect_gateway_id) is required.
74 These options are mutually exclusive.
75 type: str
76 direct_connect_gateway_id:
77 description:
78 - The direct connect gateway ID for creating a private virtual interface.
79 - To create a private virtual interface I(virtual_gateway_id) or I(direct_connect_gateway_id) is required.
80 These options are mutually exclusive.
81 type: str
82 virtual_interface_id:
83 description:
84 - The virtual interface ID.
85 type: str
86 extends_documentation_fragment:
87 - amazon.aws.common.modules
88 - amazon.aws.region.modules
89 - amazon.aws.boto3
90 """
91
92 RETURN = r"""
93 address_family:
94 description: The address family for the BGP peer.
95 returned: always
96 type: str
97 sample: ipv4
98 amazon_address:
99 description: IP address assigned to the Amazon interface.
100 returned: always
101 type: str
102 sample: 169.254.255.1/30
103 asn:
104 description: The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration.
105 returned: always
106 type: int
107 sample: 65000
108 auth_key:
109 description: The authentication key for BGP configuration.
110 returned: always
111 type: str
112 sample: 0xZ59Y1JZ2oDOSh6YriIlyRE
113 bgp_peers:
114 description: A list of the BGP peers configured on this virtual interface.
115 returned: always
116 type: complex
117 contains:
118 address_family:
119 description: The address family for the BGP peer.
120 returned: always
121 type: str
122 sample: ipv4
123 amazon_address:
124 description: IP address assigned to the Amazon interface.
125 returned: always
126 type: str
127 sample: 169.254.255.1/30
128 asn:
129 description: The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration.
130 returned: always
131 type: int
132 sample: 65000
133 auth_key:
134 description: The authentication key for BGP configuration.
135 returned: always
136 type: str
137 sample: 0xZ59Y1JZ2oDOSh6YriIlyRE
138 bgp_peer_state:
139 description: The state of the BGP peer (verifying, pending, available)
140 returned: always
141 type: str
142 sample: available
143 bgp_status:
144 description: The up/down state of the BGP peer.
145 returned: always
146 type: str
147 sample: up
148 customer_address:
149 description: IP address assigned to the customer interface.
150 returned: always
151 type: str
152 sample: 169.254.255.2/30
153 changed:
154 description: Indicated if the virtual interface has been created/modified/deleted
155 returned: always
156 type: bool
157 sample: false
158 connection_id:
159 description:
160 - The ID of the connection. This field is also used as the ID type for operations that
161 use multiple connection types (LAG, interconnect, and/or connection).
162 returned: always
163 type: str
164 sample: dxcon-fgb175av
165 customer_address:
166 description: IP address assigned to the customer interface.
167 returned: always
168 type: str
169 sample: 169.254.255.2/30
170 customer_router_config:
171 description: Information for generating the customer router configuration.
172 returned: always
173 type: str
174 location:
175 description: Where the connection is located.
176 returned: always
177 type: str
178 sample: EqDC2
179 owner_account:
180 description: The AWS account that will own the new virtual interface.
181 returned: always
182 type: str
183 sample: '123456789012'
184 route_filter_prefixes:
185 description: A list of routes to be advertised to the AWS network in this region (public virtual interface).
186 returned: always
187 type: complex
188 contains:
189 cidr:
190 description: A routes to be advertised to the AWS network in this region.
191 returned: always
192 type: str
193 sample: 54.227.92.216/30
194 virtual_gateway_id:
195 description: The ID of the virtual private gateway to a VPC. This only applies to private virtual interfaces.
196 returned: when I(public=False)
197 type: str
198 sample: vgw-f3ce259a
199 direct_connect_gateway_id:
200 description: The ID of the Direct Connect gateway. This only applies to private virtual interfaces.
201 returned: when I(public=False)
202 type: str
203 sample: f7593767-eded-44e8-926d-a2234175835d
204 virtual_interface_id:
205 description: The ID of the virtual interface.
206 returned: always
207 type: str
208 sample: dxvif-fh0w7cex
209 virtual_interface_name:
210 description: The name of the virtual interface assigned by the customer.
211 returned: always
212 type: str
213 sample: test_virtual_interface
214 virtual_interface_state:
215 description: State of the virtual interface (confirming, verifying, pending, available, down, rejected).
216 returned: always
217 type: str
218 sample: available
219 virtual_interface_type:
220 description: The type of virtual interface (private, public).
221 returned: always
222 type: str
223 sample: private
224 vlan:
225 description: The VLAN ID.
226 returned: always
227 type: int
228 sample: 100
229 """
230
231 EXAMPLES = r"""
232 ---
233 - name: create an association between a LAG and connection
234 community.aws.directconnect_virtual_interface:
235 state: present
236 name: "{{ name }}"
237 link_aggregation_group_id: LAG-XXXXXXXX
238 connection_id: dxcon-XXXXXXXX
239
240 - name: remove an association between a connection and virtual interface
241 community.aws.directconnect_virtual_interface:
242 state: absent
243 connection_id: dxcon-XXXXXXXX
244 virtual_interface_id: dxv-XXXXXXXX
245 """
246
247 import traceback
248
249 try:
250 from botocore.exceptions import BotoCoreError
251 from botocore.exceptions import ClientError
252 except ImportError:
253 # handled by AnsibleAWSModule
254 pass
255
256 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
257
258 from ansible_collections.amazon.aws.plugins.module_utils.direct_connect import DirectConnectError
259 from ansible_collections.amazon.aws.plugins.module_utils.direct_connect import delete_virtual_interface
260 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
261
262 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
263
264
265 def try_except_ClientError(failure_msg):
266 """
267 Wrapper for boto3 calls that uses AWSRetry and handles exceptions
268 """
269
270 def wrapper(f):
271 def run_func(*args, **kwargs):
272 try:
273 result = AWSRetry.jittered_backoff(
274 retries=8, delay=5, catch_extra_error_codes=["DirectConnectClientException"]
275 )(f)(*args, **kwargs)
276 except (ClientError, BotoCoreError) as e:
277 raise DirectConnectError(failure_msg, traceback.format_exc(), e)
278 return result
279
280 return run_func
281
282 return wrapper
283
284
285 def find_unique_vi(client, connection_id, virtual_interface_id, name):
286 """
287 Determines if the virtual interface exists. Returns the virtual interface ID if an exact match is found.
288 If multiple matches are found False is returned. If no matches are found None is returned.
289 """
290
291 # Get the virtual interfaces, filtering by the ID if provided.
292 vi_params = {}
293 if virtual_interface_id:
294 vi_params = {"virtualInterfaceId": virtual_interface_id}
295
296 virtual_interfaces = try_except_ClientError(failure_msg="Failed to describe virtual interface")(
297 client.describe_virtual_interfaces
298 )(**vi_params).get("virtualInterfaces")
299
300 # Remove deleting/deleted matches from the results.
301 virtual_interfaces = [vi for vi in virtual_interfaces if vi["virtualInterfaceState"] not in ("deleting", "deleted")]
302
303 matching_virtual_interfaces = filter_virtual_interfaces(virtual_interfaces, name, connection_id)
304 return exact_match(matching_virtual_interfaces)
305
306
307 def exact_match(virtual_interfaces):
308 """
309 Returns the virtual interface ID if one was found,
310 None if the virtual interface ID needs to be created,
311 False if an exact match was not found
312 """
313
314 if not virtual_interfaces:
315 return None
316 if len(virtual_interfaces) == 1:
317 return virtual_interfaces[0]["virtualInterfaceId"]
318 else:
319 return False
320
321
322 def filter_virtual_interfaces(virtual_interfaces, name, connection_id):
323 """
324 Filters the available virtual interfaces to try to find a unique match
325 """
326 # Filter by name if provided.
327 if name:
328 matching_by_name = find_virtual_interface_by_name(virtual_interfaces, name)
329 if len(matching_by_name) == 1:
330 return matching_by_name
331 else:
332 matching_by_name = virtual_interfaces
333
334 # If there isn't a unique match filter by connection ID as last resort (because connection_id may be a connection yet to be associated)
335 if connection_id and len(matching_by_name) > 1:
336 matching_by_connection_id = find_virtual_interface_by_connection_id(matching_by_name, connection_id)
337 if len(matching_by_connection_id) == 1:
338 return matching_by_connection_id
339 else:
340 matching_by_connection_id = matching_by_name
341
342 return matching_by_connection_id
343
344
345 def find_virtual_interface_by_connection_id(virtual_interfaces, connection_id):
346 """
347 Return virtual interfaces that have the connection_id associated
348 """
349 return [vi for vi in virtual_interfaces if vi["connectionId"] == connection_id]
350
351
352 def find_virtual_interface_by_name(virtual_interfaces, name):
353 """
354 Return virtual interfaces that match the provided name
355 """
356 return [vi for vi in virtual_interfaces if vi["virtualInterfaceName"] == name]
357
358
359 def vi_state(client, virtual_interface_id):
360 """
361 Returns the state of the virtual interface.
362 """
363 err_msg = f"Failed to describe virtual interface: {virtual_interface_id}"
364 vi = try_except_ClientError(failure_msg=err_msg)(client.describe_virtual_interfaces)(
365 virtualInterfaceId=virtual_interface_id
366 )
367 return vi["virtualInterfaces"][0]
368
369
370 def assemble_params_for_creating_vi(params):
371 """
372 Returns kwargs to use in the call to create the virtual interface
373
374 Params for public virtual interfaces:
375 virtualInterfaceName, vlan, asn, authKey, amazonAddress, customerAddress, addressFamily, cidr
376 Params for private virtual interfaces:
377 virtualInterfaceName, vlan, asn, authKey, amazonAddress, customerAddress, addressFamily, virtualGatewayId
378 """
379
380 public = params["public"]
381 name = params["name"]
382 vlan = params["vlan"]
383 bgp_asn = params["bgp_asn"]
384 auth_key = params["authentication_key"]
385 amazon_addr = params["amazon_address"]
386 customer_addr = params["customer_address"]
387 family_addr = params["address_type"]
388 cidr = params["cidr"]
389 virtual_gateway_id = params["virtual_gateway_id"]
390 direct_connect_gateway_id = params["direct_connect_gateway_id"]
391
392 parameters = dict(virtualInterfaceName=name, vlan=vlan, asn=bgp_asn)
393 opt_params = dict(
394 authKey=auth_key, amazonAddress=amazon_addr, customerAddress=customer_addr, addressFamily=family_addr
395 )
396
397 for name, value in opt_params.items():
398 if value:
399 parameters[name] = value
400
401 # virtual interface type specific parameters
402 if public and cidr:
403 parameters["routeFilterPrefixes"] = [{"cidr": c} for c in cidr]
404 if not public:
405 if virtual_gateway_id:
406 parameters["virtualGatewayId"] = virtual_gateway_id
407 elif direct_connect_gateway_id:
408 parameters["directConnectGatewayId"] = direct_connect_gateway_id
409
410 return parameters
411
412
413 def create_vi(client, public, associated_id, creation_params):
414 """
415 :param public: a boolean
416 :param associated_id: a link aggregation group ID or connection ID to associate
417 with the virtual interface.
418 :param creation_params: a dict of parameters to use in the AWS SDK call
419 :return The ID of the created virtual interface
420 """
421 err_msg = "Failed to create virtual interface"
422 if public:
423 vi = try_except_ClientError(failure_msg=err_msg)(client.create_public_virtual_interface)(
424 connectionId=associated_id, newPublicVirtualInterface=creation_params
425 )
426 else:
427 vi = try_except_ClientError(failure_msg=err_msg)(client.create_private_virtual_interface)(
428 connectionId=associated_id, newPrivateVirtualInterface=creation_params
429 )
430 return vi["virtualInterfaceId"]
431
432
433 def modify_vi(client, virtual_interface_id, connection_id):
434 """
435 Associate a new connection ID
436 """
437 err_msg = f"Unable to associate {connection_id} with virtual interface {virtual_interface_id}"
438 try_except_ClientError(failure_msg=err_msg)(client.associate_virtual_interface)(
439 virtualInterfaceId=virtual_interface_id, connectionId=connection_id
440 )
441
442
443 def needs_modification(client, virtual_interface_id, connection_id):
444 """
445 Determine if the associated connection ID needs to be updated
446 """
447 return vi_state(client, virtual_interface_id).get("connectionId") != connection_id
448
449
450 def ensure_state(connection, module):
451 changed = False
452
453 state = module.params["state"]
454 connection_id = module.params["id_to_associate"]
455 public = module.params["public"]
456 name = module.params["name"]
457
458 virtual_interface_id = find_unique_vi(connection, connection_id, module.params.get("virtual_interface_id"), name)
459
460 if virtual_interface_id is False:
461 module.fail_json(
462 msg=(
463 "Multiple virtual interfaces were found. Use the virtual_interface_id, name, "
464 "and connection_id options if applicable to find a unique match."
465 )
466 )
467
468 if state == "present":
469 if not virtual_interface_id and module.params["virtual_interface_id"]:
470 module.fail_json(msg=f"The virtual interface {module.params['virtual_interface_id']} does not exist.")
471
472 elif not virtual_interface_id:
473 assembled_params = assemble_params_for_creating_vi(module.params)
474 virtual_interface_id = create_vi(connection, public, connection_id, assembled_params)
475 changed = True
476
477 if needs_modification(connection, virtual_interface_id, connection_id):
478 modify_vi(connection, virtual_interface_id, connection_id)
479 changed = True
480
481 latest_state = vi_state(connection, virtual_interface_id)
482
483 else:
484 if virtual_interface_id:
485 delete_virtual_interface(connection, virtual_interface_id)
486 changed = True
487
488 latest_state = {}
489
490 return changed, latest_state
491
492
493 def main():
494 argument_spec = dict(
495 state=dict(required=True, choices=["present", "absent"]),
496 id_to_associate=dict(required=True, aliases=["link_aggregation_group_id", "connection_id"]),
497 public=dict(type="bool"),
498 name=dict(),
499 vlan=dict(type="int", default=100),
500 bgp_asn=dict(type="int", default=65000),
501 authentication_key=dict(no_log=True),
502 amazon_address=dict(),
503 customer_address=dict(),
504 address_type=dict(),
505 cidr=dict(type="list", elements="str"),
506 virtual_gateway_id=dict(),
507 direct_connect_gateway_id=dict(),
508 virtual_interface_id=dict(),
509 )
510
511 module = AnsibleAWSModule(
512 argument_spec=argument_spec,
513 required_one_of=[["virtual_interface_id", "name"]],
514 required_if=[
515 ["state", "present", ["public"]],
516 ["public", True, ["amazon_address"]],
517 ["public", True, ["customer_address"]],
518 ["public", True, ["cidr"]],
519 ],
520 mutually_exclusive=[["virtual_gateway_id", "direct_connect_gateway_id"]],
521 )
522
523 connection = module.client("directconnect")
524
525 try:
526 changed, latest_state = ensure_state(connection, module)
527 except DirectConnectError as e:
528 if e.exception:
529 module.fail_json_aws(exception=e.exception, msg=e.msg)
530 else:
531 module.fail_json(msg=e.msg)
532
533 module.exit_json(changed=changed, **camel_dict_to_snake_dict(latest_state))
534
535
536 if __name__ == "__main__":
537 main()