Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_cli_script.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_cli_script
13 short_description: Manage CLI scripts on a BIG-IP
14 description:
15 - Manages CLI scripts on a BIG-IP. CLI scripts, otherwise known as tmshell scripts
16 or TMSH scripts, allow you to create custom scripts that can run to manage objects
17 within a BIG-IP.
18 version_added: "1.0.0"
19 options:
20 name:
21 description:
22 - Specifies the name of the script.
23 type: str
24 required: True
25 content:
26 description:
27 - The content of the script.
28 - This parameter is typically used in conjunction with Ansible's C(file) or
29 template lookup plugins. See the examples in this documentation.
30 type: str
31 description:
32 description:
33 - Description of the cli script.
34 type: str
35 partition:
36 description:
37 - Device partition on which to manage resources.
38 type: str
39 default: Common
40 state:
41 description:
42 - When C(present), ensures the script exists.
43 - When C(absent), ensures the script is removed.
44 type: str
45 default: present
46 choices:
47 - present
48 - absent
49 extends_documentation_fragment: f5networks.f5_modules.f5
50 author:
51 - Tim Rupp (@caphrim007)
52 - Wojciech Wypior (@wojtek0806)
53 '''
54
55 EXAMPLES = r'''
56 - name: Create a cli script from an existing file
57 bigip_cli_script:
58 name: foo
59 content: "{{ lookup('file', '/absolute/path/to/cli/script.tcl') }}"
60 provider:
61 password: secret
62 server: lb.mydomain.com
63 user: admin
64 delegate_to: localhost
65
66 - name: Create a cli script from a jinja template representing a cli script
67 bigip_cli_script:
68 name: foo
69 content: "{{ lookup('template', '/absolute/path/to/cli/script.tcl') }}"
70 provider:
71 password: secret
72 server: lb.mydomain.com
73 user: admin
74 delegate_to: localhost
75 '''
76
77 RETURN = r'''
78 param1:
79 description: The new param1 value of the resource.
80 returned: changed
81 type: bool
82 sample: true
83 param2:
84 description: The new param2 value of the resource.
85 returned: changed
86 type: str
87 sample: Foo is bar
88 '''
89 from datetime import datetime
90
91 from ansible.module_utils.basic import (
92 AnsibleModule, env_fallback
93 )
94
95 from ..module_utils.bigip import F5RestClient
96 from ..module_utils.common import (
97 F5ModuleError, AnsibleF5Parameters, f5_argument_spec, transform_name
98 )
99 from ..module_utils.icontrol import tmos_version
100 from ..module_utils.teem import send_teem
101
102
103 class Parameters(AnsibleF5Parameters):
104 api_map = {
105 'apiAnonymous': 'content',
106 'scriptChecksum': 'checksum',
107 }
108
109 api_attributes = [
110 'apiAnonymous',
111 'description',
112 ]
113
114 returnables = [
115 'description',
116 'content',
117 ]
118
119 updatables = [
120 'description',
121 'content',
122 ]
123
124
125 class ApiParameters(Parameters):
126 @property
127 def ignore_verification(self):
128 return "true"
129
130 @property
131 def content(self):
132 return self._values['content'].strip()
133
134
135 class ModuleParameters(Parameters):
136 @property
137 def ignore_verification(self):
138 return "true"
139
140 @property
141 def content(self):
142 if self._values['content'] is None:
143 return None
144 return self._values['content'].strip()
145
146 @property
147 def description(self):
148 if self._values['description'] is None:
149 return None
150 elif self._values['description'] in ['none', '']:
151 return ''
152 return self._values['description']
153
154
155 class Changes(Parameters):
156 def to_return(self):
157 result = {}
158 try:
159 for returnable in self.returnables:
160 result[returnable] = getattr(self, returnable)
161 result = self._filter_params(result)
162 except Exception:
163 raise
164 return result
165
166
167 class UsableChanges(Changes):
168 pass
169
170
171 class ReportableChanges(Changes):
172 pass
173
174
175 class Difference(object):
176 def __init__(self, want, have=None):
177 self.want = want
178 self.have = have
179
180 def compare(self, param):
181 try:
182 result = getattr(self, param)
183 return result
184 except AttributeError:
185 return self.__default(param)
186
187 def __default(self, param):
188 attr1 = getattr(self.want, param)
189 try:
190 attr2 = getattr(self.have, param)
191 if attr1 != attr2:
192 return attr1
193 except AttributeError:
194 return attr1
195
196 @property
197 def content(self):
198 if self.want.content is None:
199 return None
200 if self.have.content is None:
201 return self.want.content
202 if self.want.content != self.have.content:
203 return self.want.content
204
205 @property
206 def description(self):
207 if self.want.description is None:
208 return None
209 if self.have.description is None and self.want.description == '':
210 return None
211 if self.want.description != self.have.description:
212 return self.want.description
213
214
215 class ModuleManager(object):
216 def __init__(self, *args, **kwargs):
217 self.module = kwargs.get('module', None)
218 self.client = F5RestClient(**self.module.params)
219 self.want = ModuleParameters(params=self.module.params)
220 self.have = ApiParameters()
221 self.changes = UsableChanges()
222
223 def _set_changed_options(self):
224 changed = {}
225 for key in Parameters.returnables:
226 if getattr(self.want, key) is not None:
227 changed[key] = getattr(self.want, key)
228 if changed:
229 self.changes = UsableChanges(params=changed)
230
231 def _update_changed_options(self):
232 diff = Difference(self.want, self.have)
233 updatables = Parameters.updatables
234 changed = dict()
235 for k in updatables:
236 change = diff.compare(k)
237 if change is None:
238 continue
239 else:
240 if isinstance(change, dict):
241 changed.update(change)
242 else:
243 changed[k] = change
244 if changed:
245 self.changes = UsableChanges(params=changed)
246 return True
247 return False
248
249 def should_update(self):
250 result = self._update_changed_options()
251 if result:
252 return True
253 return False
254
255 def exec_module(self):
256 start = datetime.now().isoformat()
257 version = tmos_version(self.client)
258 changed = False
259 result = dict()
260 state = self.want.state
261
262 if state == "present":
263 changed = self.present()
264 elif state == "absent":
265 changed = self.absent()
266
267 reportable = ReportableChanges(params=self.changes.to_return())
268 changes = reportable.to_return()
269 result.update(**changes)
270 result.update(dict(changed=changed))
271 self._announce_deprecations(result)
272 send_teem(start, self.client, self.module, version)
273 return result
274
275 def _announce_deprecations(self, result):
276 warnings = result.pop('__warnings', [])
277 for warning in warnings:
278 self.client.module.deprecate(
279 msg=warning['msg'],
280 version=warning['version']
281 )
282
283 def present(self):
284 if self.exists():
285 return self.update()
286 else:
287 return self.create()
288
289 def exists(self):
290 errors = [401, 403, 409, 500, 501, 502, 503, 504]
291 uri = "https://{0}:{1}/mgmt/tm/cli/script/{2}".format(
292 self.client.provider['server'],
293 self.client.provider['server_port'],
294 transform_name(self.want.partition, self.want.name)
295 )
296 resp = self.client.api.get(uri)
297 try:
298 response = resp.json()
299 except ValueError as ex:
300 raise F5ModuleError(str(ex))
301
302 if resp.status == 404 or 'code' in response and response['code'] == 404:
303 return False
304 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
305 return True
306
307 if resp.status in errors or 'code' in response and response['code'] in errors:
308 if 'message' in response:
309 raise F5ModuleError(response['message'])
310 else:
311 raise F5ModuleError(resp.content)
312
313 def update(self):
314 self.have = self.read_current_from_device()
315 if not self.should_update():
316 return False
317 if self.module.check_mode:
318 return True
319
320 # Update any missing params
321 #
322 # The cli/script API is kinda weird in that it wont let us individually
323 # PATCH the description. We appear to need to include the content otherwise
324 # we get errors about us trying to replace procs that are needed by other
325 # scripts, ie, the script we're trying to update.
326 params = self.changes.api_params()
327 if 'description' in params and 'content' not in params:
328 self.changes.update({'content': self.have.content})
329 if 'content' in params and 'description' not in params:
330 self.changes.update({'description': self.have.description})
331
332 self.update_on_device()
333 return True
334
335 def remove(self):
336 if self.module.check_mode:
337 return True
338 self.remove_from_device()
339 if self.exists():
340 raise F5ModuleError("Failed to delete the resource.")
341 return True
342
343 def create(self):
344 self._set_changed_options()
345 if self.module.check_mode:
346 return True
347 self.create_on_device()
348 return True
349
350 def create_on_device(self):
351 params = self.changes.api_params()
352 params['name'] = self.want.name
353 params['partition'] = self.want.partition
354 uri = "https://{0}:{1}/mgmt/tm/cli/script/".format(
355 self.client.provider['server'],
356 self.client.provider['server_port']
357 )
358 resp = self.client.api.post(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 update_on_device(self):
369 params = self.changes.api_params()
370 uri = "https://{0}:{1}/mgmt/tm/cli/script/{2}".format(
371 self.client.provider['server'],
372 self.client.provider['server_port'],
373 transform_name(self.want.partition, self.want.name)
374 )
375 resp = self.client.api.patch(uri, json=params)
376 try:
377 response = resp.json()
378 except ValueError as ex:
379 raise F5ModuleError(str(ex))
380
381 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
382 return True
383 raise F5ModuleError(resp.content)
384
385 def absent(self):
386 if self.exists():
387 return self.remove()
388 return False
389
390 def remove_from_device(self):
391 uri = "https://{0}:{1}/mgmt/tm/cli/script/{2}".format(
392 self.client.provider['server'],
393 self.client.provider['server_port'],
394 transform_name(self.want.partition, self.want.name)
395 )
396 response = self.client.api.delete(uri)
397
398 if response.status in [200, 201]:
399 return True
400 raise F5ModuleError(response.content)
401
402 def read_current_from_device(self):
403 uri = "https://{0}:{1}/mgmt/tm/cli/script/{2}".format(
404 self.client.provider['server'],
405 self.client.provider['server_port'],
406 transform_name(self.want.partition, self.want.name)
407 )
408 resp = self.client.api.get(uri)
409 try:
410 response = resp.json()
411 except ValueError as ex:
412 raise F5ModuleError(str(ex))
413
414 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
415 return ApiParameters(params=response)
416 raise F5ModuleError(resp.content)
417
418
419 class ArgumentSpec(object):
420 def __init__(self):
421 self.supports_check_mode = True
422 argument_spec = dict(
423 name=dict(required=True),
424 description=dict(),
425 content=dict(),
426 state=dict(
427 default='present',
428 choices=['present', 'absent']
429 ),
430 partition=dict(
431 default='Common',
432 fallback=(env_fallback, ['F5_PARTITION'])
433 )
434 )
435 self.argument_spec = {}
436 self.argument_spec.update(f5_argument_spec)
437 self.argument_spec.update(argument_spec)
438
439
440 def main():
441 spec = ArgumentSpec()
442
443 module = AnsibleModule(
444 argument_spec=spec.argument_spec,
445 supports_check_mode=spec.supports_check_mode,
446 )
447
448 try:
449 mm = ModuleManager(module=module)
450 results = mm.exec_module()
451 module.exit_json(**results)
452 except F5ModuleError as ex:
453 module.fail_json(msg=str(ex))
454
455
456 if __name__ == '__main__':
457 main()