Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_device_sshd.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_device_sshd
13 short_description: Manage the SSHD settings of a BIG-IP
14 description:
15 - Manage the SSHD (secure shell daemon) settings of a BIG-IP.
16 version_added: "1.0.0"
17 options:
18 allow:
19 description:
20 - If you have enabled SSH access, specifies the IP address or address
21 range for other systems that can use SSH to communicate with this
22 system.
23 - To specify all addresses, use the value C(all).
24 - An IP address can be specified, such as 172.27.1.10.
25 - IP ranges can be specified, such as 172.27.*.* or 172.27.0.0/255.255.0.0.
26 - To remove SSH access, specify an empty list or an empty string.
27 type: list
28 elements: str
29 banner:
30 description:
31 - Whether to enable the banner or not.
32 type: str
33 choices:
34 - enabled
35 - disabled
36 banner_text:
37 description:
38 - Specifies the text to include on the pre-login banner, which displays
39 when a user attempts to login to the system using SSH.
40 type: str
41 inactivity_timeout:
42 description:
43 - Specifies the number of seconds before inactivity causes an SSH
44 session to log out.
45 type: int
46 log_level:
47 description:
48 - Specifies the minimum SSHD message level to include in the system log.
49 type: str
50 choices:
51 - debug
52 - debug1
53 - debug2
54 - debug3
55 - error
56 - fatal
57 - info
58 - quiet
59 - verbose
60 login:
61 description:
62 - When checked C(enabled), specifies the system accepts SSH
63 communication.
64 type: str
65 choices:
66 - enabled
67 - disabled
68 port:
69 description:
70 - Port on which you want the SSH daemon to run.
71 type: int
72 notes:
73 - Requires BIG-IP version 12.0.0 or greater
74 extends_documentation_fragment: f5networks.f5_modules.f5
75 author:
76 - Tim Rupp (@caphrim007)
77 - Wojciech Wypior (@wojtek0806)
78 '''
79
80 EXAMPLES = r'''
81 - name: Set the banner for the SSHD service from a string
82 bigip_device_sshd:
83 banner: enabled
84 banner_text: banner text goes here
85 provider:
86 password: secret
87 server: lb.mydomain.com
88 user: admin
89 delegate_to: localhost
90
91 - name: Set the banner for the SSHD service from a file
92 bigip_device_sshd:
93 banner: enabled
94 banner_text: "{{ lookup('file', '/path/to/file') }}"
95 provider:
96 password: secret
97 server: lb.mydomain.com
98 user: admin
99 delegate_to: localhost
100
101 - name: Set the SSHD service to run on port 2222
102 bigip_device_sshd:
103 port: 2222
104 provider:
105 user: admin
106 password: secret
107 server: lb.mydomain.com
108 delegate_to: localhost
109 '''
110
111 RETURN = r'''
112 allow:
113 description:
114 - If you have enabled SSH access, specifies the IP address or address
115 range for other systems that can use SSH to communicate with this
116 system.
117 returned: changed
118 type: list
119 sample: 192.0.2.*
120 banner:
121 description: Whether the banner is enabled or not.
122 returned: changed
123 type: str
124 sample: true
125 banner_text:
126 description:
127 - Specifies the text included on the pre-login banner which
128 displays when a user attempts to login to the system using SSH.
129 returned: changed and success
130 type: str
131 sample: This is a corporate device. Connecting to it without...
132 inactivity_timeout:
133 description:
134 - The number of seconds before inactivity causes an SSH
135 session to log out.
136 returned: changed
137 type: int
138 sample: 10
139 log_level:
140 description: The minimum SSHD message level to include in the system log.
141 returned: changed
142 type: str
143 sample: debug
144 login:
145 description: Specifies whether the system accepts SSH communications or not.
146 returned: changed
147 type: bool
148 sample: true
149 port:
150 description: Port on which you want the SSH daemon to run.
151 returned: changed
152 type: int
153 sample: 22
154 '''
155 from datetime import datetime
156 from ansible.module_utils.basic import AnsibleModule
157
158 from ..module_utils.bigip import F5RestClient
159 from ..module_utils.common import (
160 F5ModuleError, AnsibleF5Parameters, is_empty_list, f5_argument_spec
161 )
162 from ..module_utils.icontrol import tmos_version
163 from ..module_utils.teem import send_teem
164
165
166 class Parameters(AnsibleF5Parameters):
167 api_map = {
168 'bannerText': 'banner_text',
169 'inactivityTimeout': 'inactivity_timeout',
170 'logLevel': 'log_level',
171 }
172
173 api_attributes = [
174 'allow', 'banner', 'bannerText', 'inactivityTimeout',
175 'logLevel', 'login', 'port',
176 ]
177
178 updatables = [
179 'allow', 'banner', 'banner_text', 'inactivity_timeout',
180 'log_level', 'login', 'port',
181 ]
182
183 returnables = [
184 'allow', 'banner', 'banner_text', 'inactivity_timeout',
185 'log_level', 'login', 'port',
186 ]
187
188
189 class ApiParameters(Parameters):
190 pass
191
192
193 class ModuleParameters(Parameters):
194 @property
195 def inactivity_timeout(self):
196 if self._values['inactivity_timeout'] is None:
197 return None
198 return int(self._values['inactivity_timeout'])
199
200 @property
201 def port(self):
202 if self._values['port'] is None:
203 return None
204 return int(self._values['port'])
205
206 @property
207 def allow(self):
208 allow = self._values['allow']
209 if allow is None:
210 return None
211 if is_empty_list(allow):
212 return []
213 return allow
214
215
216 class Changes(Parameters):
217 def to_return(self):
218 result = {}
219 try:
220 for returnable in self.returnables:
221 change = getattr(self, returnable)
222 if isinstance(change, dict):
223 result.update(change)
224 else:
225 result[returnable] = change
226 result = self._filter_params(result)
227 except Exception:
228 raise
229 return result
230
231
232 class UsableChanges(Changes):
233 pass
234
235
236 class ReportableChanges(Changes):
237 pass
238
239
240 class Difference(object):
241 def __init__(self, want, have=None):
242 self.want = want
243 self.have = have
244
245 def compare(self, param):
246 try:
247 result = getattr(self, param)
248 return result
249 except AttributeError:
250 return self.__default(param)
251
252 def __default(self, param):
253 attr1 = getattr(self.want, param)
254 try:
255 attr2 = getattr(self.have, param)
256 if attr1 != attr2:
257 return attr1
258 except AttributeError:
259 return attr1
260
261 @property
262 def allow(self):
263 if self.want.allow is None:
264 return None
265 if not self.want.allow:
266 if self.have.allow is None:
267 return None
268 if self.have.allow is not None:
269 return self.want.allow
270 if self.have.allow is None:
271 return self.want.allow
272 if set(self.want.allow) != set(self.have.allow):
273 return self.want.allow
274
275 @property
276 def banner_text(self):
277 if self.want.banner_text is None:
278 return None
279 if self.want.banner_text == '' and self.have.banner_text is None:
280 return None
281 if self.want.banner_text != self.have.banner_text:
282 return self.want.banner_text
283
284
285 class ModuleManager(object):
286 def __init__(self, *args, **kwargs):
287 self.module = kwargs.get('module', None)
288 self.client = F5RestClient(**self.module.params)
289 self.want = ModuleParameters(params=self.module.params)
290 self.have = ApiParameters()
291 self.changes = UsableChanges()
292
293 def _update_changed_options(self):
294 diff = Difference(self.want, self.have)
295 updatables = Parameters.updatables
296 changed = dict()
297 for k in updatables:
298 change = diff.compare(k)
299 if change is None:
300 continue
301 else:
302 if isinstance(change, dict):
303 changed.update(change)
304 else:
305 changed[k] = change
306 if changed:
307 self.changes = UsableChanges(params=changed)
308 return True
309 return False
310
311 def _announce_deprecations(self, result):
312 warnings = result.pop('__warnings', [])
313 for warning in warnings:
314 self.client.module.deprecate(
315 msg=warning['msg'],
316 version=warning['version']
317 )
318
319 def exec_module(self):
320 start = datetime.now().isoformat()
321 version = tmos_version(self.client)
322 result = dict()
323
324 changed = self.present()
325
326 reportable = ReportableChanges(params=self.changes.to_return())
327 changes = reportable.to_return()
328 result.update(**changes)
329 result.update(dict(changed=changed))
330 self._announce_deprecations(result)
331 send_teem(start, self.client, self.module, version)
332 return result
333
334 def present(self):
335 return self.update()
336
337 def update(self):
338 self.have = self.read_current_from_device()
339 if not self.should_update():
340 return False
341 if self.module.check_mode:
342 return True
343 self.update_on_device()
344 return True
345
346 def should_update(self):
347 result = self._update_changed_options()
348 if result:
349 return True
350 return False
351
352 def update_on_device(self):
353 params = self.changes.api_params()
354 uri = "https://{0}:{1}/mgmt/tm/sys/sshd/".format(
355 self.client.provider['server'],
356 self.client.provider['server_port'],
357 )
358 resp = self.client.api.patch(uri, json=params)
359 try:
360 response = resp.json()
361 except ValueError as ex:
362 raise F5ModuleError(str(ex))
363
364 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
365 return True
366 raise F5ModuleError(resp.content)
367
368 def read_current_from_device(self):
369 uri = "https://{0}:{1}/mgmt/tm/sys/sshd/".format(
370 self.client.provider['server'],
371 self.client.provider['server_port'],
372 )
373 resp = self.client.api.get(uri)
374 try:
375 response = resp.json()
376 except ValueError as ex:
377 raise F5ModuleError(str(ex))
378
379 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
380 return ApiParameters(params=response)
381 raise F5ModuleError(resp.content)
382
383
384 class ArgumentSpec(object):
385 def __init__(self):
386 self.choices = ['enabled', 'disabled']
387 self.levels = [
388 'debug', 'debug1', 'debug2', 'debug3', 'error', 'fatal', 'info',
389 'quiet', 'verbose'
390 ]
391 self.supports_check_mode = True
392 argument_spec = dict(
393 allow=dict(
394 type='list',
395 elements='str',
396 ),
397 banner=dict(
398 choices=self.choices
399 ),
400 banner_text=dict(),
401 inactivity_timeout=dict(
402 type='int'
403 ),
404 log_level=dict(
405 choices=self.levels
406 ),
407 login=dict(
408 choices=self.choices
409 ),
410 port=dict(
411 type='int'
412 )
413 )
414 self.argument_spec = {}
415 self.argument_spec.update(f5_argument_spec)
416 self.argument_spec.update(argument_spec)
417
418
419 def main():
420 spec = ArgumentSpec()
421
422 module = AnsibleModule(
423 argument_spec=spec.argument_spec,
424 supports_check_mode=spec.supports_check_mode
425 )
426
427 try:
428 mm = ModuleManager(module=module)
429 results = mm.exec_module()
430 module.exit_json(**results)
431 except F5ModuleError as ex:
432 module.fail_json(msg=str(ex))
433
434
435 if __name__ == '__main__':
436 main()