Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_gtm_global.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_gtm_global
13 short_description: Manages global GTM settings
14 description:
15 - Manages global BIG-IP GTM (now BIG-IP DNS) settings. These settings include general, load balancing, and metrics
16 related settings.
17 version_added: "1.0.0"
18 options:
19 synchronization:
20 description:
21 - Specifies whether this system is a member of a synchronization group.
22 - When you enable synchronization, the system periodically queries other systems in
23 the synchronization group to obtain and distribute configuration and metrics collection
24 updates.
25 - The synchronization group may contain systems configured as Global Traffic Manager (DNS) and
26 Link Controller systems.
27 type: bool
28 synchronization_group_name:
29 description:
30 - Specifies the name of the synchronization group to which the system belongs.
31 type: str
32 synchronize_zone_files:
33 description:
34 - Specifies the system synchronizes Domain Name System (DNS) zone files among the
35 synchronization group members.
36 type: bool
37 extends_documentation_fragment: f5networks.f5_modules.f5
38 author:
39 - Tim Rupp (@caphrim007)
40 - Wojciech Wypior (@wojtek0806)
41 '''
42
43 EXAMPLES = r'''
44 - name: Configure synchronization settings
45 bigip_gtm_global:
46 synchronization: true
47 synchronization_group_name: my-group
48 synchronize_zone_files: true
49 state: present
50 provider:
51 user: admin
52 password: secret
53 server: lb.mydomain.com
54 delegate_to: localhost
55 '''
56
57 RETURN = r'''
58 synchronization:
59 description: The synchronization setting on the system.
60 returned: changed
61 type: bool
62 sample: true
63 synchronization_group_name:
64 description: The synchronization group name.
65 returned: changed
66 type: str
67 sample: my-group
68 synchronize_zone_files:
69 description: Whether or not the system will synchronize zone files.
70 returned: changed
71 type: str
72 sample: my-group
73 '''
74 from datetime import datetime
75 from ansible.module_utils.basic import AnsibleModule
76
77 from ..module_utils.bigip import F5RestClient
78 from ..module_utils.common import (
79 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
80 )
81 from ..module_utils.icontrol import (
82 module_provisioned, tmos_version
83 )
84 from ..module_utils.teem import send_teem
85
86
87 class Parameters(AnsibleF5Parameters):
88 api_map = {
89 'synchronizationGroupName': 'synchronization_group_name',
90 'synchronizeZoneFiles': 'synchronize_zone_files',
91 }
92
93 api_attributes = [
94 'synchronizeZoneFiles',
95 'synchronizationGroupName',
96 'synchronization',
97 ]
98
99 returnables = [
100 'synchronization',
101 'synchronization_group_name',
102 'synchronize_zone_files',
103 ]
104
105 updatables = [
106 'synchronization',
107 'synchronization_group_name',
108 'synchronize_zone_files',
109 ]
110
111
112 class ApiParameters(Parameters):
113 @property
114 def synchronization(self):
115 if self._values['synchronization'] is None:
116 return None
117 elif self._values['synchronization'] == 'no':
118 return False
119 else:
120 return True
121
122 @property
123 def synchronize_zone_files(self):
124 if self._values['synchronize_zone_files'] is None:
125 return None
126 elif self._values['synchronize_zone_files'] == 'no':
127 return False
128 else:
129 return True
130
131 @property
132 def synchronization_group_name(self):
133 if self._values['synchronization_group_name'] is None:
134 return None
135 return str(self._values['synchronization_group_name'])
136
137
138 class ModuleParameters(Parameters):
139 pass
140
141
142 class Changes(Parameters):
143 def to_return(self):
144 result = {}
145 try:
146 for returnable in self.returnables:
147 result[returnable] = getattr(self, returnable)
148 result = self._filter_params(result)
149 except Exception:
150 raise
151 return result
152
153
154 class UsableChanges(Changes):
155 @property
156 def synchronization(self):
157 if self._values['synchronization'] is None:
158 return None
159 elif self._values['synchronization'] is False:
160 return 'no'
161 else:
162 return 'yes'
163
164 @property
165 def synchronize_zone_files(self):
166 if self._values['synchronize_zone_files'] is None:
167 return None
168 elif self._values['synchronize_zone_files'] is False:
169 return 'no'
170 else:
171 return 'yes'
172
173
174 class ReportableChanges(Changes):
175 pass
176
177
178 class Difference(object):
179 def __init__(self, want, have=None):
180 self.want = want
181 self.have = have
182
183 def compare(self, param):
184 try:
185 result = getattr(self, param)
186 return result
187 except AttributeError:
188 return self.__default(param)
189
190 def __default(self, param):
191 attr1 = getattr(self.want, param)
192 try:
193 attr2 = getattr(self.have, param)
194 if attr1 != attr2:
195 return attr1
196 except AttributeError:
197 return attr1
198
199 @property
200 def synchronization_group_name(self):
201 if self.want.synchronization_group_name is None:
202 return None
203 if self.want.synchronization_group_name == '' and self.have.synchronization_group_name is None:
204 return None
205 if self.want.synchronization_group_name != self.have.synchronization_group_name:
206 return self.want.synchronization_group_name
207
208
209 class ModuleManager(object):
210 def __init__(self, *args, **kwargs):
211 self.module = kwargs.get('module', None)
212 self.client = F5RestClient(**self.module.params)
213 self.want = ModuleParameters(params=self.module.params)
214 self.have = ApiParameters()
215 self.changes = UsableChanges()
216
217 def _update_changed_options(self):
218 diff = Difference(self.want, self.have)
219 updatables = Parameters.updatables
220 changed = dict()
221 for k in updatables:
222 change = diff.compare(k)
223 if change is None:
224 continue
225 else:
226 if isinstance(change, dict):
227 changed.update(change)
228 else:
229 changed[k] = change
230 if changed:
231 self.changes = UsableChanges(params=changed)
232 return True
233 return False
234
235 def _announce_deprecations(self, result):
236 warnings = result.pop('__warnings', [])
237 for warning in warnings:
238 self.client.module.deprecate(
239 msg=warning['msg'],
240 version=warning['version']
241 )
242
243 def exec_module(self):
244 start = datetime.now().isoformat()
245 version = tmos_version(self.client)
246 if not module_provisioned(self.client, 'gtm'):
247 raise F5ModuleError(
248 "GTM must be provisioned to use this module."
249 )
250 result = dict()
251
252 changed = self.present()
253
254 reportable = ReportableChanges(params=self.changes.to_return())
255 changes = reportable.to_return()
256 result.update(**changes)
257 result.update(dict(changed=changed))
258 self._announce_deprecations(result)
259 send_teem(start, self.client, self.module, version)
260 return result
261
262 def present(self):
263 return self.update()
264
265 def update(self):
266 self.have = self.read_current_from_device()
267 if not self.should_update():
268 return False
269 if self.module.check_mode:
270 return True
271 self.update_on_device()
272 return True
273
274 def should_update(self):
275 result = self._update_changed_options()
276 if result:
277 return True
278 return False
279
280 def update_on_device(self):
281 params = self.changes.api_params()
282 uri = "https://{0}:{1}/mgmt/tm/gtm/global-settings/general/".format(
283 self.client.provider['server'],
284 self.client.provider['server_port'],
285 )
286 resp = self.client.api.patch(uri, json=params)
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 read_current_from_device(self):
297 uri = "https://{0}:{1}/mgmt/tm/gtm/global-settings/general/".format(
298 self.client.provider['server'],
299 self.client.provider['server_port'],
300 )
301 resp = self.client.api.get(uri)
302 try:
303 response = resp.json()
304 except ValueError as ex:
305 raise F5ModuleError(str(ex))
306
307 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
308 return ApiParameters(params=response)
309 raise F5ModuleError(resp.content)
310
311
312 class ArgumentSpec(object):
313 def __init__(self):
314 self.supports_check_mode = True
315 argument_spec = dict(
316 synchronization=dict(type='bool'),
317 synchronization_group_name=dict(),
318 synchronize_zone_files=dict(type='bool')
319 )
320 self.argument_spec = {}
321 self.argument_spec.update(f5_argument_spec)
322 self.argument_spec.update(argument_spec)
323
324
325 def main():
326 spec = ArgumentSpec()
327
328 module = AnsibleModule(
329 argument_spec=spec.argument_spec,
330 supports_check_mode=spec.supports_check_mode,
331 )
332
333 try:
334 mm = ModuleManager(module=module)
335 results = mm.exec_module()
336 module.exit_json(**results)
337 except F5ModuleError as ex:
338 module.fail_json(msg=str(ex))
339
340
341 if __name__ == '__main__':
342 main()