Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_smtp.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_smtp
13 short_description: Manages SMTP settings on the BIG-IP
14 description:
15 - Allows configuring of the BIG-IP to send mail via an SMTP server by
16 configuring the parameters of an SMTP server.
17 version_added: "1.0.0"
18 options:
19 name:
20 description:
21 - Specifies the name of the SMTP server configuration.
22 type: str
23 required: True
24 partition:
25 description:
26 - Device partition to manage resources on.
27 type: str
28 default: Common
29 smtp_server:
30 description:
31 - SMTP server host name in the format of a fully qualified domain name.
32 - This value is required when creating a new SMTP configuration.
33 type: str
34 smtp_server_port:
35 description:
36 - Specifies the SMTP port number.
37 - When creating a new SMTP configuration, the default is C(25) when
38 C(encryption) is C(none) or C(tls). The default is C(465) when C(ssl) is selected.
39 type: int
40 local_host_name:
41 description:
42 - Hostname used in SMTP headers in the format of a fully qualified
43 domain name. This setting does not refer to the hostname of the BIG-IP system.
44 type: str
45 from_address:
46 description:
47 - Email address from which the email is being sent. This is the "Reply-to"
48 address the recipient sees.
49 type: str
50 encryption:
51 description:
52 - Specifies whether the SMTP server requires an encrypted connection in
53 order to send mail.
54 type: str
55 choices:
56 - none
57 - ssl
58 - tls
59 authentication:
60 description:
61 - Credentials can be set on an SMTP server's configuration even if that
62 authentication is not used (for example, staging configs or emergency changes).
63 This parameter acts as a switch to make the specified C(smtp_server_username)
64 and C(smtp_server_password) parameters active or not.
65 - When C(true), the authentication parameters are active.
66 - When C(false), the authentication parameters are inactive.
67 type: bool
68 smtp_server_username:
69 description:
70 - User name the SMTP server requires when validating a user.
71 type: str
72 smtp_server_password:
73 description:
74 - Password the SMTP server requires when validating a user.
75 type: str
76 state:
77 description:
78 - When C(present), ensures the SMTP configuration exists.
79 - When C(absent), ensures the SMTP configuration does not exist.
80 type: str
81 choices:
82 - present
83 - absent
84 default: present
85 update_password:
86 description:
87 - Passwords are stored encrypted, so the module cannot know if the supplied
88 C(smtp_server_password) is the same or different than the existing password.
89 This parameter controls the updating of the C(smtp_server_password)
90 credential.
91 - When C(always), the system always updates the password.
92 - When C(on_create), the system only sets the password for newly created SMTP server
93 configurations.
94 type: str
95 choices:
96 - always
97 - on_create
98 default: always
99 extends_documentation_fragment: f5networks.f5_modules.f5
100 author:
101 - Tim Rupp (@caphrim007)
102 '''
103
104 EXAMPLES = r'''
105 - name: Create a base SMTP server configuration
106 bigip_smtp:
107 name: my-smtp
108 smtp_server: 1.1.1.1
109 smtp_server_username: mail-admin
110 smtp_server_password: mail-secret
111 local_host_name: smtp.mydomain.com
112 from_address: [email protected]
113 state: present
114 provider:
115 user: admin
116 password: secret
117 server: lb.mydomain.com
118 delegate_to: localhost
119 '''
120
121 RETURN = r'''
122 smtp_server:
123 description: The new C(smtp_server) value of the SMTP configuration.
124 returned: changed
125 type: str
126 sample: mail.mydomain.com
127 smtp_server_port:
128 description: The new C(smtp_server_port) value of the SMTP configuration.
129 returned: changed
130 type: int
131 sample: 25
132 local_host_name:
133 description: The new C(local_host_name) value of the SMTP configuration.
134 returned: changed
135 type: str
136 sample: smtp.mydomain.com
137 from_address:
138 description: The new C(from_address) value of the SMTP configuration.
139 returned: changed
140 type: str
141 sample: [email protected]
142 encryption:
143 description: The new C(encryption) value of the SMTP configuration.
144 returned: changed
145 type: str
146 sample: tls
147 authentication:
148 description: Whether the authentication parameters are active or not.
149 returned: changed
150 type: bool
151 sample: true
152 '''
153 from datetime import datetime
154 from ansible.module_utils.basic import (
155 AnsibleModule, env_fallback
156 )
157
158 from ..module_utils.bigip import F5RestClient
159 from ..module_utils.common import (
160 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, is_valid_hostname
161 )
162 from ..module_utils.ipaddress import is_valid_ip
163 from ..module_utils.icontrol import tmos_version
164 from ..module_utils.teem import send_teem
165
166
167 class Parameters(AnsibleF5Parameters):
168 api_map = {
169 'username': 'smtp_server_username',
170 'passwordEncrypted': 'smtp_server_password',
171 'localHostName': 'local_host_name',
172 'smtpServerHostName': 'smtp_server',
173 'smtpServerPort': 'smtp_server_port',
174 'encryptedConnection': 'encryption',
175 'authenticationEnabled': 'authentication_enabled',
176 'authenticationDisabled': 'authentication_disabled',
177 'fromAddress': 'from_address',
178 }
179
180 api_attributes = [
181 'username',
182 'passwordEncrypted',
183 'localHostName',
184 'smtpServerHostName',
185 'smtpServerPort',
186 'encryptedConnection',
187 'authenticationEnabled',
188 'authenticationDisabled',
189 'fromAddress',
190 ]
191
192 returnables = [
193 'smtp_server_username',
194 'smtp_server_password',
195 'local_host_name',
196 'smtp_server',
197 'smtp_server_port',
198 'encryption',
199 'authentication',
200 'from_address',
201 ]
202
203 updatables = [
204 'smtp_server_username',
205 'smtp_server_password',
206 'local_host_name',
207 'smtp_server',
208 'smtp_server_port',
209 'encryption',
210 'authentication',
211 'from_address',
212 ]
213
214
215 class ApiParameters(Parameters):
216 pass
217
218
219 class ModuleParameters(Parameters):
220 @property
221 def local_host_name(self):
222 if self._values['local_host_name'] is None:
223 return None
224 if is_valid_ip(self._values['local_host_name']):
225 return self._values['local_host_name']
226 elif is_valid_hostname(self._values['local_host_name']):
227 # else fallback to checking reasonably well formatted hostnames
228 return str(self._values['local_host_name'])
229 raise F5ModuleError(
230 "The provided 'local_host_name' value {0} is not a valid IP or hostname".format(
231 str(self._values['local_host_name'])
232 )
233 )
234
235 @property
236 def authentication_enabled(self):
237 if self._values['authentication'] is None:
238 return None
239 if self._values['authentication']:
240 return True
241
242 @property
243 def authentication_disabled(self):
244 if self._values['authentication'] is None:
245 return None
246 if not self._values['authentication']:
247 return True
248
249 @property
250 def smtp_server_port(self):
251 if self._values['smtp_server_port'] is None:
252 return None
253 return int(self._values['smtp_server_port'])
254
255
256 class Changes(Parameters):
257 def to_return(self):
258 result = {}
259 try:
260 for returnable in self.returnables:
261 result[returnable] = getattr(self, returnable)
262 result = self._filter_params(result)
263 except Exception:
264 pass
265 return result
266
267
268 class UsableChanges(Changes):
269 pass
270
271
272 class ReportableChanges(Changes):
273 @property
274 def smtp_server_password(self):
275 return None
276
277 @property
278 def smtp_server_username(self):
279 return None
280
281
282 class Difference(object):
283 def __init__(self, want, have=None):
284 self.want = want
285 self.have = have
286
287 def compare(self, param):
288 try:
289 result = getattr(self, param)
290 return result
291 except AttributeError:
292 return self.__default(param)
293
294 def __default(self, param):
295 attr1 = getattr(self.want, param)
296 try:
297 attr2 = getattr(self.have, param)
298 if attr1 != attr2:
299 return attr1
300 except AttributeError:
301 return attr1
302
303 @property
304 def smtp_server_password(self):
305 if self.want.update_password == 'on_create':
306 return None
307 return self.want.smtp_server_password
308
309 @property
310 def authentication(self):
311 if self.want.authentication_enabled:
312 if self.want.authentication_enabled != self.have.authentication_enabled:
313 return dict(
314 authentication_enabled=self.want.authentication_enabled
315 )
316 if self.want.authentication_disabled:
317 if self.want.authentication_disabled != self.have.authentication_disabled:
318 return dict(
319 authentication_disable=self.want.authentication_disabled
320 )
321
322
323 class ModuleManager(object):
324 def __init__(self, *args, **kwargs):
325 self.module = kwargs.get('module', None)
326 self.client = F5RestClient(**self.module.params)
327 self.want = ModuleParameters(params=self.module.params)
328 self.have = ApiParameters()
329 self.changes = UsableChanges()
330
331 def _set_changed_options(self):
332 changed = {}
333 for key in Parameters.returnables:
334 if getattr(self.want, key) is not None:
335 changed[key] = getattr(self.want, key)
336 if changed:
337 self.changes = UsableChanges(params=changed)
338
339 def _update_changed_options(self):
340 diff = Difference(self.want, self.have)
341 updatables = Parameters.updatables
342 changed = dict()
343 for k in updatables:
344 change = diff.compare(k)
345 if change is None:
346 continue
347 else:
348 if isinstance(change, dict):
349 changed.update(change)
350 else:
351 changed[k] = change
352 if changed:
353 self.changes = UsableChanges(params=changed)
354 return True
355 return False
356
357 def should_update(self):
358 result = self._update_changed_options()
359 if result:
360 return True
361 return False
362
363 def exec_module(self):
364 start = datetime.now().isoformat()
365 version = tmos_version(self.client)
366 changed = False
367 result = dict()
368 state = self.want.state
369
370 if state == "present":
371 changed = self.present()
372 elif state == "absent":
373 changed = self.absent()
374
375 reportable = ReportableChanges(params=self.changes.to_return())
376 changes = reportable.to_return()
377 result.update(**changes)
378 result.update(dict(changed=changed))
379 self._announce_deprecations(result)
380 send_teem(start, self.client, self.module, version)
381 return result
382
383 def _announce_deprecations(self, result):
384 warnings = result.pop('__warnings', [])
385 for warning in warnings:
386 self.client.module.deprecate(
387 msg=warning['msg'],
388 version=warning['version']
389 )
390
391 def present(self):
392 if self.exists():
393 return self.update()
394 else:
395 return self.create()
396
397 def absent(self):
398 if self.exists():
399 return self.remove()
400 return False
401
402 def update(self):
403 self.have = self.read_current_from_device()
404 if not self.should_update():
405 return False
406 if self.module.check_mode:
407 return True
408 self.update_on_device()
409 return True
410
411 def remove(self):
412 if self.module.check_mode:
413 return True
414 self.remove_from_device()
415 if self.exists():
416 raise F5ModuleError("Failed to delete the resource.")
417 return True
418
419 def create(self):
420 self._set_changed_options()
421 if self.module.check_mode:
422 return True
423 self.create_on_device()
424 return True
425
426 def exists(self):
427 uri = "https://{0}:{1}/mgmt/tm/sys/smtp-server/{2}".format(
428 self.client.provider['server'],
429 self.client.provider['server_port'],
430 transform_name(self.want.partition, self.want.name)
431 )
432 resp = self.client.api.get(uri)
433 try:
434 response = resp.json()
435 except ValueError as ex:
436 raise F5ModuleError(str(ex))
437
438 if resp.status == 404 or 'code' in response and response['code'] == 404:
439 return False
440 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
441 return True
442
443 errors = [401, 403, 409, 500, 501, 502, 503, 504]
444
445 if resp.status in errors or 'code' in response and response['code'] in errors:
446 if 'message' in response:
447 raise F5ModuleError(response['message'])
448 else:
449 raise F5ModuleError(resp.content)
450
451 def create_on_device(self):
452 params = self.want.api_params()
453 params['name'] = self.want.name
454 params['partition'] = self.want.partition
455 uri = "https://{0}:{1}/mgmt/tm/sys/smtp-server/".format(
456 self.client.provider['server'],
457 self.client.provider['server_port'],
458 )
459 resp = self.client.api.post(uri, json=params)
460 try:
461 response = resp.json()
462 except ValueError as ex:
463 raise F5ModuleError(str(ex))
464
465 if 'code' in response and response['code'] in [400, 403]:
466 if 'message' in response:
467 raise F5ModuleError(response['message'])
468 else:
469 raise F5ModuleError(resp.content)
470
471 def update_on_device(self):
472 params = self.want.api_params()
473 uri = "https://{0}:{1}/mgmt/tm/sys/smtp-server/{2}".format(
474 self.client.provider['server'],
475 self.client.provider['server_port'],
476 transform_name(self.want.partition, self.want.name)
477 )
478 resp = self.client.api.patch(uri, json=params)
479 try:
480 response = resp.json()
481 except ValueError as ex:
482 raise F5ModuleError(str(ex))
483
484 if 'code' in response and response['code'] == 400:
485 if 'message' in response:
486 raise F5ModuleError(response['message'])
487 else:
488 raise F5ModuleError(resp.content)
489
490 def remove_from_device(self):
491 uri = "https://{0}:{1}/mgmt/tm/sys/smtp-server/{2}".format(
492 self.client.provider['server'],
493 self.client.provider['server_port'],
494 transform_name(self.want.partition, self.want.name)
495 )
496 resp = self.client.api.delete(uri)
497 if resp.status == 200:
498 return True
499
500 def read_current_from_device(self):
501 uri = "https://{0}:{1}/mgmt/tm/sys/smtp-server/{2}".format(
502 self.client.provider['server'],
503 self.client.provider['server_port'],
504 transform_name(self.want.partition, self.want.name)
505 )
506 resp = self.client.api.get(uri)
507 try:
508 response = resp.json()
509 except ValueError as ex:
510 raise F5ModuleError(str(ex))
511
512 if 'code' in response and response['code'] == 400:
513 if 'message' in response:
514 raise F5ModuleError(response['message'])
515 else:
516 raise F5ModuleError(resp.content)
517 return ApiParameters(params=response)
518
519
520 class ArgumentSpec(object):
521 def __init__(self):
522 self.supports_check_mode = True
523 argument_spec = dict(
524 name=dict(required=True),
525 smtp_server=dict(),
526 smtp_server_port=dict(type='int'),
527 smtp_server_username=dict(no_log=True),
528 smtp_server_password=dict(no_log=True),
529 local_host_name=dict(),
530 encryption=dict(choices=['none', 'ssl', 'tls']),
531 update_password=dict(
532 default='always',
533 choices=['always', 'on_create'],
534 no_log=False
535 ),
536 from_address=dict(),
537 authentication=dict(type='bool'),
538 partition=dict(
539 default='Common',
540 fallback=(env_fallback, ['F5_PARTITION'])
541 ),
542 state=dict(
543 default='present',
544 choices=['present', 'absent']
545 )
546 )
547 self.argument_spec = {}
548 self.argument_spec.update(f5_argument_spec)
549 self.argument_spec.update(argument_spec)
550
551
552 def main():
553 spec = ArgumentSpec()
554
555 module = AnsibleModule(
556 argument_spec=spec.argument_spec,
557 supports_check_mode=spec.supports_check_mode
558 )
559
560 try:
561 mm = ModuleManager(module=module)
562 results = mm.exec_module()
563 module.exit_json(**results)
564 except F5ModuleError as ex:
565 module.fail_json(msg=str(ex))
566
567
568 if __name__ == '__main__':
569 main()