Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_configsync_action.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_configsync_action
13 short_description: Perform different actions related to config-sync
14 description:
15 - Allows running different config-sync actions. These actions allow
16 you to manually sync your configuration across multiple BIG-IPs when
17 those devices are in an HA pair.
18 version_added: "1.0.0"
19 options:
20 device_group:
21 description:
22 - The device group on which you want to perform config-sync actions.
23 type: str
24 required: True
25 sync_device_to_group:
26 description:
27 - Specifies the system synchronizes configuration data from this
28 device to other members of the device group. In this case, the device
29 performs a "push" to all the other devices in the group. This option
30 is mutually exclusive with the C(sync_group_to_device) option.
31 type: bool
32 sync_group_to_device:
33 description:
34 - Specifies the system synchronizes configuration data from the
35 device with the most recent configuration. In this case, the device
36 performs a "pull" from the most recently updated device. This option
37 is mutually exclusive with the C(sync_device_to_group) options.
38 type: bool
39 overwrite_config:
40 description:
41 - Indicates the sync operation overwrites the configuration on
42 the target.
43 type: bool
44 default: false
45 notes:
46 - Requires the objectpath Python package on the host. This is as easy as
47 running C(pip install objectpath).
48 extends_documentation_fragment: f5networks.f5_modules.f5
49 author:
50 - Tim Rupp (@caphrim007)
51 - Wojciech Wypior (@wojtek0806)
52 '''
53
54 EXAMPLES = r'''
55 - name: Sync configuration from device to group
56 bigip_configsync_action:
57 device_group: foo-group
58 sync_device_to_group: true
59 provider:
60 server: lb.mydomain.com
61 user: admin
62 password: secret
63 delegate_to: localhost
64
65 - name: Sync configuration from most recent device to the current host
66 bigip_configsync_action:
67 device_group: foo-group
68 sync_group_to_device: true
69 provider:
70 server: lb.mydomain.com
71 user: admin
72 password: secret
73 delegate_to: localhost
74
75 - name: Perform an initial sync of a device to a new device group
76 bigip_configsync_action:
77 device_group: new-device-group
78 sync_device_to_group: true
79 provider:
80 server: lb.mydomain.com
81 user: admin
82 password: secret
83 delegate_to: localhost
84 '''
85
86 RETURN = r'''
87 # only common fields returned
88 '''
89
90 import re
91 import time
92 from datetime import datetime
93
94 from ansible.module_utils.basic import AnsibleModule
95
96
97 from ..module_utils.bigip import F5RestClient
98 from ..module_utils.common import (
99 F5ModuleError, AnsibleF5Parameters, f5_argument_spec, flatten_boolean
100 )
101 from ..module_utils.icontrol import tmos_version
102 from ..module_utils.teem import send_teem
103
104 try:
105 from objectpath import Tree
106 HAS_OBJPATH = True
107 except ImportError:
108 HAS_OBJPATH = False
109
110
111 class Parameters(AnsibleF5Parameters):
112 api_attributes = []
113 returnables = []
114
115
116 class ApiParameters(Parameters):
117 pass
118
119
120 class ModuleParameters(Parameters):
121 @property
122 def direction(self):
123 if self.sync_device_to_group:
124 return 'to-group'
125 else:
126 return 'from-group'
127
128 @property
129 def sync_device_to_group(self):
130 result = flatten_boolean(self._values['sync_device_to_group'])
131 if result == 'yes':
132 return True
133 if result == 'no':
134 return False
135
136 @property
137 def sync_group_to_device(self):
138 result = flatten_boolean(self._values['sync_group_to_device'])
139 if result == 'yes':
140 return True
141 if result == 'no':
142 return False
143
144 @property
145 def force_full_push(self):
146 if self.overwrite_config:
147 return 'force-full-load-push'
148 else:
149 return ''
150
151 @property
152 def overwrite_config(self):
153 result = flatten_boolean(self._values['overwrite_config'])
154 if result == 'yes':
155 return True
156 if result == 'no':
157 return False
158
159
160 class Changes(Parameters):
161 def to_return(self):
162 result = {}
163 try:
164 for returnable in self.returnables:
165 result[returnable] = getattr(self, returnable)
166 result = self._filter_params(result)
167 except Exception:
168 raise
169 return result
170
171
172 class UsableChanges(Changes):
173 pass
174
175
176 class ReportableChanges(Changes):
177 pass
178
179
180 class Difference(object):
181 pass
182
183
184 class ModuleManager(object):
185 def __init__(self, *args, **kwargs):
186 self.module = kwargs.get('module', None)
187 self.client = F5RestClient(**self.module.params)
188 self.want = ModuleParameters(params=self.module.params)
189 self.changes = UsableChanges()
190
191 def _announce_deprecations(self, result):
192 warnings = result.pop('__warnings', [])
193 for warning in warnings:
194 self.client.module.deprecate(
195 msg=warning['msg'],
196 version=warning['version']
197 )
198
199 def exec_module(self):
200 start = datetime.now().isoformat()
201 version = tmos_version(self.client)
202 result = dict()
203
204 changed = self.present()
205
206 reportable = ReportableChanges(params=self.changes.to_return())
207 changes = reportable.to_return()
208 result.update(**changes)
209 result.update(dict(changed=changed))
210 self._announce_deprecations(result)
211 send_teem(start, self.client, self.module, version)
212 return result
213
214 def present(self):
215 if not self._device_group_exists():
216 raise F5ModuleError(
217 "The specified 'device_group' not not exist."
218 )
219 if self._sync_to_group_required():
220 raise F5ModuleError(
221 "This device group needs an initial sync. Please use "
222 "'sync_device_to_group'"
223 )
224 if self.exists():
225 return False
226 else:
227 return self.execute()
228
229 def _sync_to_group_required(self):
230 status = self._get_status_from_resource()
231 if status == 'Awaiting Initial Sync' and self.want.sync_group_to_device:
232 return True
233 return False
234
235 def _device_group_exists(self):
236 errors = [401, 403, 409, 500, 501, 502, 503, 504]
237 uri = "https://{0}:{1}/mgmt/tm/cm/device-group/{2}".format(
238 self.client.provider['server'],
239 self.client.provider['server_port'],
240 self.want.device_group
241 )
242 resp = self.client.api.get(uri)
243 try:
244 response = resp.json()
245 except ValueError as ex:
246 raise F5ModuleError(str(ex))
247
248 if resp.status == 404 or 'code' in response and response['code'] == 404:
249 return False
250 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
251 return True
252
253 if resp.status in errors or 'code' in response and response['code'] in errors:
254 if 'message' in response:
255 raise F5ModuleError(response['message'])
256 else:
257 raise F5ModuleError(resp.content)
258
259 def execute(self):
260 self.execute_on_device()
261 self._wait_for_sync()
262 return True
263
264 def exists(self):
265 status = self._get_status_from_resource()
266 if status == 'In Sync':
267 return True
268 else:
269 return False
270
271 def execute_on_device(self):
272 sync_cmd = 'config-sync {0} {1} {2}'.format(
273 self.want.direction,
274 self.want.device_group,
275 self.want.force_full_push
276 )
277 uri = "https://{0}:{1}/mgmt/tm/cm".format(
278 self.client.provider['server'],
279 self.client.provider['server_port'],
280 )
281 args = dict(
282 command='run',
283 utilCmdArgs=sync_cmd
284 )
285 resp = self.client.api.post(uri, json=args)
286
287 try:
288 response = resp.json()
289 except ValueError as ex:
290 raise F5ModuleError(str(ex))
291
292 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
293 return True
294 raise F5ModuleError(resp.content)
295
296 def _wait_for_sync(self):
297 # Wait no more than half an hour
298 for x in range(1, 180):
299 time.sleep(3)
300 status = self._get_status_from_resource()
301
302 # Changes Pending:
303 # The existing device has changes made to it that
304 # need to be sync'd to the group.
305 #
306 # Awaiting Initial Sync:
307 # This is a new device group and has not had any sync
308 # done yet. You _must_ `sync_device_to_group` in this
309 # case.
310 #
311 # Not All Devices Synced:
312 # A device group will go into this state immediately
313 # after starting the sync and stay until all devices finish.
314 #
315 if status in ['Changes Pending']:
316 details = self._get_details_from_resource()
317 self._validate_pending_status(details)
318 elif status in ['Awaiting Initial Sync', 'Not All Devices Synced']:
319 pass
320 elif status == 'In Sync':
321 return
322 elif status == 'Disconnected':
323 raise F5ModuleError(
324 "One or more devices are unreachable (disconnected). "
325 "Resolve any communication problems before attempting to sync."
326 )
327 else:
328 raise F5ModuleError(status)
329
330 def read_current_from_device(self):
331 uri = "https://{0}:{1}/mgmt/tm/cm/sync-status/".format(
332 self.client.provider['server'],
333 self.client.provider['server_port'],
334 )
335 resp = self.client.api.get(uri)
336 try:
337 response = resp.json()
338 except ValueError as ex:
339 raise F5ModuleError(str(ex))
340
341 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
342 return response
343 raise F5ModuleError(resp.content)
344
345 def _get_status_from_resource(self):
346 resource = self.read_current_from_device()
347 entries = resource['entries'].copy()
348 k, v = entries.popitem()
349 status = v['nestedStats']['entries']['status']['description']
350 return status
351
352 def _get_details_from_resource(self):
353 resource = self.read_current_from_device()
354 stats = resource['entries'].copy()
355 if HAS_OBJPATH:
356 tree = Tree(stats)
357 else:
358 raise F5ModuleError(
359 "objectpath module required, install objectpath module to continue. "
360 )
361 details = list(tree.execute('$..*["details"]["description"]'))
362 result = details[::-1]
363 return result
364
365 def _validate_pending_status(self, details):
366 """Validate the content of a pending sync operation
367
368 This is a hack. The REST API is not consistent with its 'status' values
369 so this method is here to check the returned strings from the operation
370 and see if it reported any of these inconsistencies.
371
372 :param details:
373 :raises F5ModuleError:
374 """
375 pattern1 = r'.*(?P<msg>Recommended\s+action.*)'
376 for detail in details:
377 matches = re.search(pattern1, detail)
378 if matches:
379 raise F5ModuleError(matches.group('msg'))
380
381
382 class ArgumentSpec(object):
383 def __init__(self):
384 self.supports_check_mode = False
385
386 argument_spec = dict(
387 sync_device_to_group=dict(
388 type='bool'
389 ),
390 sync_group_to_device=dict(
391 type='bool'
392 ),
393 overwrite_config=dict(
394 type='bool',
395 default='no'
396 ),
397 device_group=dict(
398 required=True
399 )
400 )
401 self.argument_spec = {}
402 self.argument_spec.update(f5_argument_spec)
403 self.argument_spec.update(argument_spec)
404
405 self.required_one_of = [
406 ['sync_device_to_group', 'sync_group_to_device']
407 ]
408 self.mutually_exclusive = [
409 ['sync_device_to_group', 'sync_group_to_device']
410 ]
411
412
413 def main():
414 spec = ArgumentSpec()
415
416 module = AnsibleModule(
417 argument_spec=spec.argument_spec,
418 supports_check_mode=spec.supports_check_mode,
419 mutually_exclusive=spec.mutually_exclusive,
420 required_one_of=spec.required_one_of
421 )
422
423 try:
424 mm = ModuleManager(module=module)
425 results = mm.exec_module()
426 module.exit_json(**results)
427 except F5ModuleError as ex:
428 module.fail_json(msg=str(ex))
429
430
431 if __name__ == '__main__':
432 main()