Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2018, 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_tunnel
13 short_description: Manage tunnels on a BIG-IP
14 description:
15 - Manages tunnels on a BIG-IP. Tunnels are usually based upon a tunnel profile which
16 defines both default arguments and constraints for the tunnel.
17 - Due to this, this module exposes a number of settings that may or may not be related
18 to the type of tunnel you are working with. It is important that you take this into
19 consideration when declaring your tunnel config.
20 - If a specific tunnel does not support the parameter you are considering, the documentation
21 of the parameter will usually make mention of this. Otherwise, when configuring that
22 parameter on the device, the device will notify you.
23 version_added: "1.0.0"
24 options:
25 name:
26 description:
27 - Specifies the name of the tunnel.
28 type: str
29 required: True
30 description:
31 description:
32 - Description of the tunnel.
33 type: str
34 profile:
35 description:
36 - Specifies the profile to associate with the tunnel for handling traffic.
37 - Depending on your selection, other settings become available or disappear.
38 - This parameter may not be changed after it is set.
39 type: str
40 key:
41 description:
42 - When applied to a GRE tunnel, this value specifies an optional field in the GRE header,
43 used to authenticate the source of the packet.
44 - When applied to a VXLAN or Geneve tunnel, this value specifies the Virtual Network
45 Identifier (VNI).
46 - When applied to an NVGRE tunnel, this value specifies the Virtual Subnet Identifier (VSID).
47 - When creating a new tunnel, if this parameter is supported by the tunnel profile but not
48 specified, the default value is C(0).
49 type: int
50 local_address:
51 description:
52 - Specifies the IP address of the local endpoint of the tunnel.
53 type: str
54 remote_address:
55 description:
56 - Specifies the IP address of the remote endpoint of the tunnel.
57 - For C(dslite), C(fec) (when configuring the FEC tunnel for receiving traffic only),
58 C(v6rd) (configured as a border relay), or C(map), the tunnel must have an unspecified
59 remote address (any).
60 type: str
61 secondary_address:
62 description:
63 - Specifies a non-floating IP address for the tunnel, to be used with host-initiated traffic.
64 type: str
65 mtu:
66 description:
67 - Specifies the maximum transmission unit (MTU) of the tunnel.
68 - When creating a new tunnel, if this parameter is supported by the tunnel profile but not
69 specified, the default value is C(0).
70 - The valid range is from C(0) to C(65515).
71 type: int
72 use_pmtu:
73 description:
74 - Enables or disables the tunnel to use the PMTU (Path MTU) information provided by ICMP
75 NeedFrag error messages.
76 - If C(true) and the tunnel C(mtu) is set to C(0), the tunnel will use the PMTU information.
77 - If C(true) and the tunnel C(mtu) is fixed to a non-zero value, the tunnel will use the
78 minimum of PMTU and MTU.
79 - If C(false), the tunnel will use fixed MTU or calculate its MTU using tunnel encapsulation
80 configurations.
81 type: bool
82 tos:
83 description:
84 - Specifies the Type of Service (TOS) value to insert in the encapsulating header of
85 transmitted packets.
86 - When creating a new tunnel, if this parameter is supported by the tunnel profile but not
87 specified, the default value is C(preserve).
88 - When C(preserve), the system copies the TOS value from the inner header to the outer header.
89 - You may also specify a numeric value. The possible values are from C(0) to C(255).
90 type: str
91 auto_last_hop:
92 description:
93 - Allows you to configure auto last hop on a per-tunnel basis.
94 - When creating a new tunnel, if this parameter is supported by the tunnel profile but not
95 specified, the default is C(default).
96 - When C(default), means that the system uses the global auto-lasthop setting to send back
97 the request.
98 - When C(enabled), allows the system to send return traffic to the MAC address that transmitted
99 the request, even if the routing table points to a different network or interface. As a
100 result, the system can send return traffic to clients even when there is no matching route.
101 type: str
102 choices:
103 - default
104 - enabled
105 - disabled
106 traffic_group:
107 description:
108 - Specifies the traffic group to associate with the tunnel.
109 - This value cannot be changed after it is set. This is a limitation of BIG-IP.
110 type: str
111 mode:
112 description:
113 - Specifies how the tunnel carries traffic.
114 - When creating a new tunnel, if this parameter is supported by the tunnel profile but not
115 specified, the default is C(bidirectional).
116 - When C(bidirectional), specifies that the tunnel carries both inbound and outbound traffic.
117 - When C(inbound), specifies that the tunnel carries only incoming traffic.
118 - When C(outbound), specifies that the tunnel carries only outgoing traffic.
119 type: str
120 choices:
121 - bidirectional
122 - inbound
123 - outbound
124 transparent:
125 description:
126 - Specifies that the tunnel operates in transparent mode.
127 - When C(true), you can inspect and manipulate the encapsulated traffic flowing through the BIG-IP
128 system.
129 - A transparent tunnel terminates a tunnel while presenting the illusion that the tunnel transits
130 the device unmodified (that is, the BIG-IP system appears as if it were an intermediate router
131 that simply routes IP traffic through the device).
132 type: bool
133 partition:
134 description:
135 - Device partition to manage resources on.
136 type: str
137 default: Common
138 state:
139 description:
140 - When C(present), ensures that the tunnel exists.
141 - When C(absent), ensures the tunnel is removed.
142 type: str
143 choices:
144 - present
145 - absent
146 default: present
147 extends_documentation_fragment: f5networks.f5_modules.f5
148 author:
149 - Tim Rupp (@caphrim007)
150 '''
151
152 EXAMPLES = r'''
153 - name: Create a VXLAN tunnel
154 bigip_tunnel:
155 name: openshift-tunnel
156 local_address: 192.1681.240
157 key: 0
158 secondary_address: 192.168.1.100
159 mtu: 0
160 use_pmtu: true
161 tos: preserve
162 auto_last_hop: default
163 traffic_group: traffic-group-1
164 state: present
165 provider:
166 password: secret
167 server: lb.mydomain.com
168 user: admin
169 delegate_to: localhost
170 '''
171
172 RETURN = r'''
173 param1:
174 description: The new param1 value of the resource.
175 returned: changed
176 type: bool
177 sample: true
178 param2:
179 description: The new param2 value of the resource.
180 returned: changed
181 type: str
182 sample: Foo is bar
183 '''
184 from datetime import datetime
185
186 from ansible.module_utils.basic import (
187 AnsibleModule, env_fallback
188 )
189
190 from ..module_utils.bigip import F5RestClient
191 from ..module_utils.common import (
192 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name, flatten_boolean
193 )
194 from ..module_utils.icontrol import tmos_version
195 from ..module_utils.teem import send_teem
196
197
198 class Parameters(AnsibleF5Parameters):
199 api_map = {
200 'autoLasthop': 'auto_last_hop',
201 'localAddress': 'local_address',
202 'remoteAddress': 'remote_address',
203 'secondaryAddress': 'secondary_address',
204 'usePmtu': 'use_pmtu',
205 'trafficGroup': 'traffic_group',
206 }
207
208 api_attributes = [
209 'autoLasthop',
210 'description',
211 'key',
212 'mtu',
213 'profile',
214 'transparent',
215 'usePmtu',
216 'tos',
217 'secondaryAddress',
218 'remoteAddress',
219 'mode',
220 'localAddress',
221 'trafficGroup',
222 ]
223
224 returnables = [
225 'auto_last_hop',
226 'local_address',
227 'mode',
228 'remote_address',
229 'secondary_address',
230 'description',
231 'key',
232 'mtu',
233 'profile',
234 'transparent',
235 'use_pmtu',
236 'tos',
237 'traffic_group',
238 ]
239
240 updatables = [
241 'auto_last_hop',
242 'local_address',
243 'mode',
244 'remote_address',
245 'profile',
246 'secondary_address',
247 'description',
248 'key',
249 'mtu',
250 'transparent',
251 'use_pmtu',
252 'tos',
253 'traffic_group',
254 ]
255
256
257 class ApiParameters(Parameters):
258 pass
259
260
261 class ModuleParameters(Parameters):
262 @property
263 def transparent(self):
264 result = flatten_boolean(self._values['transparent'])
265 if result == 'yes':
266 return 'enabled'
267 elif result == 'no':
268 return 'disabled'
269
270 @property
271 def use_pmtu(self):
272 result = flatten_boolean(self._values['use_pmtu'])
273 if result == 'yes':
274 return 'enabled'
275 elif result == 'no':
276 return 'disabled'
277
278 @property
279 def profile(self):
280 if self._values['profile'] is None:
281 return None
282 return fq_name(self.partition, self._values['profile'])
283
284 @property
285 def traffic_group(self):
286 if self._values['traffic_group'] is None:
287 return None
288 elif self._values['traffic_group'] in ['', 'none']:
289 return ''
290 return fq_name(self.partition, self._values['traffic_group'])
291
292
293 class Changes(Parameters):
294 def to_return(self):
295 result = {}
296 try:
297 for returnable in self.returnables:
298 result[returnable] = getattr(self, returnable)
299 result = self._filter_params(result)
300 except Exception:
301 pass
302 return result
303
304
305 class UsableChanges(Changes):
306 pass
307
308
309 class ReportableChanges(Changes):
310 @property
311 def transparent(self):
312 result = flatten_boolean(self._values['transparent'])
313 return result
314
315 @property
316 def use_pmtu(self):
317 result = flatten_boolean(self._values['use_pmtu'])
318 return result
319
320
321 class Difference(object):
322 def __init__(self, want, have=None):
323 self.want = want
324 self.have = have
325
326 def compare(self, param):
327 try:
328 result = getattr(self, param)
329 return result
330 except AttributeError:
331 return self.__default(param)
332
333 def __default(self, param):
334 attr1 = getattr(self.want, param)
335 try:
336 attr2 = getattr(self.have, param)
337 if attr1 != attr2:
338 return attr1
339 except AttributeError:
340 return attr1
341
342 @property
343 def profile(self):
344 if self.want.profile is None:
345 return None
346 if self.want.profile != self.have.profile:
347 raise F5ModuleError(
348 "'profile' cannot be changed after it is set."
349 )
350
351 @property
352 def traffic_group(self):
353 if self.want.traffic_group is None:
354 return None
355 if self.want.traffic_group in ['', None] and self.have.traffic_group is None:
356 return None
357 if self.want.traffic_group != self.have.traffic_group:
358 raise F5ModuleError(
359 "'traffic_group' cannot be changed after it is set."
360 )
361
362
363 class ModuleManager(object):
364 def __init__(self, *args, **kwargs):
365 self.module = kwargs.get('module', None)
366 self.client = F5RestClient(**self.module.params)
367 self.want = ModuleParameters(params=self.module.params)
368 self.have = ApiParameters()
369 self.changes = UsableChanges()
370
371 def _set_changed_options(self):
372 changed = {}
373 for key in Parameters.returnables:
374 if getattr(self.want, key) is not None:
375 changed[key] = getattr(self.want, key)
376 if changed:
377 self.changes = UsableChanges(params=changed)
378
379 def _update_changed_options(self):
380 diff = Difference(self.want, self.have)
381 updatables = Parameters.updatables
382 changed = dict()
383 for k in updatables:
384 change = diff.compare(k)
385 if change is None:
386 continue
387 else:
388 if isinstance(change, dict):
389 changed.update(change)
390 else:
391 changed[k] = change
392 if changed:
393 self.changes = UsableChanges(params=changed)
394 return True
395 return False
396
397 def should_update(self):
398 result = self._update_changed_options()
399 if result:
400 return True
401 return False
402
403 def exec_module(self):
404 start = datetime.now().isoformat()
405 version = tmos_version(self.client)
406 changed = False
407 result = dict()
408 state = self.want.state
409
410 if state == "present":
411 changed = self.present()
412 elif state == "absent":
413 changed = self.absent()
414
415 reportable = ReportableChanges(params=self.changes.to_return())
416 changes = reportable.to_return()
417 result.update(**changes)
418 result.update(dict(changed=changed))
419 self._announce_deprecations(result)
420 send_teem(start, self.client, self.module, version)
421 return result
422
423 def _announce_deprecations(self, result):
424 warnings = result.pop('__warnings', [])
425 for warning in warnings:
426 self.client.module.deprecate(
427 msg=warning['msg'],
428 version=warning['version']
429 )
430
431 def present(self):
432 if self.exists():
433 return self.update()
434 else:
435 return self.create()
436
437 def exists(self):
438 uri = "https://{0}:{1}/mgmt/tm/net/tunnels/tunnel/{2}".format(
439 self.client.provider['server'],
440 self.client.provider['server_port'],
441 transform_name(self.want.partition, self.want.name)
442 )
443 resp = self.client.api.get(uri)
444 try:
445 response = resp.json()
446 except ValueError as ex:
447 raise F5ModuleError(str(ex))
448
449 if resp.status == 404 or 'code' in response and response['code'] == 404:
450 return False
451 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
452 return True
453
454 errors = [401, 403, 409, 500, 501, 502, 503, 504]
455
456 if resp.status in errors or 'code' in response and response['code'] in errors:
457 if 'message' in response:
458 raise F5ModuleError(response['message'])
459 else:
460 raise F5ModuleError(resp.content)
461
462 def update(self):
463 self.have = self.read_current_from_device()
464 if not self.should_update():
465 return False
466 if self.module.check_mode:
467 return True
468 self.update_on_device()
469 return True
470
471 def remove(self):
472 if self.module.check_mode:
473 return True
474 self.remove_from_device()
475 if self.exists():
476 raise F5ModuleError("Failed to delete the resource.")
477 return True
478
479 def create(self):
480 self._set_changed_options()
481 if self.module.check_mode:
482 return True
483 self.create_on_device()
484 return True
485
486 def create_on_device(self):
487 params = self.changes.api_params()
488 params['name'] = self.want.name
489 params['partition'] = self.want.partition
490 uri = "https://{0}:{1}/mgmt/tm/net/tunnels/tunnel/".format(
491 self.client.provider['server'],
492 self.client.provider['server_port']
493 )
494 resp = self.client.api.post(uri, json=params)
495 try:
496 response = resp.json()
497 except ValueError as ex:
498 raise F5ModuleError(str(ex))
499
500 if 'code' in response and response['code'] in [400, 403]:
501 if 'message' in response:
502 raise F5ModuleError(response['message'])
503 else:
504 raise F5ModuleError(resp.content)
505 return response['selfLink']
506
507 def update_on_device(self):
508 params = self.changes.api_params()
509 uri = "https://{0}:{1}/mgmt/tm/net/tunnels/tunnel/{2}".format(
510 self.client.provider['server'],
511 self.client.provider['server_port'],
512 transform_name(self.want.partition, self.want.name)
513 )
514 resp = self.client.api.patch(uri, json=params)
515 try:
516 response = resp.json()
517 except ValueError as ex:
518 raise F5ModuleError(str(ex))
519
520 if 'code' in response and response['code'] == 400:
521 if 'message' in response:
522 raise F5ModuleError(response['message'])
523 else:
524 raise F5ModuleError(resp.content)
525
526 def absent(self):
527 if self.exists():
528 return self.remove()
529 return False
530
531 def remove_from_device(self):
532 uri = "https://{0}:{1}/mgmt/tm/net/tunnels/tunnel/{2}".format(
533 self.client.provider['server'],
534 self.client.provider['server_port'],
535 transform_name(self.want.partition, self.want.name)
536 )
537 response = self.client.api.delete(uri)
538 if response.status == 200:
539 return True
540 if 'code' in response and response['code'] == 400:
541 if 'message' in response:
542 raise F5ModuleError(response['message'])
543 else:
544 raise F5ModuleError(response.content)
545
546 def read_current_from_device(self):
547 uri = "https://{0}:{1}/mgmt/tm/net/tunnels/tunnel/{2}".format(
548 self.client.provider['server'],
549 self.client.provider['server_port'],
550 transform_name(self.want.partition, self.want.name)
551 )
552 resp = self.client.api.get(uri)
553 try:
554 response = resp.json()
555 except ValueError as ex:
556 raise F5ModuleError(str(ex))
557
558 if 'code' in response and response['code'] == 400:
559 if 'message' in response:
560 raise F5ModuleError(response['message'])
561 else:
562 raise F5ModuleError(resp.content)
563 return ApiParameters(params=response)
564
565
566 class ArgumentSpec(object):
567 def __init__(self):
568 self.supports_check_mode = True
569 argument_spec = dict(
570 name=dict(required=True),
571 profile=dict(),
572 description=dict(),
573 key=dict(type='int', no_log=True),
574 local_address=dict(),
575 remote_address=dict(),
576 secondary_address=dict(),
577 mtu=dict(type='int'),
578 use_pmtu=dict(type='bool'),
579 tos=dict(),
580 auto_last_hop=dict(
581 choices=['default', 'enabled', 'disabled']
582 ),
583 traffic_group=dict(),
584 mode=dict(
585 choices=['bidirectional', 'inbound', 'outbound']
586 ),
587 transparent=dict(type='bool'),
588 state=dict(
589 default='present',
590 choices=['present', 'absent']
591 ),
592 partition=dict(
593 default='Common',
594 fallback=(env_fallback, ['F5_PARTITION'])
595 )
596 )
597 self.argument_spec = {}
598 self.argument_spec.update(f5_argument_spec)
599 self.argument_spec.update(argument_spec)
600
601
602 def main():
603 spec = ArgumentSpec()
604
605 module = AnsibleModule(
606 argument_spec=spec.argument_spec,
607 supports_check_mode=spec.supports_check_mode,
608 )
609
610 try:
611 mm = ModuleManager(module=module)
612 results = mm.exec_module()
613 module.exit_json(**results)
614 except F5ModuleError as ex:
615 module.fail_json(msg=str(ex))
616
617
618 if __name__ == '__main__':
619 main()