Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_profile_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_profile_ftp
13 short_description: Manages FTP profiles
14 description:
15 - Manages FTP profiles on the BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the profile.
21 type: str
22 required: True
23 allow_ftps:
24 description:
25 - Allows explicit FTPS negotiation.
26 type: bool
27 description:
28 description:
29 - Description of the profile.
30 type: str
31 parent:
32 description:
33 - Specifies the profile from which this profile inherits settings.
34 - When creating a new profile, if this parameter is not specified, the default
35 is the system-supplied C(ftp) profile.
36 type: str
37 inherit_parent_profile:
38 description:
39 - Enables the FTP data channel to inherit the TCP profile used by the control channel.
40 - "When C(false), the data channel uses FastL4 (BigProto) only."
41 type: bool
42 log_profile:
43 description:
44 - Configures the ALG log profile that controls logging.
45 type: str
46 log_publisher:
47 description:
48 - Configures the log publisher that handles events logging for this profile.
49 type: str
50 translate_extended:
51 description:
52 - Translates RFC 2428 extended requests C(EPSV) and C(EPRT) to C(PASV) and C(PORT)
53 when communicating with IPv4 servers.
54 - This option can only be used if the system is licensed for the BIG-IP Application Security Manager (ASM).
55 type: bool
56 port:
57 description:
58 - Specifies a service for the data channel port used for this FTP profile.
59 - Valid range of values is between C(0) and C(65535) inclusive.
60 type: int
61 security:
62 description:
63 - Enables secure FTP traffic for the BIG-IP Application Security Manager.
64 - This option can only be used if the system is licensed for the BIG-IP ASM.
65 type: bool
66 state:
67 description:
68 - When C(state) is C(present), ensures the ftp profile exists.
69 - When C(state) is C(absent), ensures the ftp profile is removed.
70 type: str
71 choices:
72 - present
73 - absent
74 default: present
75 partition:
76 description:
77 - Device partition to manage resources on.
78 type: str
79 default: Common
80 extends_documentation_fragment: f5networks.f5_modules.f5
81 author:
82 - Wojciech Wypior (@wojtek0806)
83 '''
84
85 EXAMPLES = r'''
86 - name: Create an ftp profile
87 bigip_profile_ftp:
88 name: foo
89 parent: /Common/barfoo
90 port: 2221
91 allow_ftps: true
92 provider:
93 password: secret
94 server: lb.mydomain.com
95 user: admin
96 delegate_to: localhost
97
98 - name: Modify an ftp profile
99 bigip_profile_ftp:
100 name: foo
101 log_profile: /Common/alg_log
102 log_publisher: /Common/foo_publisher
103 security: true
104 description: my description
105 provider:
106 password: secret
107 server: lb.mydomain.com
108 user: admin
109 delegate_to: localhost
110
111 - name: Remove an ftp profile
112 bigip_profile_ftp:
113 name: foo
114 state: absent
115 provider:
116 password: secret
117 server: lb.mydomain.com
118 user: admin
119 delegate_to: localhost
120 '''
121
122 RETURN = r'''
123 allow_ftps:
124 description: Allow explicit FTPS negotiation.
125 returned: changed
126 type: bool
127 sample: true
128 description:
129 description: Description of the profile.
130 returned: changed
131 type: str
132 sample: Foo is bar
133 parent:
134 description: Specifies the profile from which this profile inherits settings.
135 returned: changed
136 type: str
137 sample: /Common/ftp
138 inherit_parent_profile:
139 description: Enables the FTP data channel to inherit the TCP profile used by the control channel.
140 returned: changed
141 type: bool
142 sample: false
143 log_profile:
144 description: The ALG log profile that controls logging.
145 returned: changed
146 type: str
147 sample: /Common/foo_log_profile
148 log_publisher:
149 description: The name of the log publisher that handles events logging for this profile.
150 returned: changed
151 type: list
152 sample: /Common/publisher_1
153 translate_extended:
154 description: Translates RFC 2428 extended requests when communicating with IPv4 servers.
155 returned: changed
156 type: bool
157 sample: true
158 port:
159 description: Specifies a service for the data channel port used for this FTP profile.
160 returned: changed
161 type: int
162 sample: 20
163 security:
164 description: Enables secure FTP traffic for the BIG-IP Application Security Manager.
165 returned: changed
166 type: bool
167 sample: false
168 '''
169 from datetime import datetime
170
171 from ansible.module_utils.basic import (
172 AnsibleModule, env_fallback
173 )
174
175 from ..module_utils.bigip import F5RestClient
176 from ..module_utils.common import (
177 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
178 )
179 from ..module_utils.icontrol import tmos_version
180 from ..module_utils.teem import send_teem
181
182
183 class Parameters(AnsibleF5Parameters):
184 api_map = {
185 'allowFtps': 'allow_ftps',
186 'defaultsFrom': 'parent',
187 'inheritParentProfile': 'inherit_parent_profile',
188 'logProfile': 'log_profile',
189 'logPublisher': 'log_publisher',
190 'translateExtended': 'translate_extended',
191 }
192
193 api_attributes = [
194 'allowFtps',
195 'description',
196 'inheritParentProfile',
197 'logProfile',
198 'logPublisher',
199 'port',
200 'security',
201 'translateExtended',
202 ]
203
204 returnables = [
205 'allow_ftps',
206 'description',
207 'inherit_parent_profile',
208 'log_profile',
209 'log_publisher',
210 'parent',
211 'port',
212 'security',
213 'translate_extended',
214 ]
215
216 updatables = [
217 'allow_ftps',
218 'description',
219 'inherit_parent_profile',
220 'log_profile',
221 'log_publisher',
222 'parent',
223 'port',
224 'security',
225 'translate_extended',
226 ]
227
228
229 class ApiParameters(Parameters):
230 pass
231
232
233 class ModuleParameters(Parameters):
234 @property
235 def allow_ftps(self):
236 result = flatten_boolean(self._values['allow_ftps'])
237 if result is None:
238 return None
239 if result == 'yes':
240 return 'enabled'
241 return 'disabled'
242
243 @property
244 def inherit_parent_profile(self):
245 result = flatten_boolean(self._values['inherit_parent_profile'])
246 if result is None:
247 return None
248 if result == 'yes':
249 return 'enabled'
250 return 'disabled'
251
252 @property
253 def log_profile(self):
254 if self._values['log_profile'] is None:
255 return None
256 if self._values['log_profile'] in ['', 'none']:
257 return ''
258 result = fq_name(self.partition, self._values['log_profile'])
259 return result
260
261 @property
262 def log_publisher(self):
263 if self._values['log_publisher'] is None:
264 return None
265 if self._values['log_publisher'] in ['', 'none']:
266 return ''
267 result = fq_name(self.partition, self._values['log_publisher'])
268 return result
269
270 @property
271 def parent(self):
272 if self._values['parent'] is None:
273 return None
274 result = fq_name(self.partition, self._values['parent'])
275 return result
276
277 @property
278 def port(self):
279 if self._values['port'] is None:
280 return None
281 if 0 <= self._values['port'] <= 65535:
282 return self._values['port']
283 raise F5ModuleError(
284 "Valid 'port' must be in range 0 - 65535."
285 )
286
287 @property
288 def security(self):
289 result = flatten_boolean(self._values['security'])
290 if result is None:
291 return None
292 if result == 'yes':
293 return 'enabled'
294 return 'disabled'
295
296 @property
297 def translate_extended(self):
298 result = flatten_boolean(self._values['translate_extended'])
299 if result is None:
300 return None
301 if result == 'yes':
302 return 'enabled'
303 return 'disabled'
304
305
306 class Changes(Parameters):
307 def to_return(self):
308 result = {}
309 try:
310 for returnable in self.returnables:
311 result[returnable] = getattr(self, returnable)
312 result = self._filter_params(result)
313 except Exception:
314 pass
315 return result
316
317
318 class UsableChanges(Changes):
319 pass
320
321
322 class ReportableChanges(Changes):
323
324 @property
325 def allow_ftps(self):
326 result = flatten_boolean(self._values['allow_ftps'])
327 return result
328
329 @property
330 def inherit_parent_profile(self):
331 result = flatten_boolean(self._values['inherit_parent_profile'])
332 return result
333
334 @property
335 def security(self):
336 result = flatten_boolean(self._values['security'])
337 return result
338
339 @property
340 def translate_extended(self):
341 result = flatten_boolean(self._values['translate_extended'])
342 return result
343
344
345 class Difference(object):
346 def __init__(self, want, have=None):
347 self.want = want
348 self.have = have
349
350 def compare(self, param):
351 try:
352 result = getattr(self, param)
353 return result
354 except AttributeError:
355 return self.__default(param)
356
357 def __default(self, param):
358 attr1 = getattr(self.want, param)
359 try:
360 attr2 = getattr(self.have, param)
361 if attr1 != attr2:
362 return attr1
363 except AttributeError:
364 return attr1
365
366 @property
367 def log_profile(self):
368 if self.want.log_profile is None:
369 return None
370 if self.want.log_profile == '' and self.have.log_profile in [None, 'none']:
371 return None
372 if self.want.log_profile == '':
373 if self.have.log_publisher not in [None, 'none'] and self.want.log_publisher is None:
374 raise F5ModuleError(
375 "The log_profile cannot be removed if log_publisher is defined on device."
376 )
377 if self.want.log_profile != '':
378 if self.want.log_publisher is None and self.have.log_publisher in [None, 'none']:
379 raise F5ModuleError(
380 "The log_profile cannot be specified without an existing valid log_publisher."
381 )
382 if self.want.log_profile != self.have.log_profile:
383 return self.want.log_profile
384
385 @property
386 def log_publisher(self):
387 if self.want.log_publisher is None:
388 return None
389 if self.want.log_publisher == '' and self.have.log_publisher in [None, 'none']:
390 return None
391 if self.want.log_publisher == '':
392 if self.want.log_profile is None and self.have.log_profile not in [None, 'none']:
393 raise F5ModuleError(
394 "The log_publisher cannot be removed if log_profile is defined on device."
395 )
396 if self.want.log_publisher != self.have.log_publisher:
397 return self.want.log_publisher
398
399 @property
400 def description(self):
401 if self.want.description is None:
402 return None
403 if self.have.description in [None, 'none'] and self.want.description == '':
404 return None
405 if self.want.description != self.have.description:
406 return self.want.description
407
408
409 class ModuleManager(object):
410 def __init__(self, *args, **kwargs):
411 self.module = kwargs.get('module', None)
412 self.client = F5RestClient(**self.module.params)
413 self.want = ModuleParameters(params=self.module.params)
414 self.have = ApiParameters()
415 self.changes = UsableChanges()
416
417 def _set_changed_options(self):
418 changed = {}
419 for key in Parameters.returnables:
420 if getattr(self.want, key) is not None:
421 changed[key] = getattr(self.want, key)
422 if changed:
423 self.changes = UsableChanges(params=changed)
424
425 def _update_changed_options(self):
426 diff = Difference(self.want, self.have)
427 updatables = Parameters.updatables
428 changed = dict()
429 for k in updatables:
430 change = diff.compare(k)
431 if change is None:
432 continue
433 else:
434 if isinstance(change, dict):
435 changed.update(change)
436 else:
437 changed[k] = change
438 if changed:
439 self.changes = UsableChanges(params=changed)
440 return True
441 return False
442
443 def _announce_deprecations(self, result):
444 warnings = result.pop('__warnings', [])
445 for warning in warnings:
446 self.client.module.deprecate(
447 msg=warning['msg'],
448 version=warning['version']
449 )
450
451 def exec_module(self):
452 start = datetime.now().isoformat()
453 version = tmos_version(self.client)
454 changed = False
455 result = dict()
456 state = self.want.state
457
458 if state == "present":
459 changed = self.present()
460 elif state == "absent":
461 changed = self.absent()
462
463 reportable = ReportableChanges(params=self.changes.to_return())
464 changes = reportable.to_return()
465 result.update(**changes)
466 result.update(dict(changed=changed))
467 self._announce_deprecations(result)
468 send_teem(start, self.client, self.module, version)
469 return result
470
471 def present(self):
472 if self.exists():
473 return self.update()
474 else:
475 return self.create()
476
477 def absent(self):
478 if self.exists():
479 return self.remove()
480 return False
481
482 def should_update(self):
483 result = self._update_changed_options()
484 if result:
485 return True
486 return False
487
488 def update(self):
489 self.have = self.read_current_from_device()
490 if not self.should_update():
491 return False
492 if self.module.check_mode:
493 return True
494 self.update_on_device()
495 return True
496
497 def remove(self):
498 if self.module.check_mode:
499 return True
500 self.remove_from_device()
501 if self.exists():
502 raise F5ModuleError("Failed to delete the resource.")
503 return True
504
505 def create(self):
506 self._set_changed_options()
507 if self.module.check_mode:
508 return True
509 self.create_on_device()
510 return True
511
512 def exists(self):
513 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/ftp/{2}".format(
514 self.client.provider['server'],
515 self.client.provider['server_port'],
516 transform_name(self.want.partition, self.want.name)
517 )
518 resp = self.client.api.get(uri)
519 try:
520 response = resp.json()
521 except ValueError as ex:
522 raise F5ModuleError(str(ex))
523
524 if resp.status == 404 or 'code' in response and response['code'] == 404:
525 return False
526 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
527 return True
528
529 errors = [401, 403, 409, 500, 501, 502, 503, 504]
530
531 if resp.status in errors or 'code' in response and response['code'] in errors:
532 if 'message' in response:
533 raise F5ModuleError(response['message'])
534 else:
535 raise F5ModuleError(resp.content)
536
537 def create_on_device(self):
538 params = self.changes.api_params()
539 params['name'] = self.want.name
540 params['partition'] = self.want.partition
541 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/ftp/".format(
542 self.client.provider['server'],
543 self.client.provider['server_port'],
544 )
545 resp = self.client.api.post(uri, json=params)
546 try:
547 response = resp.json()
548 except ValueError as ex:
549 raise F5ModuleError(str(ex))
550
551 if 'code' in response and response['code'] in [400, 409]:
552 if 'message' in response:
553 raise F5ModuleError(response['message'])
554 else:
555 raise F5ModuleError(resp.content)
556 return True
557
558 def update_on_device(self):
559 params = self.changes.api_params()
560 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/ftp/{2}".format(
561 self.client.provider['server'],
562 self.client.provider['server_port'],
563 transform_name(self.want.partition, self.want.name)
564 )
565 resp = self.client.api.patch(uri, json=params)
566 try:
567 response = resp.json()
568 except ValueError as ex:
569 raise F5ModuleError(str(ex))
570
571 if 'code' in response and response['code'] == 400:
572 if 'message' in response:
573 raise F5ModuleError(response['message'])
574 else:
575 raise F5ModuleError(resp.content)
576
577 def remove_from_device(self):
578 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/ftp/{2}".format(
579 self.client.provider['server'],
580 self.client.provider['server_port'],
581 transform_name(self.want.partition, self.want.name)
582 )
583 response = self.client.api.delete(uri)
584 if response.status == 200:
585 return True
586 raise F5ModuleError(response.content)
587
588 def read_current_from_device(self):
589 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/ftp/{2}".format(
590 self.client.provider['server'],
591 self.client.provider['server_port'],
592 transform_name(self.want.partition, self.want.name)
593 )
594 resp = self.client.api.get(uri)
595 try:
596 response = resp.json()
597 except ValueError as ex:
598 raise F5ModuleError(str(ex))
599
600 if 'code' in response and response['code'] == 400:
601 if 'message' in response:
602 raise F5ModuleError(response['message'])
603 else:
604 raise F5ModuleError(resp.content)
605 return ApiParameters(params=response)
606
607
608 class ArgumentSpec(object):
609 def __init__(self):
610 self.supports_check_mode = True
611 argument_spec = dict(
612 name=dict(required=True),
613 allow_ftps=dict(type='bool'),
614 description=dict(),
615 parent=dict(),
616 inherit_parent_profile=dict(type='bool'),
617 log_profile=dict(),
618 log_publisher=dict(),
619 translate_extended=dict(type='bool'),
620 port=dict(type='int'),
621 security=dict(type='bool'),
622 state=dict(
623 default='present',
624 choices=['present', 'absent']
625 ),
626 partition=dict(
627 default='Common',
628 fallback=(env_fallback, ['F5_PARTITION'])
629 )
630 )
631 self.argument_spec = {}
632 self.argument_spec.update(f5_argument_spec)
633 self.argument_spec.update(argument_spec)
634
635
636 def main():
637 spec = ArgumentSpec()
638
639 module = AnsibleModule(
640 argument_spec=spec.argument_spec,
641 supports_check_mode=spec.supports_check_mode,
642 )
643
644 try:
645 mm = ModuleManager(module=module)
646 results = mm.exec_module()
647 module.exit_json(**results)
648 except F5ModuleError as ex:
649 module.fail_json(msg=str(ex))
650
651
652 if __name__ == '__main__':
653 main()