Debian Codegraph @

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