Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_traffic_selector.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_traffic_selector
13 short_description: Manage IPSec Traffic Selectors on BIG-IP
14 description:
15 - Manage IPSec Traffic Selectors on BIG-IP.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the traffic selector.
21 type: str
22 required: True
23 destination_address:
24 description:
25 - Specifies the host or network IP address to which the application traffic is destined.
26 - When creating a new traffic selector, this parameter is required.
27 type: str
28 source_address:
29 description:
30 - Specifies the host or network IP address from which the application traffic originates.
31 - When creating a new traffic selector, this parameter is required.
32 type: str
33 ipsec_policy:
34 description:
35 - Specifies the IPsec policy that tells the BIG-IP system how to handle the packets.
36 - When creating a new traffic selector, if this parameter is not specified, the default
37 is C(default-ipsec-policy).
38 type: str
39 order:
40 description:
41 - Specifies the order in which traffic is matched, if traffic can be matched to multiple
42 traffic selectors.
43 - Traffic is matched to the traffic selector with the highest priority (lowest order number).
44 - When creating a new traffic selector, if this parameter is not specified, the default
45 is C(last).
46 type: int
47 description:
48 description:
49 - Description of the traffic selector.
50 type: str
51 partition:
52 description:
53 - Device partition to manage resources on.
54 type: str
55 default: Common
56 state:
57 description:
58 - When C(present), ensures the resource exists.
59 - When C(absent), ensures the resource is removed.
60 type: str
61 choices:
62 - present
63 - absent
64 default: present
65 extends_documentation_fragment: f5networks.f5_modules.f5
66 author:
67 - Tim Rupp (@caphrim007)
68 - Wojciech Wypior (@wojtek0806)
69 '''
70
71 EXAMPLES = r'''
72 - name: Create a traffic selector
73 bigip_traffic_selector:
74 name: selector1
75 destination_address: 1.1.1.1
76 ipsec_policy: policy1
77 order: 1
78 source_address: 2.2.2.2
79 provider:
80 password: secret
81 server: lb.mydomain.com
82 user: admin
83 delegate_to: localhost
84 '''
85
86 RETURN = r'''
87 destination_address:
88 description: The new Destination IP Address.
89 returned: changed
90 type: str
91 sample: 1.2.3.4/32
92 source_address:
93 description: The new Source IP address.
94 returned: changed
95 type: str
96 sample: 2.3.4.5/32
97 ipsec_policy:
98 description: The new IPSec policy.
99 returned: changed
100 type: str
101 sample: /Common/policy1
102 order:
103 description: The new sort order.
104 returned: changed
105 type: int
106 sample: 1
107 '''
108
109 import re
110 from datetime import datetime
111
112 from ansible.module_utils.basic import (
113 AnsibleModule, env_fallback
114 )
115 from ipaddress import ip_interface
116
117 from ..module_utils.bigip import F5RestClient
118 from ..module_utils.common import (
119 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
120 )
121 from ..module_utils.compare import cmp_str_with_none
122 from ..module_utils.icontrol import tmos_version
123 from ..module_utils.teem import send_teem
124
125
126 class Parameters(AnsibleF5Parameters):
127 api_map = {
128 'destinationAddress': 'destination_address',
129 'sourceAddress': 'source_address',
130 'ipsecPolicy': 'ipsec_policy',
131 }
132
133 api_attributes = [
134 'destinationAddress',
135 'sourceAddress',
136 'ipsecPolicy',
137 'order',
138 'description',
139 ]
140
141 returnables = [
142 'destination_address',
143 'source_address',
144 'ipsec_policy',
145 'order',
146 'description',
147 ]
148
149 updatables = [
150 'destination_address',
151 'source_address',
152 'ipsec_policy',
153 'order',
154 'description',
155 ]
156
157
158 class ApiParameters(Parameters):
159 @property
160 def description(self):
161 if self._values['description'] in [None, 'none']:
162 return None
163 return self._values['description']
164
165
166 class ModuleParameters(Parameters):
167 @property
168 def ipsec_policy(self):
169 if self._values['ipsec_policy'] is None:
170 return None
171 return fq_name(self.partition, self._values['ipsec_policy'])
172
173 @property
174 def destination_address(self):
175 result = self._format_address('destination_address')
176 if result == -1:
177 raise F5ModuleError(
178 "No IP address found in 'destination_address'."
179 )
180 return result
181
182 @property
183 def source_address(self):
184 result = self._format_address('source_address')
185 if result == -1:
186 raise F5ModuleError(
187 "No IP address found in 'source_address'."
188 )
189 return result
190
191 @property
192 def description(self):
193 if self._values['description'] is None:
194 return None
195 elif self._values['description'] in ['none', '']:
196 return ''
197 return self._values['description']
198
199 def _format_address(self, type):
200 if self._values[type] is None:
201 return None
202 pattern = r'(?P<addr>[^%/]+)(%(?P<rd>\d+))?(/(?P<cidr>\d+))?'
203 if '%' in self._values[type]:
204 # Handle route domains
205 matches = re.match(pattern, self._values[type])
206 if not matches:
207 return None
208 addr = matches.group('addr')
209 if addr is None:
210 return -1
211 cidr = matches.group('cidr')
212 rd = matches.group('rd')
213 if cidr is not None:
214 ip = ip_interface(u'{0}/{1}'.format(addr, cidr))
215 else:
216 ip = ip_interface(u'{0}'.format(addr))
217 if rd:
218 result = '{0}%{1}/{2}'.format(str(ip.ip), rd, ip.network.prefixlen)
219 else:
220 result = '{0}/{1}'.format(str(ip.ip), ip.network.prefixlen)
221 return result
222 return str(ip_interface(u'{0}'.format(self._values[type])))
223
224
225 class Changes(Parameters):
226 def to_return(self):
227 result = {}
228 try:
229 for returnable in self.returnables:
230 result[returnable] = getattr(self, returnable)
231 result = self._filter_params(result)
232 except Exception:
233 pass
234 return result
235
236
237 class UsableChanges(Changes):
238 pass
239
240
241 class ReportableChanges(Changes):
242 pass
243
244
245 class Difference(object):
246 def __init__(self, want, have=None):
247 self.want = want
248 self.have = have
249
250 def compare(self, param):
251 try:
252 result = getattr(self, param)
253 return result
254 except AttributeError:
255 return self.__default(param)
256
257 def __default(self, param):
258 attr1 = getattr(self.want, param)
259 try:
260 attr2 = getattr(self.have, param)
261 if attr1 != attr2:
262 return attr1
263 except AttributeError:
264 return attr1
265
266 @property
267 def description(self):
268 return cmp_str_with_none(self.want.description, self.have.description)
269
270
271 class ModuleManager(object):
272 def __init__(self, *args, **kwargs):
273 self.module = kwargs.get('module', None)
274 self.client = F5RestClient(**self.module.params)
275 self.want = ModuleParameters(params=self.module.params)
276 self.have = ApiParameters()
277 self.changes = UsableChanges()
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 should_update(self):
306 result = self._update_changed_options()
307 if result:
308 return True
309 return False
310
311 def exec_module(self):
312 start = datetime.now().isoformat()
313 version = tmos_version(self.client)
314 changed = False
315 result = dict()
316 state = self.want.state
317
318 if state == "present":
319 changed = self.present()
320 elif state == "absent":
321 changed = self.absent()
322
323 reportable = ReportableChanges(params=self.changes.to_return())
324 changes = reportable.to_return()
325 result.update(**changes)
326 result.update(dict(changed=changed))
327 self._announce_deprecations(result)
328 send_teem(start, self.client, self.module, version)
329 return result
330
331 def _announce_deprecations(self, result):
332 warnings = result.pop('__warnings', [])
333 for warning in warnings:
334 self.client.module.deprecate(
335 msg=warning['msg'],
336 version=warning['version']
337 )
338
339 def present(self):
340 if self.exists():
341 return self.update()
342 else:
343 return self.create()
344
345 def exists(self):
346 uri = "https://{0}:{1}/mgmt/tm/net/ipsec/traffic-selector/{2}".format(
347 self.client.provider['server'],
348 self.client.provider['server_port'],
349 transform_name(self.want.partition, self.want.name)
350 )
351 resp = self.client.api.get(uri)
352 try:
353 response = resp.json()
354 except ValueError as ex:
355 raise F5ModuleError(str(ex))
356
357 if resp.status == 404 or 'code' in response and response['code'] == 404:
358 return False
359 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
360 return True
361
362 errors = [401, 403, 409, 500, 501, 502, 503, 504]
363
364 if resp.status in errors or 'code' in response and response['code'] in errors:
365 if 'message' in response:
366 raise F5ModuleError(response['message'])
367 else:
368 raise F5ModuleError(resp.content)
369
370 def update(self):
371 self.have = self.read_current_from_device()
372 if not self.should_update():
373 return False
374 if self.module.check_mode:
375 return True
376 self.update_on_device()
377 return True
378
379 def remove(self):
380 if self.module.check_mode:
381 return True
382 self.remove_from_device()
383 if self.exists():
384 raise F5ModuleError("Failed to delete the resource.")
385 return True
386
387 def create(self):
388 self._set_changed_options()
389 if self.module.check_mode:
390 return True
391 self.create_on_device()
392 return True
393
394 def create_on_device(self):
395 params = self.changes.api_params()
396 params['name'] = self.want.name
397 params['partition'] = self.want.partition
398 uri = "https://{0}:{1}/mgmt/tm/net/ipsec/traffic-selector/".format(
399 self.client.provider['server'],
400 self.client.provider['server_port']
401 )
402 resp = self.client.api.post(uri, json=params)
403 try:
404 response = resp.json()
405 except ValueError as ex:
406 raise F5ModuleError(str(ex))
407
408 if 'code' in response and response['code'] in [400, 403]:
409 if 'message' in response:
410 raise F5ModuleError(response['message'])
411 else:
412 raise F5ModuleError(resp.content)
413
414 def update_on_device(self):
415 params = self.changes.api_params()
416 uri = "https://{0}:{1}/mgmt/tm/net/ipsec/traffic-selector/{2}".format(
417 self.client.provider['server'],
418 self.client.provider['server_port'],
419 transform_name(self.want.partition, self.want.name)
420 )
421 resp = self.client.api.patch(uri, json=params)
422 try:
423 response = resp.json()
424 except ValueError as ex:
425 raise F5ModuleError(str(ex))
426
427 if 'code' in response and response['code'] == 400:
428 if 'message' in response:
429 raise F5ModuleError(response['message'])
430 else:
431 raise F5ModuleError(resp.content)
432
433 def absent(self):
434 if self.exists():
435 return self.remove()
436 return False
437
438 def remove_from_device(self):
439 uri = "https://{0}:{1}/mgmt/tm/net/ipsec/traffic-selector/{2}".format(
440 self.client.provider['server'],
441 self.client.provider['server_port'],
442 transform_name(self.want.partition, self.want.name)
443 )
444 resp = self.client.api.delete(uri)
445 if resp.status == 200:
446 return True
447
448 def read_current_from_device(self):
449 uri = "https://{0}:{1}/mgmt/tm/net/ipsec/traffic-selector/{2}".format(
450 self.client.provider['server'],
451 self.client.provider['server_port'],
452 transform_name(self.want.partition, self.want.name)
453 )
454 resp = self.client.api.get(uri)
455 try:
456 response = resp.json()
457 except ValueError as ex:
458 raise F5ModuleError(str(ex))
459
460 if 'code' in response and response['code'] == 400:
461 if 'message' in response:
462 raise F5ModuleError(response['message'])
463 else:
464 raise F5ModuleError(resp.content)
465 return ApiParameters(params=response)
466
467
468 class ArgumentSpec(object):
469 def __init__(self):
470 self.supports_check_mode = True
471 argument_spec = dict(
472 name=dict(required=True),
473 destination_address=dict(),
474 source_address=dict(),
475 ipsec_policy=dict(),
476 order=dict(type='int'),
477 description=dict(),
478 state=dict(
479 default='present',
480 choices=['present', 'absent']
481 ),
482 partition=dict(
483 default='Common',
484 fallback=(env_fallback, ['F5_PARTITION'])
485 )
486 )
487 self.argument_spec = {}
488 self.argument_spec.update(f5_argument_spec)
489 self.argument_spec.update(argument_spec)
490
491
492 def main():
493 spec = ArgumentSpec()
494
495 module = AnsibleModule(
496 argument_spec=spec.argument_spec,
497 supports_check_mode=spec.supports_check_mode,
498 )
499
500 try:
501 mm = ModuleManager(module=module)
502 results = mm.exec_module()
503 module.exit_json(**results)
504 except F5ModuleError as ex:
505 module.fail_json(msg=str(ex))
506
507
508 if __name__ == '__main__':
509 main()