Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_snat_pool.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2016, 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_snat_pool
13 short_description: Manage SNAT pools on a BIG-IP
14 description:
15 - Manage SNAT pools on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 members:
19 description:
20 - List of members to put in the SNAT pool. When C(state) is C(present),
21 this parameter is required, otherwise it is optional.
22 - The members can be either IP addresses or names of the SNAT translation objects.
23 type: list
24 elements: str
25 aliases:
26 - member
27 description:
28 description:
29 - An optional description of the SNAT pool.
30 type: str
31 name:
32 description:
33 - The name of the SNAT pool.
34 type: str
35 required: True
36 state:
37 description:
38 - Whether the SNAT pool should exist or not.
39 type: str
40 choices:
41 - present
42 - absent
43 default: present
44 partition:
45 description:
46 - Device partition to manage resources on.
47 type: str
48 default: Common
49 notes:
50 - When the C(bigip_snat_pool) object is removed, it also removes any associated C(bigip_snat_translation) objects.
51 - This is a BIG-IP behavior not module behavior, and it only occurs when the C(bigip_snat_translation) objects
52 are also not referenced by another C(bigip_snat_pool).
53 extends_documentation_fragment: f5networks.f5_modules.f5
54 author:
55 - Tim Rupp (@caphrim007)
56 - Wojciech Wypior (@wojtek0806)
57 '''
58
59 EXAMPLES = r'''
60 - name: Add the SNAT pool 'my-snat-pool'
61 bigip_snat_pool:
62 name: my-snat-pool
63 state: present
64 members:
65 - 10.10.10.10
66 - 20.20.20.20
67 provider:
68 server: lb.mydomain.com
69 user: admin
70 password: secret
71 delegate_to: localhost
72
73 - name: Change the SNAT pool's members to a single member
74 bigip_snat_pool:
75 name: my-snat-pool
76 state: present
77 member: 30.30.30.30
78 provider:
79 server: lb.mydomain.com
80 user: admin
81 password: secret
82 delegate_to: localhost
83
84 - name: Remove the SNAT pool 'my-snat-pool'
85 bigip_snat_pool:
86 name: johnd
87 state: absent
88 provider:
89 server: lb.mydomain.com
90 user: admin
91 password: secret
92 delegate_to: localhost
93
94 - name: Add the SNAT pool 'my-snat-pool' with a description
95 bigip_snat_pool:
96 name: my-snat-pool
97 state: present
98 members:
99 - 10.10.10.10
100 - 20.20.20.20
101 description: A SNAT pool description
102 provider:
103 server: lb.mydomain.com
104 user: admin
105 password: secret
106 delegate_to: localhost
107 '''
108
109 RETURN = r'''
110 members:
111 description:
112 - List of members that are part of the SNAT pool.
113 returned: changed and success
114 type: list
115 sample: "['10.10.10.10']"
116 '''
117
118 import re
119 import os
120 from datetime import datetime
121
122 from ansible.module_utils.basic import (
123 AnsibleModule, env_fallback
124 )
125
126 from ..module_utils.bigip import F5RestClient
127 from ..module_utils.common import (
128 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec
129 )
130 from ..module_utils.compare import cmp_str_with_none
131 from ..module_utils.ipaddress import (
132 is_valid_ip, compress_address
133 )
134 from ..module_utils.icontrol import tmos_version
135 from ..module_utils.teem import send_teem
136
137
138 class Parameters(AnsibleF5Parameters):
139 api_map = {}
140
141 updatables = [
142 'members',
143 'description',
144 ]
145
146 returnables = [
147 'members',
148 'description',
149 ]
150
151 api_attributes = [
152 'members',
153 'description',
154 ]
155
156
157 class ApiParameters(Parameters):
158 pass
159
160
161 class ModuleParameters(Parameters):
162 def _clear_member_prefix(self, member):
163 result = os.path.basename(member)
164 return result
165
166 def _format_member_address(self, member):
167 if len(member.split('%')) > 1:
168 address, rd = member.split('%')
169 if is_valid_ip(address):
170 result = '/{0}/{1}%{2}'.format(self.partition, compress_address(address), rd)
171 return result
172 else:
173 if is_valid_ip(member):
174 address = '/{0}/{1}'.format(self.partition, member)
175 return address
176 else:
177 # names must start with alphabetic character, and can contain hyphens and underscores and numbers
178 # no special characters are allowed
179 pattern = re.compile(r'(?!-)[A-Z-].*(?<!-)$', re.IGNORECASE)
180 if pattern.match(member):
181 address = '/{0}/{1}'.format(self.partition, member)
182 return address
183 raise F5ModuleError(
184 'The provided member address: {0} is not a valid IP address or snat translation name'.format(member)
185 )
186
187 @property
188 def members(self):
189 if self._values['members'] is None:
190 return None
191 result = set()
192 for member in self._values['members']:
193 member = self._clear_member_prefix(member)
194 address = self._format_member_address(member)
195 result.update([address])
196 return list(result)
197
198 @property
199 def description(self):
200 if self._values['description'] is None:
201 return None
202 elif self._values['description'] in ['none', '']:
203 return ''
204 return self._values['description']
205
206
207 class Changes(Parameters):
208 def to_return(self):
209 result = {}
210 for returnable in self.returnables:
211 try:
212 result[returnable] = getattr(self, returnable)
213 except Exception:
214 pass
215 result = self._filter_params(result)
216 return result
217
218
219 class UsableChanges(Changes):
220 pass
221
222
223 class ReportableChanges(Changes):
224 pass
225
226
227 class Difference(object):
228 def __init__(self, want, have=None):
229 self.want = want
230 self.have = have
231
232 def compare(self, param):
233 try:
234 result = getattr(self, param)
235 return result
236 except AttributeError:
237 return self.__default(param)
238
239 def __default(self, param):
240 attr1 = getattr(self.want, param)
241 try:
242 attr2 = getattr(self.have, param)
243 if attr1 != attr2:
244 return attr1
245 except AttributeError:
246 return attr1
247
248 @property
249 def members(self):
250 if self.want.members is None:
251 return None
252 if set(self.want.members) == set(self.have.members):
253 return None
254 result = list(set(self.want.members))
255 return result
256
257 @property
258 def description(self):
259 result = cmp_str_with_none(self.want.description, self.have.description)
260 return result
261
262
263 class ModuleManager(object):
264 def __init__(self, *args, **kwargs):
265 self.module = kwargs.get('module', None)
266 self.client = F5RestClient(**self.module.params)
267 self.want = ModuleParameters(params=self.module.params)
268 self.have = ApiParameters()
269 self.changes = UsableChanges()
270
271 def _announce_deprecations(self, result):
272 warnings = result.pop('__warnings', [])
273 for warning in warnings:
274 self.module.deprecate(
275 msg=warning['msg'],
276 version=warning['version']
277 )
278
279 def _set_changed_options(self):
280 changed = {}
281 for key in Parameters.returnables:
282 if getattr(self.want, key) is not None:
283 changed[key] = getattr(self.want, key)
284 if changed:
285 self.changes = UsableChanges(params=changed)
286
287 def _update_changed_options(self):
288 diff = Difference(self.want, self.have)
289 updatables = Parameters.updatables
290 changed = dict()
291 for k in updatables:
292 change = diff.compare(k)
293 if change is None:
294 continue
295 else:
296 if isinstance(change, dict):
297 changed.update(change)
298 else:
299 changed[k] = change
300 if changed:
301 self.changes = UsableChanges(params=changed)
302 return True
303 return False
304
305 def exec_module(self):
306 start = datetime.now().isoformat()
307 version = tmos_version(self.client)
308 changed = False
309 result = dict()
310 state = self.want.state
311
312 if state == "present":
313 changed = self.present()
314 elif state == "absent":
315 changed = self.absent()
316
317 reportable = ReportableChanges(params=self.changes.to_return())
318 changes = reportable.to_return()
319 result.update(**changes)
320
321 if self.module._diff and self.have:
322 result['diff'] = self.make_diff()
323
324 result.update(dict(changed=changed))
325 self._announce_deprecations(result)
326 send_teem(start, self.client, self.module, version)
327 return result
328
329 def _grab_attr(self, item):
330 result = dict()
331 updatables = Parameters.updatables
332 for k in updatables:
333 if getattr(item, k) is not None:
334 result[k] = getattr(item, k)
335 return result
336
337 def make_diff(self):
338 result = dict(before=self._grab_attr(self.have), after=self._grab_attr(self.want))
339 return result
340
341 def present(self):
342 if self.exists():
343 return self.update()
344 else:
345 return self.create()
346
347 def absent(self):
348 changed = False
349 if self.exists():
350 changed = self.remove()
351 return changed
352
353 def should_update(self):
354 result = self._update_changed_options()
355 if result:
356 return True
357 return False
358
359 def update(self):
360 self.have = self.read_current_from_device()
361 if not self.should_update():
362 return False
363 if self.module.check_mode:
364 return True
365 self.update_on_device()
366 return True
367
368 def create(self):
369 self._set_changed_options()
370 if self.module.check_mode:
371 return True
372 self.create_on_device()
373 if not self.exists():
374 raise F5ModuleError("Failed to create the SNAT pool")
375 return True
376
377 def remove(self):
378 if self.module.check_mode:
379 return True
380 self.remove_from_device()
381 if self.exists():
382 raise F5ModuleError("Failed to delete the SNAT pool")
383 return True
384
385 def exists(self):
386 uri = "https://{0}:{1}/mgmt/tm/ltm/snatpool/{2}".format(
387 self.client.provider['server'],
388 self.client.provider['server_port'],
389 transform_name(self.want.partition, self.want.name)
390 )
391 resp = self.client.api.get(uri)
392 try:
393 response = resp.json()
394 except ValueError as ex:
395 raise F5ModuleError(str(ex))
396
397 if resp.status == 404 or 'code' in response and response['code'] == 404:
398 return False
399 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
400 return True
401
402 errors = [401, 403, 409, 500, 501, 502, 503, 504]
403
404 if resp.status in errors or 'code' in response and response['code'] in errors:
405 if 'message' in response:
406 raise F5ModuleError(response['message'])
407 else:
408 raise F5ModuleError(resp.content)
409
410 def create_on_device(self):
411 params = self.changes.api_params()
412 params['name'] = self.want.name
413 params['partition'] = self.want.partition
414 uri = "https://{0}:{1}/mgmt/tm/ltm/snatpool/".format(
415 self.client.provider['server'],
416 self.client.provider['server_port']
417 )
418 resp = self.client.api.post(uri, json=params)
419 try:
420 response = resp.json()
421 except ValueError as ex:
422 raise F5ModuleError(str(ex))
423
424 if 'code' in response and response['code'] in [400, 403]:
425 if 'message' in response:
426 raise F5ModuleError(response['message'])
427 else:
428 raise F5ModuleError(resp.content)
429 return response['selfLink']
430
431 def update_on_device(self):
432 params = self.changes.api_params()
433 uri = "https://{0}:{1}/mgmt/tm/ltm/snatpool/{2}".format(
434 self.client.provider['server'],
435 self.client.provider['server_port'],
436 transform_name(self.want.partition, self.want.name)
437 )
438 resp = self.client.api.patch(uri, json=params)
439 try:
440 response = resp.json()
441 except ValueError as ex:
442 raise F5ModuleError(str(ex))
443
444 if 'code' in response and response['code'] == 400:
445 if 'message' in response:
446 raise F5ModuleError(response['message'])
447 else:
448 raise F5ModuleError(resp.content)
449
450 def remove_from_device(self):
451 uri = "https://{0}:{1}/mgmt/tm/ltm/snatpool/{2}".format(
452 self.client.provider['server'],
453 self.client.provider['server_port'],
454 transform_name(self.want.partition, self.want.name)
455 )
456 response = self.client.api.delete(uri)
457 if response.status == 200:
458 return True
459 raise F5ModuleError(response.content)
460
461 def read_current_from_device(self):
462 uri = "https://{0}:{1}/mgmt/tm/ltm/snatpool/{2}".format(
463 self.client.provider['server'],
464 self.client.provider['server_port'],
465 transform_name(self.want.partition, self.want.name)
466 )
467 query = '?expandSubcollections=true'
468 resp = self.client.api.get(uri + query)
469 try:
470 response = resp.json()
471 except ValueError as ex:
472 raise F5ModuleError(str(ex))
473
474 if 'code' in response and response['code'] == 400:
475 if 'message' in response:
476 raise F5ModuleError(response['message'])
477 else:
478 raise F5ModuleError(resp.content)
479 return ApiParameters(params=response)
480
481
482 class ArgumentSpec(object):
483 def __init__(self):
484 self.supports_check_mode = True
485 argument_spec = dict(
486 name=dict(required=True),
487 members=dict(
488 type='list',
489 elements='str',
490 aliases=['member']
491 ),
492 description=dict(),
493 state=dict(
494 default='present',
495 choices=['absent', 'present']
496 ),
497 partition=dict(
498 default='Common',
499 fallback=(env_fallback, ['F5_PARTITION'])
500 )
501 )
502 self.argument_spec = {}
503 self.argument_spec.update(f5_argument_spec)
504 self.argument_spec.update(argument_spec)
505 self.required_if = [
506 ['state', 'present', ['members']]
507 ]
508
509
510 def main():
511 spec = ArgumentSpec()
512
513 module = AnsibleModule(
514 argument_spec=spec.argument_spec,
515 supports_check_mode=spec.supports_check_mode,
516 required_if=spec.required_if
517 )
518
519 try:
520 mm = ModuleManager(module=module)
521 results = mm.exec_module()
522 module.exit_json(**results)
523 except F5ModuleError as ex:
524 module.fail_json(msg=str(ex))
525
526
527 if __name__ == '__main__':
528 main()