Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_static_route.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_static_route
13 short_description: Manipulate static routes on a BIG-IP
14 description:
15 - Manipulate static routes on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Name of the static route.
21 type: str
22 required: True
23 description:
24 description:
25 - Descriptive text that identifies the route.
26 type: str
27 destination:
28 description:
29 - Specifies an IP address for the static entry in the routing table.
30 When creating a new static route, this value is required.
31 - This value cannot be changed once it is set.
32 type: str
33 netmask:
34 description:
35 - The netmask for the static route. When creating a new static route, this value
36 is required.
37 - This value can be in either IP or CIDR format.
38 - This value cannot be changed once it is set.
39 type: str
40 gateway_address:
41 description:
42 - Specifies the router for the system to use when forwarding packets
43 to the destination host or network. Also known as the next-hop router
44 address. This can be either an IPv4 or IPv6 address. When it is an
45 IPv6 address that starts with C(FE80:), the address is treated
46 as a link-local address. This requires the C(vlan) parameter
47 also be supplied.
48 type: str
49 vlan:
50 description:
51 - Specifies the VLAN or Tunnel through which the system forwards packets
52 to the destination. When C(gateway_address) is a link-local IPv6
53 address, this value is required.
54 type: str
55 pool:
56 description:
57 - Specifies the pool through which the system forwards packets to the
58 destination.
59 type: str
60 reject:
61 description:
62 - Specifies the system drops packets sent to the destination.
63 type: bool
64 mtu:
65 description:
66 - Specifies a specific maximum transmission unit (MTU).
67 type: str
68 route_domain:
69 description:
70 - The route domain ID of the system. When creating a new static route, if
71 this value is not specified, the default value is C(0).
72 - This value cannot be changed once it is set.
73 type: int
74 partition:
75 description:
76 - Device partition to manage resources on.
77 type: str
78 default: Common
79 state:
80 description:
81 - When C(present), ensures the static route exists.
82 - When C(absent), ensures the static does not exist.
83 type: str
84 choices:
85 - present
86 - absent
87 default: present
88 extends_documentation_fragment: f5networks.f5_modules.f5
89 author:
90 - Tim Rupp (@caphrim007)
91 '''
92
93 EXAMPLES = r'''
94 - name: Create static route with gateway address
95 bigip_static_route:
96 destination: 10.10.10.10
97 netmask: 255.255.255.255
98 gateway_address: 10.2.2.3
99 name: test-route
100 provider:
101 password: secret
102 server: lb.mydomain.come
103 user: admin
104 validate_certs: false
105 delegate_to: localhost
106 '''
107
108 RETURN = r'''
109 vlan:
110 description: The VLAN or Tunnel through which the system forwards packets to the destination.
111 returned: changed
112 type: str
113 sample: /Common/vlan1
114 gateway_address:
115 description: The router for the system to use when forwarding packets to the destination host or network.
116 returned: changed
117 type: str
118 sample: 10.2.2.3
119 destination:
120 description: An IP address for the static entry in the routing table.
121 returned: changed
122 type: str
123 sample: 0.0.0.0/0
124 route_domain:
125 description: The route domain ID of the system.
126 returned: changed
127 type: int
128 sample: 1
129 netmask:
130 description: Netmask of the destination.
131 returned: changed
132 type: str
133 sample: 255.255.255.255
134 pool:
135 description: Whether the banner is enabled or not.
136 returned: changed
137 type: str
138 sample: true
139 partition:
140 description: The partition that the static route was created on.
141 returned: changed
142 type: str
143 sample: Common
144 description:
145 description: Descriptive text that identifies the route.
146 returned: changed
147 type: str
148 sample: "Route tho DMZ"
149 reject:
150 description: Specifies the system drops packets sent to the destination.
151 returned: changed
152 type: bool
153 sample: true
154 '''
155
156 import re
157 from datetime import datetime
158
159 from ansible.module_utils.basic import (
160 AnsibleModule, env_fallback
161 )
162 from ansible.module_utils.parsing.convert_bool import BOOLEANS_TRUE
163
164 from ipaddress import (
165 ip_network, ip_interface, ip_address
166 )
167
168 from ..module_utils.bigip import F5RestClient
169 from ..module_utils.common import (
170 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
171 )
172 from ..module_utils.ipaddress import (
173 is_valid_ip, ipv6_netmask_to_cidr
174 )
175 from ..module_utils.icontrol import tmos_version
176 from ..module_utils.teem import send_teem
177
178
179 class Parameters(AnsibleF5Parameters):
180 api_map = {
181 'tmInterface': 'vlan',
182 'gw': 'gateway_address',
183 'network': 'destination',
184 'blackhole': 'reject'
185 }
186
187 updatables = [
188 'description',
189 'gateway_address',
190 'vlan',
191 'pool',
192 'mtu',
193 'reject',
194 'destination',
195 'route_domain',
196 'netmask',
197 ]
198
199 returnables = [
200 'vlan',
201 'gateway_address',
202 'destination',
203 'pool',
204 'description',
205 'reject',
206 'mtu',
207 'netmask',
208 'route_domain',
209 ]
210
211 api_attributes = [
212 'tmInterface',
213 'gw',
214 'network',
215 'blackhole',
216 'description',
217 'pool',
218 'mtu',
219 ]
220
221 def to_return(self):
222 result = {}
223 for returnable in self.returnables:
224 result[returnable] = getattr(self, returnable)
225 result = self._filter_params(result)
226 return result
227
228 @property
229 def reject(self):
230 if self._values['reject'] in BOOLEANS_TRUE:
231 return True
232
233
234 class ModuleParameters(Parameters):
235 @property
236 def vlan(self):
237 if self._values['vlan'] is None:
238 return None
239 return fq_name(self.partition, self._values['vlan'])
240
241 @property
242 def gateway_address(self):
243 if self._values['gateway_address'] is None:
244 return None
245 try:
246 if '%' in self._values['gateway_address']:
247 addr = self._values['gateway_address'].split('%')[0]
248 ip_interface(u'%s' % str(addr))
249 else:
250 addr = self._values['gateway_address']
251 ip_interface(u'%s' % str(addr))
252 if self.route_domain:
253 result = str(addr).lower() + '%' + str(self.route_domain)
254 return result
255 return str(self._values['gateway_address']).lower()
256 except ValueError:
257 raise F5ModuleError(
258 "The provided gateway_address is not an IP address"
259 )
260
261 @property
262 def route_domain(self):
263 if self._values['route_domain'] is None:
264 return None
265 result = int(self._values['route_domain'])
266 return result
267
268 @property
269 def destination(self):
270 if self._values['destination'] is None:
271 return None
272 if self._values['destination'].startswith('default'):
273 self._values['destination'] = '0.0.0.0/0'
274 if self._values['destination'].startswith('default-inet6'):
275 self._values['destination'] = '::/0'
276 try:
277 ip = ip_network(u'%s' % str(self.destination_ip))
278 if self.route_domain:
279 return '{0}%{1}/{2}'.format(str(ip.network_address), self.route_domain, ip.prefixlen)
280 else:
281 return '{0}/{1}'.format(str(ip.network_address), ip.prefixlen)
282 except ValueError:
283 raise F5ModuleError(
284 "The provided destination is not an IP address"
285 )
286
287 @property
288 def destination_ip(self):
289 if self._values['destination']:
290 ip = ip_network(u'{0}/{1}'.format(self._values['destination'], self.netmask))
291 return '{0}/{1}'.format(str(ip.network_address), ip.prefixlen)
292
293 @property
294 def netmask(self):
295 if self._values['netmask'] is None:
296 return None
297 try:
298 result = int(self._values['netmask'])
299
300 # CIDRs between 0 and 128 are allowed
301 if 0 <= result <= 128:
302 return result
303 else:
304 raise F5ModuleError(
305 "The provided netmask must be between 0 and 32 for IPv4, or "
306 "0 and 128 for IPv6."
307 )
308 except ValueError:
309 # not a number, but that's ok. Further processing necessary
310 pass
311
312 if not is_valid_ip(self._values['netmask']):
313 raise F5ModuleError(
314 'The provided netmask {0} is neither in IP or CIDR format'.format(result)
315 )
316
317 # Create a temporary address to check if the netmask IP is v4 or v6
318 addr = ip_address(u'{0}'.format(str(self._values['netmask'])))
319 if addr.version == 4:
320 # Create a more real v4 address using a wildcard, so that we can determine
321 # the CIDR value from it.
322 ip = ip_network(u'0.0.0.0/%s' % str(self._values['netmask']))
323 result = ip.prefixlen
324 else:
325 result = ipv6_netmask_to_cidr(self._values['netmask'])
326
327 return result
328
329
330 class ApiParameters(Parameters):
331 @property
332 def route_domain(self):
333 if self._values['destination'] is None:
334 return None
335 pattern = r'([0-9a-zA-Z\:\-\.]+%(?P<rd>[0-9]+))'
336 matches = re.search(pattern, self._values['destination'])
337 if matches:
338 return int(matches.group('rd'))
339 return 0
340
341 @property
342 def destination_ip(self):
343 if self._values['destination'] is None:
344 return None
345 destination = self.destination_to_network()
346
347 try:
348 pattern = r'(?P<rd>%[0-9]+)'
349 addr = re.sub(pattern, '', destination)
350 ip = ip_network(u'%s' % str(addr))
351 return '{0}/{1}'.format(str(ip.network_address), ip.prefixlen)
352 except ValueError:
353 raise F5ModuleError(
354 "The provided destination is not an IP address."
355 )
356
357 @property
358 def netmask(self):
359 destination = self.destination_to_network()
360 ip = ip_network(u'%s' % str(destination))
361 return int(ip.prefixlen)
362
363 def destination_to_network(self):
364 destination = self._values['destination']
365 if destination.startswith('default%'):
366 destination = '0.0.0.0%{0}/0'.format(destination.split('%')[1])
367 elif destination.startswith('default-inet6%'):
368 destination = '::%{0}/0'.format(destination.split('%')[1])
369 elif destination.startswith('default-inet6'):
370 destination = '::/0'
371 elif destination.startswith('default'):
372 destination = '0.0.0.0/0'
373 return destination
374
375
376 class Changes(Parameters):
377 pass
378
379
380 class UsableChanges(Parameters):
381 pass
382
383
384 class ReportableChanges(Parameters):
385 pass
386
387
388 class Difference(object):
389 def __init__(self, want, have=None):
390 self.want = want
391 self.have = have
392
393 def compare(self, param):
394 try:
395 result = getattr(self, param)
396 return result
397 except AttributeError:
398 return self.__default(param)
399
400 def __default(self, param):
401 attr1 = getattr(self.want, param)
402 try:
403 attr2 = getattr(self.have, param)
404 if attr1 != attr2:
405 return attr1
406 except AttributeError:
407 return attr1
408
409 @property
410 def destination(self):
411 if self.want.destination_ip is None:
412 return None
413 if self.want.destination_ip != self.have.destination_ip:
414 raise F5ModuleError(
415 "The destination cannot be changed. Delete and recreate "
416 "the static route if you need to do this."
417 )
418
419 @property
420 def route_domain(self):
421 if self.want.route_domain is None:
422 return None
423 if self.want.route_domain is None and self.have.route_domain == 0:
424 return None
425 if self.want.route_domain != self.have.route_domain:
426 raise F5ModuleError("You cannot change the route domain.")
427
428 @property
429 def netmask(self):
430 if self.want.netmask is None:
431 return None
432 # It's easiest to just check the netmask by comparing dest IPs.
433 if self.want.destination_ip != self.have.destination_ip:
434 raise F5ModuleError(
435 "The netmask cannot be changed. Delete and recreate "
436 "the static route if you need to do this."
437 )
438
439
440 class ModuleManager(object):
441 def __init__(self, *args, **kwargs):
442 self.module = kwargs.get('module', None)
443 self.client = F5RestClient(**self.module.params)
444 self.have = None
445 self.want = ModuleParameters(params=self.module.params)
446 self.changes = UsableChanges()
447
448 def _set_changed_options(self):
449 changed = {}
450 for key in Parameters.returnables:
451 if getattr(self.want, key) is not None:
452 changed[key] = getattr(self.want, key)
453 if changed:
454 self.changes = UsableChanges(params=changed)
455
456 def _update_changed_options(self):
457 diff = Difference(self.want, self.have)
458 updatables = Parameters.updatables
459 changed = dict()
460 for k in updatables:
461 change = diff.compare(k)
462 if change is None:
463 continue
464 else:
465 if k in ['netmask', 'route_domain']:
466 changed['address'] = change
467 else:
468 changed[k] = change
469 if changed:
470 self.changes = UsableChanges(params=changed)
471 return True
472 return False
473
474 def exec_module(self):
475 start = datetime.now().isoformat()
476 version = tmos_version(self.client)
477 changed = False
478 result = dict()
479 state = self.want.state
480
481 if state == "present":
482 changed = self.present()
483 elif state == "absent":
484 changed = self.absent()
485
486 reportable = ReportableChanges(params=self.changes.to_return())
487 changes = reportable.to_return()
488 result.update(**changes)
489 result.update(dict(changed=changed))
490 self._announce_deprecations(result)
491 send_teem(start, self.client, self.module, version)
492 return result
493
494 def _announce_deprecations(self, result):
495 warnings = result.pop('__warnings', [])
496 for warning in warnings:
497 self.module.deprecate(
498 msg=warning['msg'],
499 version=warning['version']
500 )
501
502 def exists(self):
503 uri = "https://{0}:{1}/mgmt/tm/net/route/{2}".format(
504 self.client.provider['server'],
505 self.client.provider['server_port'],
506 transform_name(self.want.partition, self.want.name)
507 )
508 resp = self.client.api.get(uri)
509 try:
510 response = resp.json()
511 except ValueError as ex:
512 raise F5ModuleError(str(ex))
513
514 if resp.status == 404 or 'code' in response and response['code'] == 404:
515 return False
516 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
517 return True
518
519 errors = [401, 403, 409, 500, 501, 502, 503, 504]
520
521 if resp.status in errors or 'code' in response and response['code'] in errors:
522 if 'message' in response:
523 raise F5ModuleError(response['message'])
524 else:
525 raise F5ModuleError(resp.content)
526
527 def present(self):
528 if self.exists():
529 return self.update()
530 else:
531 return self.create()
532
533 def create(self):
534 required_resources = ['pool', 'vlan', 'reject', 'gateway_address']
535 self._set_changed_options()
536 if self.want.destination is None:
537 raise F5ModuleError(
538 'destination must be specified when creating a static route'
539 )
540 if self.want.netmask is None:
541 raise F5ModuleError(
542 'netmask must be specified when creating a static route'
543 )
544 if all(getattr(self.want, v) is None for v in required_resources):
545 raise F5ModuleError(
546 "You must specify at least one of " + ', '.join(required_resources)
547 )
548 if self.module.check_mode:
549 return True
550 self.create_on_device()
551 return True
552
553 def should_update(self):
554 result = self._update_changed_options()
555 if result:
556 return True
557 return False
558
559 def update(self):
560 self.have = self.read_current_from_device()
561 if not self.should_update():
562 return False
563 if self.module.check_mode:
564 return True
565 self.update_on_device()
566 return True
567
568 def update_on_device(self):
569 params = self.want.api_params()
570
571 # The 'network' attribute is not updatable
572 params.pop('network', None)
573
574 uri = "https://{0}:{1}/mgmt/tm/net/route/{2}".format(
575 self.client.provider['server'],
576 self.client.provider['server_port'],
577 transform_name(self.want.partition, self.want.name)
578 )
579 resp = self.client.api.patch(uri, json=params)
580 try:
581 response = resp.json()
582 except ValueError as ex:
583 raise F5ModuleError(str(ex))
584
585 if 'code' in response and response['code'] == 400:
586 if 'message' in response:
587 raise F5ModuleError(response['message'])
588 else:
589 raise F5ModuleError(resp.content)
590
591 def read_current_from_device(self):
592 uri = "https://{0}:{1}/mgmt/tm/net/route/{2}".format(
593 self.client.provider['server'],
594 self.client.provider['server_port'],
595 transform_name(self.want.partition, self.want.name)
596 )
597 resp = self.client.api.get(uri)
598 try:
599 response = resp.json()
600 except ValueError as ex:
601 raise F5ModuleError(str(ex))
602
603 if 'code' in response and response['code'] == 400:
604 if 'message' in response:
605 raise F5ModuleError(response['message'])
606 else:
607 raise F5ModuleError(resp.content)
608 return ApiParameters(params=response)
609
610 def create_on_device(self):
611 params = self.want.api_params()
612 params['name'] = self.want.name
613 params['partition'] = self.want.partition
614 uri = "https://{0}:{1}/mgmt/tm/net/route/".format(
615 self.client.provider['server'],
616 self.client.provider['server_port']
617 )
618 resp = self.client.api.post(uri, json=params)
619 try:
620 response = resp.json()
621 except ValueError as ex:
622 raise F5ModuleError(str(ex))
623
624 if 'code' in response and response['code'] in [400, 403]:
625 if 'message' in response:
626 raise F5ModuleError(response['message'])
627 else:
628 raise F5ModuleError(resp.content)
629
630 def absent(self):
631 if self.exists():
632 return self.remove()
633 return False
634
635 def remove(self):
636 if self.module.check_mode:
637 return True
638 self.remove_from_device()
639 if self.exists():
640 raise F5ModuleError("Failed to delete the static route")
641 return True
642
643 def remove_from_device(self):
644 uri = "https://{0}:{1}/mgmt/tm/net/route/{2}".format(
645 self.client.provider['server'],
646 self.client.provider['server_port'],
647 transform_name(self.want.partition, self.want.name)
648 )
649 resp = self.client.api.delete(uri)
650 if resp.status == 200:
651 return True
652
653
654 class ArgumentSpec(object):
655 def __init__(self):
656 self.supports_check_mode = True
657 argument_spec = dict(
658 name=dict(required=True),
659 description=dict(),
660 destination=dict(),
661 netmask=dict(),
662 gateway_address=dict(),
663 vlan=dict(),
664 pool=dict(),
665 mtu=dict(),
666 reject=dict(
667 type='bool'
668 ),
669 state=dict(
670 default='present',
671 choices=['absent', 'present']
672 ),
673 partition=dict(
674 default='Common',
675 fallback=(env_fallback, ['F5_PARTITION'])
676 ),
677 route_domain=dict(type='int')
678 )
679 self.argument_spec = {}
680 self.argument_spec.update(f5_argument_spec)
681 self.argument_spec.update(argument_spec)
682 self.mutually_exclusive = [
683 ['gateway_address', 'pool', 'reject']
684 ]
685
686
687 def main():
688 spec = ArgumentSpec()
689
690 module = AnsibleModule(
691 argument_spec=spec.argument_spec,
692 supports_check_mode=spec.supports_check_mode,
693 mutually_exclusive=spec.mutually_exclusive,
694 )
695
696 try:
697 mm = ModuleManager(module=module)
698 results = mm.exec_module()
699 module.exit_json(**results)
700 except F5ModuleError as ex:
701 module.fail_json(msg=str(ex))
702
703
704 if __name__ == '__main__':
705 main()