Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2016, 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_routedomain
13 short_description: Manage route domains on a BIG-IP
14 description:
15 - Manage route domains on a BIG-IP system. A route domain is a BIG-IP
16 configuration object that isolates network traffic for a particular
17 application on the network.
18 version_added: "1.0.0"
19 options:
20 name:
21 description:
22 - The name of the route domain.
23 type: str
24 bwc_policy:
25 description:
26 - The bandwidth controller for the route domain.
27 type: str
28 connection_limit:
29 description:
30 - The maximum number of concurrent connections allowed for the
31 route domain. Setting this to C(0) turns off connection limits.
32 type: int
33 description:
34 description:
35 - Specifies descriptive text that identifies the route domain.
36 type: str
37 flow_eviction_policy:
38 description:
39 - The eviction policy to use with this route domain. Apply an eviction
40 policy to provide customized responses to flow overflows and slow
41 flows on the route domain.
42 type: str
43 id:
44 description:
45 - The unique identifying integer representing the route domain.
46 - This field is required when creating a new route domain.
47 - In version 2.5, this value is no longer used to reference a route domain when
48 making modifications to it (for instance during update and delete operations).
49 Instead, the C(name) parameter is used. In version 2.6, the C(name) value will
50 become a required parameter.
51 type: int
52 parent:
53 description:
54 - Specifies the route domain the system searches when it cannot
55 find a route in the configured domain.
56 type: str
57 partition:
58 description:
59 - Partition on which you want to create the route domain. Partitions cannot be updated
60 once they are created.
61 type: str
62 default: Common
63 routing_protocol:
64 description:
65 - Dynamic routing protocols for the system to use in the route domain.
66 type: list
67 elements: str
68 choices:
69 - none
70 - BFD
71 - BGP
72 - IS-IS
73 - OSPFv2
74 - OSPFv3
75 - PIM
76 - RIP
77 - RIPng
78 service_policy:
79 description:
80 - Service policy to associate with the route domain.
81 type: str
82 state:
83 description:
84 - Whether the route domain should exist or not.
85 type: str
86 choices:
87 - present
88 - absent
89 default: present
90 strict:
91 description:
92 - Specifies whether the system enforces cross-routing restrictions or not.
93 type: bool
94 vlans:
95 description:
96 - VLANs for the system to use in the route domain.
97 type: list
98 elements: str
99 fw_enforced_policy:
100 description:
101 - Specifies an AFM policy to be attached to route domain.
102 - To remove attached AFM policy use C("") or C(none) as values.
103 type: str
104 extends_documentation_fragment: f5networks.f5_modules.f5
105 author:
106 - Tim Rupp (@caphrim007)
107 - Wojciech Wypior (@wojtek0806)
108 '''
109
110 EXAMPLES = r'''
111 - name: Create a route domain
112 bigip_routedomain:
113 name: foo
114 id: 1234
115 state: present
116 provider:
117 user: admin
118 password: secret
119 server: lb.mydomain.com
120 delegate_to: localhost
121
122 - name: Set VLANs on the route domain
123 bigip_routedomain:
124 name: bar
125 state: present
126 vlans:
127 - net1
128 - foo
129 provider:
130 password: secret
131 server: lb.mydomain.com
132 user: admin
133 delegate_to: localhost
134 '''
135
136 RETURN = r'''
137 id:
138 description: The ID of the route domain that was changed.
139 returned: changed
140 type: int
141 sample: 2
142 description:
143 description: The description of the route domain.
144 returned: changed
145 type: str
146 sample: route domain foo
147 strict:
148 description: The new strict isolation setting.
149 returned: changed
150 type: str
151 sample: enabled
152 parent:
153 description: The new parent route domain.
154 returned: changed
155 type: int
156 sample: 0
157 vlans:
158 description: List of new VLANs to which the route domain is applied.
159 returned: changed
160 type: list
161 sample: ['/Common/http-tunnel', '/Common/socks-tunnel']
162 routing_protocol:
163 description: List of routing protocols applied to the route domain.
164 returned: changed
165 type: list
166 sample: ['bfd', 'bgp']
167 bwc_policy:
168 description: The new bandwidth controller.
169 returned: changed
170 type: str
171 sample: /Common/foo
172 connection_limit:
173 description: The new connection limit for the route domain.
174 returned: changed
175 type: int
176 sample: 100
177 flow_eviction_policy:
178 description: The new eviction policy to use with this route domain.
179 returned: changed
180 type: str
181 sample: /Common/default-eviction-policy
182 service_policy:
183 description: The new service policy to use with this route domain.
184 returned: changed
185 type: str
186 sample: /Common-my-service-policy
187 fw_enforced_policy:
188 description: Specifies the AFM policy to be attached to route domain.
189 returned: changed
190 type: str
191 sample: /Common/afm-blocking-policy
192 '''
193 from datetime import datetime
194
195 from ansible.module_utils.basic import (
196 AnsibleModule, env_fallback
197 )
198
199 from ..module_utils.bigip import F5RestClient
200 from ..module_utils.common import (
201 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
202 )
203 from ..module_utils.compare import cmp_simple_list
204 from ..module_utils.icontrol import tmos_version
205 from ..module_utils.teem import send_teem
206
207
208 class Parameters(AnsibleF5Parameters):
209 api_map = {
210 'connectionLimit': 'connection_limit',
211 'servicePolicy': 'service_policy',
212 'bwcPolicy': 'bwc_policy',
213 'flowEvictionPolicy': 'flow_eviction_policy',
214 'routingProtocol': 'routing_protocol',
215 'fwEnforcedPolicy': 'fw_enforced_policy',
216 'fwEnforcedPolicyReference': 'fw_policy_link',
217 }
218
219 api_attributes = [
220 'connectionLimit',
221 'description',
222 'strict',
223 'parent',
224 'servicePolicy',
225 'bwcPolicy',
226 'flowEvictionPolicy',
227 'routingProtocol',
228 'vlans',
229 'id',
230 'fwEnforcedPolicy',
231 'fwEnforcedPolicyReference',
232 ]
233
234 returnables = [
235 'description',
236 'strict',
237 'parent',
238 'service_policy',
239 'bwc_policy',
240 'flow_eviction_policy',
241 'routing_protocol',
242 'vlans',
243 'connection_limit',
244 'id',
245 ]
246
247 updatables = [
248 'description',
249 'strict',
250 'parent',
251 'service_policy',
252 'bwc_policy',
253 'flow_eviction_policy',
254 'routing_protocol',
255 'vlans',
256 'connection_limit',
257 'id',
258 'fw_enforced_policy',
259 'fw_policy_link',
260 ]
261
262 @property
263 def connection_limit(self):
264 if self._values['connection_limit'] is None:
265 return None
266 return int(self._values['connection_limit'])
267
268 @property
269 def id(self):
270 if self._values['id'] is None:
271 return None
272 return int(self._values['id'])
273
274
275 class ApiParameters(Parameters):
276 @property
277 def strict(self):
278 if self._values['strict'] is None:
279 return None
280 if self._values['strict'] == 'enabled':
281 return True
282 return False
283
284 @property
285 def domains(self):
286 domains = self.read_domains_from_device()
287 result = [x['fullPath'] for x in domains['items']]
288 return result
289
290 def read_domains_from_device(self):
291 uri = "https://{0}:{1}/mgmt/tm/net/route-domain/".format(
292 self.client.provider['server'],
293 self.client.provider['server_port'],
294 )
295 resp = self.client.api.get(uri)
296 try:
297 response = resp.json()
298 except ValueError as ex:
299 raise F5ModuleError(str(ex))
300
301 if 'code' in response and response['code'] == 400:
302 if 'message' in response:
303 raise F5ModuleError(response['message'])
304 else:
305 raise F5ModuleError(resp.content)
306 return response
307
308
309 class ModuleParameters(Parameters):
310 @property
311 def bwc_policy(self):
312 if self._values['bwc_policy'] is None:
313 return None
314 return fq_name(self.partition, self._values['bwc_policy'])
315
316 @property
317 def flow_eviction_policy(self):
318 if self._values['flow_eviction_policy'] is None:
319 return None
320 return fq_name(self.partition, self._values['flow_eviction_policy'])
321
322 @property
323 def service_policy(self):
324 if self._values['service_policy'] is None:
325 return None
326 return fq_name(self.partition, self._values['service_policy'])
327
328 @property
329 def parent(self):
330 if self._values['parent'] is None:
331 return None
332 result = fq_name(self.partition, self._values['parent'])
333 return result
334
335 @property
336 def vlans(self):
337 if self._values['vlans'] is None:
338 return None
339 if len(self._values['vlans']) == 1 and self._values['vlans'][0] == '':
340 return ''
341 return [fq_name(self.partition, x) for x in self._values['vlans']]
342
343 @property
344 def name(self):
345 if self._values['name'] is None:
346 return str(self.id)
347 return self._values['name']
348
349 @property
350 def routing_protocol(self):
351 if self._values['routing_protocol'] is None:
352 return None
353 if len(self._values['routing_protocol']) == 1 and self._values['routing_protocol'][0] in ['', 'none']:
354 return ''
355 return self._values['routing_protocol']
356
357 @property
358 def fw_enforced_policy(self):
359 policy = self._values['fw_enforced_policy']
360 if policy is None:
361 return None
362 if policy.lower() in ['none', '']:
363 return ''
364 name = self._values['fw_enforced_policy']
365 return fq_name(self.partition, name)
366
367 @property
368 def fw_policy_link(self):
369 policy = self.fw_enforced_policy
370 if not policy:
371 return None
372 tmp = policy.split('/')
373 link = dict(link='https://localhost/mgmt/tm/security/firewall/policy/~{0}~{1}'.format(tmp[1], tmp[2]))
374 return link
375
376
377 class Changes(Parameters):
378 def to_return(self):
379 result = {}
380 try:
381 for returnable in self.returnables:
382 result[returnable] = getattr(self, returnable)
383 result = self._filter_params(result)
384 except Exception:
385 pass
386 return result
387
388
389 class UsableChanges(Changes):
390 @property
391 def strict(self):
392 if self._values['strict'] is None:
393 return None
394 if self._values['strict']:
395 return 'enabled'
396 return 'disabled'
397
398
399 class ReportableChanges(Changes):
400 @property
401 def strict(self):
402 if self._values['strict'] is None:
403 return None
404 if self._values['strict'] == 'enabled':
405 return 'yes'
406 return 'no'
407
408
409 class Difference(object):
410 def __init__(self, want, have=None):
411 self.want = want
412 self.have = have
413
414 def compare(self, param):
415 try:
416 result = getattr(self, param)
417 return result
418 except AttributeError:
419 return self.__default(param)
420
421 def __default(self, param):
422 attr1 = getattr(self.want, param)
423 try:
424 attr2 = getattr(self.have, param)
425 if attr1 != attr2:
426 return attr1
427 except AttributeError:
428 return attr1
429
430 @property
431 def routing_protocol(self):
432 return cmp_simple_list(self.want.routing_protocol, self.have.routing_protocol)
433
434 @property
435 def vlans(self):
436 return cmp_simple_list(self.want.vlans, self.have.vlans)
437
438 @property
439 def fw_policy_link(self):
440 if self.want.fw_enforced_policy is None:
441 return None
442 if self.want.fw_enforced_policy == '' and self.have.fw_enforced_policy is None:
443 return None
444 if self.want.fw_enforced_policy == self.have.fw_enforced_policy:
445 return None
446 if self.want.fw_policy_link != self.have.fw_policy_link:
447 return self.want.fw_policy_link
448
449 @property
450 def fw_enforced_policy(self):
451 if self.want.fw_enforced_policy is None:
452 return None
453 if self.want.fw_enforced_policy == '' and self.have.fw_enforced_policy is None:
454 return None
455 if self.want.fw_enforced_policy != self.have.fw_enforced_policy:
456 return self.want.fw_enforced_policy
457
458
459 class ModuleManager(object):
460 def __init__(self, *args, **kwargs):
461 self.module = kwargs.get('module', None)
462 self.client = F5RestClient(**self.module.params)
463 self.want = ModuleParameters(params=self.module.params, client=self.client)
464 self.have = ApiParameters(client=self.client)
465 self.changes = UsableChanges()
466
467 def _set_changed_options(self):
468 changed = {}
469 for key in Parameters.returnables:
470 if getattr(self.want, key) is not None:
471 changed[key] = getattr(self.want, key)
472 if changed:
473 self.changes = UsableChanges(params=changed)
474
475 def _update_changed_options(self):
476 diff = Difference(self.want, self.have)
477 updatables = Parameters.updatables
478 changed = dict()
479 for k in updatables:
480 change = diff.compare(k)
481 if change is None:
482 continue
483 else:
484 if isinstance(change, dict):
485 changed.update(change)
486 else:
487 changed[k] = change
488 if changed:
489 self.changes = UsableChanges(params=changed)
490 return True
491 return False
492
493 def should_update(self):
494 result = self._update_changed_options()
495 if result:
496 return True
497 return False
498
499 def exec_module(self):
500 start = datetime.now().isoformat()
501 version = tmos_version(self.client)
502 changed = False
503 result = dict()
504 state = self.want.state
505
506 if state == "present":
507 changed = self.present()
508 elif state == "absent":
509 changed = self.absent()
510
511 reportable = ReportableChanges(params=self.changes.to_return())
512 changes = reportable.to_return()
513 result.update(**changes)
514 result.update(dict(changed=changed))
515 self._announce_deprecations(result)
516 send_teem(start, self.client, self.module, version)
517 return result
518
519 def _announce_deprecations(self, result):
520 warnings = result.pop('__warnings', [])
521 for warning in warnings:
522 self.client.module.deprecate(
523 msg=warning['msg'],
524 version=warning['version']
525 )
526
527 def present(self):
528 if self.exists():
529 return self.update()
530 else:
531 return self.create()
532
533 def absent(self):
534 if self.exists():
535 return self.remove()
536 return False
537
538 def update(self):
539 self.have = self.read_current_from_device()
540 if not self.should_update():
541 return False
542 if self.want.parent and self.want.parent not in self.have.domains:
543 raise F5ModuleError(
544 "The parent route domain was not found."
545 )
546 if self.module.check_mode:
547 return True
548 self.update_on_device()
549 return True
550
551 def remove(self):
552 if self.module.check_mode:
553 return True
554 self.remove_from_device()
555 if self.exists():
556 raise F5ModuleError("Failed to delete the resource.")
557 return True
558
559 def create(self):
560 if self.want.id is None:
561 raise F5ModuleError(
562 "The 'id' parameter is required when creating new route domains."
563 )
564 if self.want.parent and self.want.parent not in self.have.domains:
565 raise F5ModuleError(
566 "The parent route domain was not found."
567 )
568 self._set_changed_options()
569 if self.module.check_mode:
570 return True
571 self.create_on_device()
572 return True
573
574 def exists(self):
575 uri = "https://{0}:{1}/mgmt/tm/net/route-domain/{2}".format(
576 self.client.provider['server'],
577 self.client.provider['server_port'],
578 transform_name(self.want.partition, self.want.name),
579 )
580 resp = self.client.api.get(uri)
581 try:
582 response = resp.json()
583 except ValueError as ex:
584 raise F5ModuleError(str(ex))
585
586 if resp.status == 404 or 'code' in response and response['code'] == 404:
587 return False
588 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
589 return True
590
591 errors = [401, 403, 409, 500, 501, 502, 503, 504]
592
593 if resp.status in errors or 'code' in response and response['code'] in errors:
594 if 'message' in response:
595 raise F5ModuleError(response['message'])
596 else:
597 raise F5ModuleError(resp.content)
598
599 def create_on_device(self):
600 params = self.changes.api_params()
601 params['name'] = self.want.name
602 params['partition'] = self.want.partition
603 uri = "https://{0}:{1}/mgmt/tm/net/route-domain/".format(
604 self.client.provider['server'],
605 self.client.provider['server_port'],
606 )
607 resp = self.client.api.post(uri, json=params)
608 try:
609 response = resp.json()
610 except ValueError as ex:
611 raise F5ModuleError(str(ex))
612
613 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
614 raise F5ModuleError(resp.content)
615
616 if self.want.fw_enforced_policy:
617 payload = dict(
618 fwEnforcedPolicy=self.want.fw_enforced_policy,
619 fwEnforcedPolicyReference=self.want.fw_policy_link
620 )
621 uri = "https://{0}:{1}/mgmt/tm/net/route-domain/{2}".format(
622 self.client.provider['server'],
623 self.client.provider['server_port'],
624 transform_name(self.want.partition, self.want.name),
625 )
626 resp = self.client.api.patch(uri, json=payload)
627
628 try:
629 response = resp.json()
630 except ValueError as ex:
631 raise F5ModuleError(str(ex))
632
633 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
634 raise F5ModuleError(resp.content)
635
636 return True
637
638 def update_on_device(self):
639 params = self.changes.api_params()
640 uri = "https://{0}:{1}/mgmt/tm/net/route-domain/{2}".format(
641 self.client.provider['server'],
642 self.client.provider['server_port'],
643 transform_name(self.want.partition, self.want.name),
644 )
645 resp = self.client.api.patch(uri, json=params)
646 try:
647 response = resp.json()
648 except ValueError as ex:
649 raise F5ModuleError(str(ex))
650
651 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
652 return True
653 raise F5ModuleError(resp.content)
654
655 def remove_from_device(self):
656 uri = "https://{0}:{1}/mgmt/tm/net/route-domain/{2}".format(
657 self.client.provider['server'],
658 self.client.provider['server_port'],
659 transform_name(self.want.partition, self.want.name),
660 )
661 response = self.client.api.delete(uri)
662 if response.status == 200:
663 return True
664 raise F5ModuleError(response.content)
665
666 def read_current_from_device(self):
667 uri = "https://{0}:{1}/mgmt/tm/net/route-domain/{2}".format(
668 self.client.provider['server'],
669 self.client.provider['server_port'],
670 transform_name(self.want.partition, self.want.name),
671 )
672 resp = self.client.api.get(uri)
673 try:
674 response = resp.json()
675 except ValueError as ex:
676 raise F5ModuleError(str(ex))
677
678 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
679 return ApiParameters(params=response, client=self.client)
680 raise F5ModuleError(resp.content)
681
682
683 class ArgumentSpec(object):
684 def __init__(self):
685 self.supports_check_mode = True
686 argument_spec = dict(
687 name=dict(),
688 id=dict(type='int'),
689 description=dict(),
690 strict=dict(type='bool'),
691 parent=dict(),
692 vlans=dict(
693 type='list',
694 elements='str',
695 ),
696 routing_protocol=dict(
697 type='list',
698 elements='str',
699 choices=['BFD', 'BGP', 'IS-IS', 'OSPFv2', 'OSPFv3', 'PIM', 'RIP', 'RIPng', 'none']
700 ),
701 bwc_policy=dict(),
702 connection_limit=dict(type='int'),
703 flow_eviction_policy=dict(),
704 service_policy=dict(),
705 fw_enforced_policy=dict(),
706 partition=dict(
707 default='Common',
708 fallback=(env_fallback, ['F5_PARTITION'])
709 ),
710 state=dict(
711 default='present',
712 choices=['present', 'absent']
713 )
714 )
715 self.argument_spec = {}
716 self.argument_spec.update(f5_argument_spec)
717 self.argument_spec.update(argument_spec)
718 self.required_one_of = [
719 ['name', 'id']
720 ]
721
722
723 def main():
724 spec = ArgumentSpec()
725
726 module = AnsibleModule(
727 argument_spec=spec.argument_spec,
728 supports_check_mode=spec.supports_check_mode,
729 required_one_of=spec.required_one_of
730 )
731
732 try:
733 mm = ModuleManager(module=module)
734 results = mm.exec_module()
735 module.exit_json(**results)
736 except F5ModuleError as ex:
737 module.fail_json(msg=str(ex))
738
739
740 if __name__ == '__main__':
741 main()