Debian Codegraph @

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