Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_trunk.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, F5 Networks Inc.
5 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_trunk
13 short_description: Manage trunks on a BIG-IP
14 description:
15 - Manages trunks on a BIG-IP.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the trunk.
21 type: str
22 required: True
23 interfaces:
24 description:
25 - The interfaces that are part of the trunk.
26 - To clear the list of interfaces, specify an empty list.
27 type: list
28 elements: str
29 description:
30 description:
31 - Description of the trunk.
32 type: str
33 link_selection_policy:
34 description:
35 - Once the trunk is configured, specifies the policy the trunk uses to determine
36 which member link (interface) can handle new traffic.
37 - When creating a new trunk, if this value is not specified, the default is C(auto).
38 - When C(auto), specifies the system automatically determines which interfaces
39 can handle new traffic. For the C(auto) option, the member links must all be the
40 same media type and speed.
41 - When C(maximum-bandwidth), specifies the system determines which interfaces
42 can handle new traffic based on the members' maximum bandwidth.
43 type: str
44 choices:
45 - auto
46 - maximum-bandwidth
47 frame_distribution_hash:
48 description:
49 - Specifies the basis for the hash the system uses as the frame distribution
50 algorithm. The system uses the resulting hash to determine which interface to
51 use for forwarding traffic.
52 - When creating a new trunk, if this parameter is not specified, the default is
53 C(source-destination-ip).
54 - When C(source-destination-mac), specifies the system bases the hash on the
55 combined MAC addresses of the source and the destination.
56 - When C(destination-mac), specifies the system bases the hash on the MAC
57 address of the destination.
58 - When C(source-destination-ip), specifies the system bases the hash on the
59 combined IP addresses of the source and the destination.
60 type: str
61 choices:
62 - destination-mac
63 - source-destination-ip
64 - source-destination-mac
65 lacp_enabled:
66 description:
67 - When C(true), specifies the system supports the link aggregation control
68 protocol (LACP), which monitors the trunk by exchanging control packets over
69 the member links to determine the health of the links.
70 - If LACP detects a failure in a member link, it removes the link from the link
71 aggregation.
72 - When creating a new trunk, if this parameter is not specified, LACP is C(false).
73 - LACP is disabled by default for backward compatibility. If this does not apply
74 to your network, we recommend that you enable LACP.
75 type: bool
76 lacp_mode:
77 description:
78 - Specifies the operation mode for link aggregation control protocol (LACP),
79 if LACP is enabled for the trunk.
80 - When creating a new trunk, if this parameter is not specified, the default
81 is C(active).
82 - When C(active), specifies the system periodically sends control packets
83 regardless of whether the partner system has issued a request.
84 - When C(passive), specifies the system sends control packets only when
85 the partner system has issued a request.
86 type: str
87 choices:
88 - active
89 - passive
90 lacp_timeout:
91 description:
92 - Specifies the rate at which the system sends the LACP control packets.
93 - When creating a new trunk, if this parameter is not specified, the default is
94 C(long).
95 - When C(long), specifies the system sends an LACP control packet every 30 seconds.
96 - When C(short), specifies the system sends an LACP control packet every second.
97 type: str
98 choices:
99 - long
100 - short
101 qinq_ethertype:
102 description:
103 - Specifies the ether-type value used for the packets handled on this trunk when
104 it is a member in a QinQ VLAN.
105 - The ether-type can be set to any string containing a valid hexadecimal 16 bits
106 number, or any of the well known ether-types; C(0x8100), C(0x9100), C(0x88a8).
107 - This parameter is not supported on Virtual Editions.
108 - You should always wrap this value in quotes to prevent Ansible from interpreting
109 the value as a literal hexadecimal number and converting it to an integer.
110 type: raw
111 state:
112 description:
113 - When C(present), ensures the resource exists.
114 - When C(absent), ensures the resource is removed.
115 type: str
116 choices:
117 - present
118 - absent
119 default: present
120 extends_documentation_fragment: f5networks.f5_modules.f5
121 author:
122 - Tim Rupp (@caphrim007)
123 - Wojciech Wypior (@wojtek0806)
124 '''
125
126 EXAMPLES = r'''
127 - name: Create a trunk on hardware
128 bigip_trunk:
129 name: trunk1
130 interfaces:
131 - 1.1
132 - 1.2
133 link_selection_policy: maximum-bandwidth
134 frame_distribution_hash: destination-mac
135 lacp_enabled: true
136 lacp_mode: passive
137 lacp_timeout: short
138 provider:
139 password: secret
140 server: lb.mydomain.com
141 user: admin
142 delegate_to: localhost
143 '''
144
145 RETURN = r'''
146 lacp_mode:
147 description: Operation mode for LACP if the lacp option is enabled for the trunk.
148 returned: changed
149 type: str
150 sample: active
151 lacp_timeout:
152 description: Rate at which the system sends the LACP control packets.
153 returned: changed
154 type: str
155 sample: long
156 link_selection_policy:
157 description:
158 - LACP policy the trunk uses to determine which member link (interface)
159 can handle new traffic.
160 returned: changed
161 type: str
162 sample: auto
163 frame_distribution_hash:
164 description: Hash the system uses as the frame distribution algorithm.
165 returned: changed
166 type: str
167 sample: src-dst-ipport
168 lacp_enabled:
169 description: Whether the system supports the link aggregation control protocol (LACP) or not.
170 returned: changed
171 type: bool
172 sample: true
173 interfaces:
174 description: Interfaces that are part of the trunk.
175 returned: changed
176 type: list
177 sample: ['int1', 'int2']
178 description:
179 description: Description of the trunk.
180 returned: changed
181 type: str
182 sample: My trunk
183 qinq_ethertype:
184 description: Ether-type value used for the packets handled on this trunk when it is a member in a QinQ VLAN.
185 returned: changed
186 type: str
187 sample: 0x9100
188 '''
189 from datetime import datetime
190 from ansible.module_utils.basic import AnsibleModule
191
192 from ..module_utils.bigip import F5RestClient
193 from ..module_utils.common import (
194 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
195 )
196 from ..module_utils.compare import cmp_simple_list
197 from ..module_utils.icontrol import tmos_version
198 from ..module_utils.teem import send_teem
199
200
201 class Parameters(AnsibleF5Parameters):
202 api_map = {
203 'lacpMode': 'lacp_mode',
204 'lacpTimeout': 'lacp_timeout',
205 'linkSelectPolicy': 'link_selection_policy',
206 'distributionHash': 'frame_distribution_hash',
207 'lacp': 'lacp_enabled',
208 'qinqEthertype': 'qinq_ethertype',
209 }
210
211 api_attributes = [
212 'lacp',
213 'lacpMode',
214 'lacpTimeout',
215 'linkSelectPolicy',
216 'distributionHash',
217 'interfaces',
218 'description',
219 'qinqEthertype',
220 ]
221
222 returnables = [
223 'lacp_mode',
224 'lacp_timeout',
225 'link_selection_policy',
226 'frame_distribution_hash',
227 'lacp_enabled',
228 'interfaces',
229 'description',
230 'qinq_ethertype',
231 ]
232
233 updatables = [
234 'lacp_mode',
235 'lacp_timeout',
236 'link_selection_policy',
237 'frame_distribution_hash',
238 'lacp_enabled',
239 'interfaces',
240 'description',
241 'qinq_ethertype',
242 ]
243
244
245 class ApiParameters(Parameters):
246 @property
247 def lacp_enabled(self):
248 if self._values['lacp_enabled'] is None:
249 return None
250 if self._values['lacp_enabled'] == 'enabled':
251 return True
252 return False
253
254 @property
255 def interfaces(self):
256 if self._values['interfaces'] is None:
257 return None
258 result = list(set(self._values['interfaces']))
259 result.sort()
260 return result
261
262
263 class ModuleParameters(Parameters):
264 @property
265 def frame_distribution_hash(self):
266 if self._values['frame_distribution_hash'] is None:
267 return None
268 elif self._values['frame_distribution_hash'] == 'source-destination-ip':
269 return 'src-dst-ipport'
270 elif self._values['frame_distribution_hash'] == 'source-destination-mac':
271 return 'src-dst-mac'
272 elif self._values['frame_distribution_hash'] == 'destination-mac':
273 return 'dst-mac'
274
275 @property
276 def interfaces(self):
277 if self._values['interfaces'] is None:
278 return None
279 if len(self._values['interfaces']) == 1 and self._values['interfaces'][0] == '':
280 return ''
281 result = [str(x) for x in self._values['interfaces']]
282 result = list(set(result))
283 result.sort()
284 return result
285
286
287 class Changes(Parameters):
288 def to_return(self):
289 result = {}
290 try:
291 for returnable in self.returnables:
292 result[returnable] = getattr(self, returnable)
293 result = self._filter_params(result)
294 except Exception:
295 pass
296 return result
297
298
299 class UsableChanges(Changes):
300 @property
301 def lacp_enabled(self):
302 if self._values['lacp_enabled'] is None:
303 return None
304 if self._values['lacp_enabled']:
305 return 'enabled'
306 return 'disabled'
307
308
309 class ReportableChanges(Changes):
310 @property
311 def frame_distribution_hash(self):
312 if self._values['frame_distribution_hash'] is None:
313 return None
314 elif self._values['frame_distribution_hash'] == 'src-dst-ipport':
315 return 'source-destination-ip'
316 elif self._values['frame_distribution_hash'] == 'src-dst-mac':
317 return 'source-destination-mac'
318 elif self._values['frame_distribution_hash'] == 'dst-mac':
319 return 'destination-mac'
320
321 @property
322 def lacp_enabled(self):
323 if self._values['lacp_enabled'] is None:
324 return None
325 if self._values['lacp_enabled'] == 'enabled':
326 return True
327 return False
328
329
330 class Difference(object):
331 def __init__(self, want, have=None):
332 self.want = want
333 self.have = have
334
335 def compare(self, param):
336 try:
337 result = getattr(self, param)
338 return result
339 except AttributeError:
340 return self.__default(param)
341
342 def __default(self, param):
343 attr1 = getattr(self.want, param)
344 try:
345 attr2 = getattr(self.have, param)
346 if attr1 != attr2:
347 return attr1
348 except AttributeError:
349 return attr1
350
351 @property
352 def interfaces(self):
353 result = cmp_simple_list(self.want.interfaces, self.have.interfaces)
354 return result
355
356
357 class ModuleManager(object):
358 def __init__(self, *args, **kwargs):
359 self.module = kwargs.get('module', None)
360 self.client = F5RestClient(**self.module.params)
361 self.want = ModuleParameters(params=self.module.params)
362 self.have = ApiParameters()
363 self.changes = UsableChanges()
364
365 def _set_changed_options(self):
366 changed = {}
367 for key in Parameters.returnables:
368 if getattr(self.want, key) is not None:
369 changed[key] = getattr(self.want, key)
370 if changed:
371 self.changes = UsableChanges(params=changed)
372
373 def _update_changed_options(self):
374 diff = Difference(self.want, self.have)
375 updatables = Parameters.updatables
376 changed = dict()
377 for k in updatables:
378 change = diff.compare(k)
379 if change is None:
380 continue
381 else:
382 if isinstance(change, dict):
383 changed.update(change)
384 else:
385 changed[k] = change
386 if changed:
387 self.changes = UsableChanges(params=changed)
388 return True
389 return False
390
391 def should_update(self):
392 result = self._update_changed_options()
393 if result:
394 return True
395 return False
396
397 def exec_module(self):
398 start = datetime.now().isoformat()
399 version = tmos_version(self.client)
400 changed = False
401 result = dict()
402 state = self.want.state
403
404 if state == "present":
405 changed = self.present()
406 elif state == "absent":
407 changed = self.absent()
408
409 reportable = ReportableChanges(params=self.changes.to_return())
410 changes = reportable.to_return()
411 result.update(**changes)
412 result.update(dict(changed=changed))
413 self._announce_deprecations(result)
414 send_teem(start, self.client, self.module, version)
415 return result
416
417 def _announce_deprecations(self, result):
418 warnings = result.pop('__warnings', [])
419 for warning in warnings:
420 self.client.module.deprecate(
421 msg=warning['msg'],
422 version=warning['version']
423 )
424
425 def present(self):
426 if self.exists():
427 return self.update()
428 else:
429 return self.create()
430
431 def absent(self):
432 if self.exists():
433 return self.remove()
434 return False
435
436 def update(self):
437 self.have = self.read_current_from_device()
438 if not self.should_update():
439 return False
440 if self.module.check_mode:
441 return True
442 self.update_on_device()
443 return True
444
445 def remove(self):
446 if self.module.check_mode:
447 return True
448 self.remove_from_device()
449 if self.exists():
450 raise F5ModuleError("Failed to delete the resource.")
451 return True
452
453 def create(self):
454 if self.want.link_selection_policy is None:
455 self.want.update({'link_selection_policy': 'auto'})
456 if self.want.frame_distribution_hash is None:
457 self.want.update({'frame_distribution_hash': 'source-destination-ip'})
458 if self.want.lacp_enabled is None:
459 self.want.update({'lacp_enabled': False})
460 if self.want.lacp_mode is None:
461 self.want.update({'lacp_mode': 'active'})
462 if self.want.lacp_timeout is None:
463 self.want.update({'lacp_timeout': 'long'})
464 self._set_changed_options()
465 if self.module.check_mode:
466 return True
467 self.create_on_device()
468 return True
469
470 def exists(self):
471 uri = "https://{0}:{1}/mgmt/tm/net/trunk/{2}".format(
472 self.client.provider['server'],
473 self.client.provider['server_port'],
474 self.want.name
475 )
476 resp = self.client.api.get(uri)
477 try:
478 response = resp.json()
479 except ValueError as ex:
480 raise F5ModuleError(str(ex))
481
482 if resp.status == 404 or 'code' in response and response['code'] == 404:
483 return False
484 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
485 return True
486
487 errors = [401, 403, 409, 500, 501, 502, 503, 504]
488
489 if resp.status in errors or 'code' in response and response['code'] in errors:
490 if 'message' in response:
491 raise F5ModuleError(response['message'])
492 else:
493 raise F5ModuleError(resp.content)
494
495 def create_on_device(self):
496 params = self.changes.api_params()
497 params['name'] = self.want.name
498 uri = "https://{0}:{1}/mgmt/tm/net/trunk/".format(
499 self.client.provider['server'],
500 self.client.provider['server_port'],
501 )
502 resp = self.client.api.post(uri, json=params)
503 try:
504 response = resp.json()
505 except ValueError as ex:
506 raise F5ModuleError(str(ex))
507
508 if 'code' in response and response['code'] in [400, 403, 409]:
509 if 'message' in response:
510 raise F5ModuleError(response['message'])
511 else:
512 raise F5ModuleError(resp.content)
513
514 def update_on_device(self):
515 params = self.changes.api_params()
516 uri = "https://{0}:{1}/mgmt/tm/net/trunk/{2}".format(
517 self.client.provider['server'],
518 self.client.provider['server_port'],
519 self.want.name
520 )
521 resp = self.client.api.patch(uri, json=params)
522 try:
523 response = resp.json()
524 except ValueError as ex:
525 raise F5ModuleError(str(ex))
526
527 if 'code' in response and response['code'] == 400:
528 if 'message' in response:
529 raise F5ModuleError(response['message'])
530 else:
531 raise F5ModuleError(resp.content)
532
533 def remove_from_device(self):
534 uri = "https://{0}:{1}/mgmt/tm/net/trunk/{2}".format(
535 self.client.provider['server'],
536 self.client.provider['server_port'],
537 self.want.name
538 )
539 resp = self.client.api.delete(uri)
540 if resp.status == 200:
541 return True
542
543 def read_current_from_device(self):
544 uri = "https://{0}:{1}/mgmt/tm/net/trunk/{2}".format(
545 self.client.provider['server'],
546 self.client.provider['server_port'],
547 self.want.name
548 )
549 resp = self.client.api.get(uri)
550 try:
551 response = resp.json()
552 except ValueError as ex:
553 raise F5ModuleError(str(ex))
554
555 if 'code' in response and response['code'] == 400:
556 if 'message' in response:
557 raise F5ModuleError(response['message'])
558 else:
559 raise F5ModuleError(resp.content)
560 return ApiParameters(params=response)
561
562
563 class ArgumentSpec(object):
564 def __init__(self):
565 self.supports_check_mode = True
566 argument_spec = dict(
567 name=dict(required=True),
568 interfaces=dict(
569 type='list',
570 elements='str',
571 ),
572 link_selection_policy=dict(
573 choices=['auto', 'maximum-bandwidth']
574 ),
575 frame_distribution_hash=dict(
576 choices=['destination-mac', 'source-destination-ip', 'source-destination-mac']
577 ),
578 lacp_enabled=dict(type='bool'),
579 lacp_mode=dict(choices=['active', 'passive']),
580 lacp_timeout=dict(choices=['short', 'long']),
581 description=dict(),
582 state=dict(
583 default='present',
584 choices=['absent', 'present']
585 ),
586 qinq_ethertype=dict(type='raw'),
587 )
588 self.argument_spec = {}
589 self.argument_spec.update(f5_argument_spec)
590 self.argument_spec.update(argument_spec)
591
592
593 def main():
594 spec = ArgumentSpec()
595
596 module = AnsibleModule(
597 argument_spec=spec.argument_spec,
598 supports_check_mode=spec.supports_check_mode
599 )
600
601 try:
602 mm = ModuleManager(module=module)
603 results = mm.exec_module()
604 module.exit_json(**results)
605 except F5ModuleError as ex:
606 module.fail_json(msg=str(ex))
607
608
609 if __name__ == '__main__':
610 main()