Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2019, 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_monitor_ftp
13 short_description: Manage FTP monitors on a BIG-IP
14 description:
15 - Manage FTP monitors on a BIG-IP device.
16 version_added: "1.1.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the monitor.
21 type: str
22 required: True
23 app_service:
24 description:
25 - The iApp service to be associated with this profile. When no service is
26 specified, the default is None.
27 type: str
28 parent:
29 description:
30 - The parent template of this monitor template. Once this value has
31 been set, it cannot be changed.
32 - When creating a new monitor, if this parameter is not specified, the default
33 is the system-supplied C(ftp) monitor.
34 type: str
35 description:
36 description:
37 - The description of the monitor.
38 type: str
39 debug:
40 description:
41 - Specifies whether the monitor sends error messages and additional information to a log file created and
42 labeled specifically for this monitor.
43 - "When C(true) the system redirects error messages and additional information to the
44 C(/var/log/monitors/<monitor_name>-<node_name>-<port>.log) file."
45 type: bool
46 mode:
47 description:
48 - Specifies the data transfer process (DTP) mode.
49 - When C(passive), the monitor sends a data transfer request to the FTP server. When the FTP server receives the
50 request, the FTP server initiates and establishes the data connection.
51 - When C(port), the monitor initiates and establishes the data connection with the FTP server.
52 type: str
53 choices:
54 - passive
55 - port
56 filename:
57 description:
58 - Specifies the full path and file name of the file the system attempts to download. The health check
59 is successful if the system can download the file.
60 type: str
61 target_username:
62 description:
63 - Specifies the user name, if the monitored target requires authentication.
64 type: str
65 target_password:
66 description:
67 - Specifies the password, if the monitored target requires authentication.
68 type: str
69 ip:
70 description:
71 - IP address part of the IP/port definition. If this parameter is not
72 provided when creating a new monitor, the default value is '*'.
73 type: str
74 port:
75 description:
76 - Port address part of the IP/port definition. If this parameter is not
77 provided when creating a new monitor, the default value is '*'.
78 If specifying an IP address, you must use a value between 1 and 65535.
79 type: str
80 interval:
81 description:
82 - The interval specifying how frequently the monitor instance of this
83 template will run.
84 - This value B(must) be less than the C(timeout) value.
85 - When creating a new monitor, if this parameter is not provided, the
86 default C(5) will be used.
87 type: int
88 up_interval:
89 description:
90 - Specifies the interval at which the system performs the health check
91 when a resource is up.
92 - When C(0), specifies the system uses the interval specified in
93 C(interval) to check the health of the resource.
94 - When any other number, enables you to specify a different interval to
95 use when checking the health of a resource that is up.
96 - When creating a new monitor, if this parameter is not provided, the
97 default C(0) will be used.
98 type: int
99 timeout:
100 description:
101 - The number of seconds in which the node or service must respond to
102 the monitor request.
103 - If the target responds within the set time period, it is considered up.
104 - If the target does not respond within the set time period, it is considered down.
105 - You can change this to any number, however, it should be 3 times the
106 interval number of seconds plus 1 second.
107 - If this parameter is not provided when creating a new monitor, then the default
108 value will be C(31).
109 type: int
110 manual_resume:
111 description:
112 - Specifies whether the system automatically changes the status of a resource
113 to B(enabled) at the next successful monitor check.
114 - If you set this option to C(true), you must manually re-enable the resource
115 before the system can use it for load balancing connections.
116 - When creating a new monitor, if this parameter is not specified, the default
117 value is C(false).
118 - When C(true), specifies you must manually re-enable the resource after an
119 unsuccessful monitor check.
120 - When C(false)), specifies the system automatically changes the status of a
121 resource to B(enabled) at the next successful monitor check.
122 type: bool
123 time_until_up:
124 description:
125 - Specifies the amount of time in seconds after the first successful
126 response before a node will be marked up.
127 - A value of C(0) will cause a node to be marked up immediately after a valid
128 response is received from the node.
129 - If this parameter is not provided when creating a new monitor, then the default
130 value will be C(0).
131 type: int
132 update_password:
133 description:
134 - C(always) will update passwords if the C(target_password) is specified.
135 - C(on_create) will only set the password for newly created monitors.
136 type: str
137 choices:
138 - always
139 - on_create
140 default: always
141 partition:
142 description:
143 - Device partition to manage resources on.
144 type: str
145 default: Common
146 state:
147 description:
148 - When C(present), ensures the monitor exists.
149 - When C(absent), ensures the monitor is removed.
150 type: str
151 choices:
152 - present
153 - absent
154 default: present
155 extends_documentation_fragment: f5networks.f5_modules.f5
156 author:
157 - Wojciech Wypior (@wojtek0806)
158 '''
159
160 EXAMPLES = r'''
161 - name: Create FTP Monitor
162 bigip_monitor_ftp:
163 state: present
164 ip: 10.10.10.10
165 name: my_ft_monitor
166 provider:
167 server: lb.mydomain.com
168 user: admin
169 password: secret
170 delegate_to: localhost
171
172 - name: Remove FTP Monitor
173 bigip_monitor_ftp:
174 state: absent
175 name: my_ftp_monitor
176 provider:
177 server: lb.mydomain.com
178 user: admin
179 password: secret
180 delegate_to: localhost
181
182 - name: Include a username and password in the FTP monitor
183 bigip_monitor_ftp:
184 state: absent
185 name: my_ftp_monitor
186 target_username: monitor_user
187 target_password: monitor_pass
188 provider:
189 server: lb.mydomain.com
190 user: admin
191 password: secret
192 delegate_to: localhost
193 '''
194
195 RETURN = r'''
196 app_service:
197 description: The iApp service associated with this monitor.
198 returned: changed
199 type: str
200 sample: /Common/good_service.app/good_service
201 parent:
202 description: The parent monitor.
203 returned: changed
204 type: str
205 sample: /Common/foo_ftp
206 description:
207 description: The description of the monitor.
208 returned: changed
209 type: str
210 sample: Important Monitor
211 debug:
212 description:
213 - Whether the monitor sends error messages and additional information to a log file created and
214 labeled specifically for this monitor.
215 returned: changed
216 type: bool
217 sample: false
218 mode:
219 description: Specifies the data transfer process (DTP) mode.
220 returned: changed
221 type: str
222 sample: passive
223 filename:
224 description: Specifies the full path and file name of the file the system attempts to download.
225 returned: changed
226 type: str
227 sample: /ftp/var/health.txt
228 ip:
229 description: The new IP of IP/port definition.
230 returned: changed
231 type: str
232 sample: 10.12.13.14
233 port:
234 description:
235 - Alias port or service for the monitor to check, on behalf of the pools or pool
236 members with which the monitor is associated.
237 returned: changed
238 type: str
239 sample: 80
240 interval:
241 description: The new interval at which to run the monitor check.
242 returned: changed
243 type: int
244 sample: 2
245 up_interval:
246 description: Interval for the system to use to perform the health check when a resource is up.
247 returned: changed
248 type: int
249 sample: 0
250 timeout:
251 description: The new timeout in which the remote system must respond to the monitor.
252 returned: changed
253 type: int
254 sample: 10
255 manual_resume:
256 description:
257 - Specifies whether the system automatically changes the status of a
258 resource to up at the next successful monitor check.
259 returned: changed
260 type: bool
261 sample: true
262 time_until_up:
263 description: The new time in which to mark a system as up after first successful response.
264 returned: changed
265 type: int
266 sample: 2
267 '''
268 from datetime import datetime
269
270 from ansible.module_utils.basic import (
271 AnsibleModule, env_fallback
272 )
273
274 from ..module_utils.bigip import F5RestClient
275 from ..module_utils.common import (
276 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
277 )
278 from ..module_utils.compare import cmp_str_with_none
279 from ..module_utils.ipaddress import is_valid_ip
280 from ..module_utils.icontrol import tmos_version
281 from ..module_utils.teem import send_teem
282
283
284 class Parameters(AnsibleF5Parameters):
285 api_map = {
286 'appService': 'app_service',
287 'defaultsFrom': 'parent',
288 'timeUntilUp': 'time_until_up',
289 'manualResume': 'manual_resume',
290 'upInterval': 'up_interval',
291 'username': 'target_username',
292 'password': 'target_password',
293 }
294
295 api_attributes = [
296 'defaultsFrom',
297 'description',
298 'debug',
299 'mode',
300 'filename',
301 'username',
302 'password',
303 'destination',
304 'interval',
305 'upInterval',
306 'timeout',
307 'manualResume',
308 'timeUntilUp',
309 ]
310
311 returnables = [
312 'app_service',
313 'parent',
314 'description',
315 'debug',
316 'mode',
317 'filename',
318 'ip',
319 'port',
320 'interval',
321 'up_interval',
322 'timeout',
323 'manual_resume',
324 'time_until_up',
325 'target_username',
326 'destination',
327 ]
328
329 updatables = [
330 'app_service',
331 'description',
332 'debug',
333 'mode',
334 'filename',
335 'target_username',
336 'target_password',
337 'ip',
338 'port',
339 'interval',
340 'up_interval',
341 'timeout',
342 'manual_resume',
343 'time_until_up',
344 'destination',
345 ]
346
347
348 class ApiParameters(Parameters):
349 @property
350 def ip(self):
351 des = self._values['destination']
352 ip, d, port = des.rpartition('.')
353 if not is_valid_ip(ip) and ip != '*':
354 ip, d, port = des.rpartition(':')
355 return ip
356
357 @property
358 def port(self):
359 des = self._values['destination']
360 ip, d, port = des.rpartition('.')
361 if not is_valid_ip(ip) and ip != '*':
362 ip, d, port = des.rpartition(':')
363 return int(port) if port.isnumeric() else port
364
365 @property
366 def description(self):
367 if self._values['description'] in [None, 'none']:
368 return None
369 return self._values['description']
370
371
372 class ModuleParameters(Parameters):
373 @property
374 def description(self):
375 if self._values['description'] is None:
376 return None
377 elif self._values['description'] in ['none', '']:
378 return ''
379 return self._values['description']
380
381 @property
382 def parent(self):
383 if self._values['parent'] is None:
384 return None
385 result = fq_name(self.partition, self._values['parent'])
386 return result
387
388 @property
389 def interval(self):
390 if self._values['interval'] is None:
391 return None
392 if 1 > self._values['interval'] > 86400:
393 raise F5ModuleError(
394 "Interval value must be between 1 and 86400."
395 )
396 return self._values['interval']
397
398 @property
399 def timeout(self):
400 if self._values['timeout'] is None:
401 return None
402 if self._values['timeout'] is None:
403 return None
404 if 1 > self._values['timeout'] > 86400:
405 raise F5ModuleError(
406 "Timeout value must be between 1 and 86400."
407 )
408 return self._values['timeout']
409
410 @property
411 def ip(self):
412 if self._values['ip'] is None:
413 return None
414 if self._values['ip'] in ['*', '0.0.0.0']:
415 return '*'
416 elif is_valid_ip(self._values['ip']) or is_valid_ip(self._values['ip'].split("%")[0]):
417 return self._values['ip']
418 else:
419 raise F5ModuleError(
420 "The provided 'ip' parameter is not an IP address."
421 )
422
423 @property
424 def port(self):
425 if self._values['port'] is None:
426 return None
427 elif self._values['port'] == '*':
428 return '*'
429 return int(self._values['port'])
430
431 @property
432 def destination(self):
433 if self.ip is None and self.port is None:
434 return None
435 destination = '{0}:{1}'.format(self.ip, self.port)
436 return destination
437
438 @destination.setter
439 def destination(self, value):
440 ip, port = value.split(':')
441 self._values['ip'] = ip
442 self._values['port'] = port
443
444 @property
445 def time_until_up(self):
446 if self._values['time_until_up'] is None:
447 return None
448 if self._values['time_until_up'] is None:
449 return None
450 if 0 > self._values['time_until_up'] > 86400:
451 raise F5ModuleError(
452 "Time_until_up value must be between 0 and 86400."
453 )
454 return self._values['time_until_up']
455
456 @property
457 def manual_resume(self):
458 result = flatten_boolean(self._values['manual_resume'])
459 if result == 'yes':
460 return 'enabled'
461 if result == 'no':
462 return 'disabled'
463
464 @property
465 def debug(self):
466 result = flatten_boolean(self._values['debug'])
467 if result == 'yes':
468 return 'enabled'
469 if result == 'no':
470 return 'disabled'
471
472
473 class Changes(Parameters):
474 def to_return(self):
475 result = {}
476 try:
477 for returnable in self.returnables:
478 result[returnable] = getattr(self, returnable)
479 result = self._filter_params(result)
480 except Exception:
481 raise
482 return result
483
484
485 class UsableChanges(Changes):
486 pass
487
488
489 class ReportableChanges(Changes):
490 @property
491 def debug(self):
492 return flatten_boolean(self._values['debug'])
493
494 @property
495 def manual_resume(self):
496 return flatten_boolean(self._values['manual_resume'])
497
498
499 class Difference(object):
500 def __init__(self, want, have=None):
501 self.want = want
502 self.have = have
503
504 def compare(self, param):
505 try:
506 result = getattr(self, param)
507 return result
508 except AttributeError:
509 return self.__default(param)
510
511 def __default(self, param):
512 attr1 = getattr(self.want, param)
513 try:
514 attr2 = getattr(self.have, param)
515 if attr1 != attr2:
516 return attr1
517 except AttributeError:
518 return attr1
519
520 @property
521 def destination(self):
522 if self.want.ip is None and self.want.port is None:
523 return None
524 if self.want.port is None:
525 self.want.update({'port': self.have.port})
526 if self.want.ip is None:
527 self.want.update({'ip': self.have.ip})
528
529 if self.want.port in [None, '*'] and self.want.ip != '*':
530 raise F5ModuleError(
531 "Specifying an IP address requires that a port number be specified."
532 )
533 if self.want.destination != self.have.destination:
534 return self.want.destination
535
536 @property
537 def target_password(self):
538 if self.want.target_password != self.have.target_password:
539 if self.want.update_password == 'always':
540 result = self.want.target_password
541 return result
542
543 @property
544 def description(self):
545 return cmp_str_with_none(self.want.description, self.have.description)
546
547 @property
548 def interval(self):
549 if self.want.timeout is not None and self.want.interval is not None:
550 if self.want.interval >= self.want.timeout:
551 raise F5ModuleError(
552 "Parameter 'interval' must be less than 'timeout'."
553 )
554 elif self.want.timeout is not None:
555 if self.have.interval >= self.want.timeout:
556 raise F5ModuleError(
557 "Parameter 'interval' must be less than 'timeout'."
558 )
559 elif self.want.interval is not None:
560 if self.want.interval >= self.have.timeout:
561 raise F5ModuleError(
562 "Parameter 'interval' must be less than 'timeout'."
563 )
564 if self.want.interval != self.have.interval:
565 return self.want.interval
566
567
568 class ModuleManager(object):
569 def __init__(self, *args, **kwargs):
570 self.module = kwargs.get('module', None)
571 self.client = F5RestClient(**self.module.params)
572 self.want = ModuleParameters(params=self.module.params)
573 self.have = ApiParameters()
574 self.changes = UsableChanges()
575
576 def _set_changed_options(self):
577 changed = {}
578 for key in Parameters.returnables:
579 if getattr(self.want, key) is not None:
580 changed[key] = getattr(self.want, key)
581 if changed:
582 self.changes = UsableChanges(params=changed)
583
584 def _update_changed_options(self):
585 diff = Difference(self.want, self.have)
586 updatables = Parameters.updatables
587 changed = dict()
588 for k in updatables:
589 change = diff.compare(k)
590 if change is None:
591 continue
592 else:
593 if isinstance(change, dict):
594 changed.update(change)
595 else:
596 changed[k] = change
597 if changed:
598 self.changes = UsableChanges(params=changed)
599 return True
600 return False
601
602 def _announce_deprecations(self, result):
603 warnings = result.pop('__warnings', [])
604 for warning in warnings:
605 self.client.module.deprecate(
606 msg=warning['msg'],
607 version=warning['version']
608 )
609
610 def exec_module(self):
611 start = datetime.now().isoformat()
612 version = tmos_version(self.client)
613 changed = False
614 result = dict()
615 state = self.want.state
616
617 if state == "present":
618 changed = self.present()
619 elif state == "absent":
620 changed = self.absent()
621
622 reportable = ReportableChanges(params=self.changes.to_return())
623 changes = reportable.to_return()
624 result.update(**changes)
625 result.update(dict(changed=changed))
626 self._announce_deprecations(result)
627 send_teem(start, self.client, self.module, version)
628 return result
629
630 def present(self):
631 if self.exists():
632 return self.update()
633 else:
634 return self.create()
635
636 def absent(self):
637 if self.exists():
638 return self.remove()
639 return False
640
641 def should_update(self):
642 result = self._update_changed_options()
643 if result:
644 return True
645 return False
646
647 def update(self):
648 self.have = self.read_current_from_device()
649 if not self.should_update():
650 return False
651 if self.module.check_mode:
652 return True
653 self.update_on_device()
654 return True
655
656 def remove(self):
657 if self.module.check_mode:
658 return True
659 self.remove_from_device()
660 if self.exists():
661 raise F5ModuleError("Failed to delete the resource.")
662 return True
663
664 def create(self):
665 self._set_changed_options()
666 if self.module.check_mode:
667 return True
668 self.create_on_device()
669 return True
670
671 def exists(self):
672 uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/ftp/{2}".format(
673 self.client.provider['server'],
674 self.client.provider['server_port'],
675 transform_name(self.want.partition, self.want.name)
676 )
677 resp = self.client.api.get(uri)
678 try:
679 response = resp.json()
680 except ValueError as ex:
681 raise F5ModuleError(str(ex))
682
683 if resp.status == 404 or 'code' in response and response['code'] == 404:
684 return False
685 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
686 return True
687
688 errors = [401, 403, 409, 500, 501, 502, 503, 504]
689
690 if resp.status in errors or 'code' in response and response['code'] in errors:
691 if 'message' in response:
692 raise F5ModuleError(response['message'])
693 else:
694 raise F5ModuleError(resp.content)
695
696 def create_on_device(self):
697 params = self.changes.api_params()
698 params['name'] = self.want.name
699 params['partition'] = self.want.partition
700 uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/ftp/".format(
701 self.client.provider['server'],
702 self.client.provider['server_port'],
703 )
704 resp = self.client.api.post(uri, json=params)
705 try:
706 response = resp.json()
707 except ValueError as ex:
708 raise F5ModuleError(str(ex))
709
710 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
711 return True
712 raise F5ModuleError(resp.content)
713
714 def update_on_device(self):
715 params = self.changes.api_params()
716 uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/ftp/{2}".format(
717 self.client.provider['server'],
718 self.client.provider['server_port'],
719 transform_name(self.want.partition, self.want.name)
720 )
721 resp = self.client.api.patch(uri, json=params)
722 try:
723 response = resp.json()
724 except ValueError as ex:
725 raise F5ModuleError(str(ex))
726
727 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
728 return True
729 raise F5ModuleError(resp.content)
730
731 def remove_from_device(self):
732 uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/ftp/{2}".format(
733 self.client.provider['server'],
734 self.client.provider['server_port'],
735 transform_name(self.want.partition, self.want.name)
736 )
737 response = self.client.api.delete(uri)
738 if response.status == 200:
739 return True
740 raise F5ModuleError(response.content)
741
742 def read_current_from_device(self):
743 uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/ftp/{2}".format(
744 self.client.provider['server'],
745 self.client.provider['server_port'],
746 transform_name(self.want.partition, self.want.name)
747 )
748 resp = self.client.api.get(uri)
749 try:
750 response = resp.json()
751 except ValueError as ex:
752 raise F5ModuleError(str(ex))
753
754 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
755 return ApiParameters(params=response)
756 raise F5ModuleError(resp.content)
757
758
759 class ArgumentSpec(object):
760 def __init__(self):
761 self.supports_check_mode = True
762 argument_spec = dict(
763 name=dict(required=True),
764 app_service=dict(),
765 parent=dict(),
766 description=dict(),
767 debug=dict(type='bool'),
768 mode=dict(
769 choices=['passive', 'port']
770 ),
771 filename=dict(),
772 target_username=dict(),
773 target_password=dict(no_log=True),
774 ip=dict(),
775 port=dict(),
776 interval=dict(type='int'),
777 up_interval=dict(type='int'),
778 timeout=dict(type='int'),
779 manual_resume=dict(type='bool'),
780 time_until_up=dict(type='int'),
781 update_password=dict(
782 default='always',
783 choices=['always', 'on_create'],
784 no_log=False
785 ),
786 state=dict(
787 default='present',
788 choices=['present', 'absent']
789 ),
790 partition=dict(
791 default='Common',
792 fallback=(env_fallback, ['F5_PARTITION'])
793 )
794 )
795 self.argument_spec = {}
796 self.argument_spec.update(f5_argument_spec)
797 self.argument_spec.update(argument_spec)
798
799
800 def main():
801 spec = ArgumentSpec()
802
803 module = AnsibleModule(
804 argument_spec=spec.argument_spec,
805 supports_check_mode=spec.supports_check_mode,
806 )
807
808 try:
809 mm = ModuleManager(module=module)
810 results = mm.exec_module()
811 module.exit_json(**results)
812 except F5ModuleError as ex:
813 module.fail_json(msg=str(ex))
814
815
816 if __name__ == '__main__':
817 main()