Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_snmp.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_snmp
13 short_description: Manipulate general SNMP settings on a BIG-IP
14 description:
15 - Manipulate general SNMP settings on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 allowed_addresses:
19 description:
20 - Configures the IP addresses of the SNMP clients from which the snmpd
21 daemon accepts requests.
22 - This value can be hostnames, IP addresses, or IP networks.
23 - You may specify a single list item of C(default) to set the value back
24 to the system default of C(127.0.0.0/8).
25 - You can remove all allowed addresses by either providing the word C(none), or
26 by providing the empty string C("").
27 type: raw
28 contact:
29 description:
30 - Specifies the name of the person who administers the SNMP
31 service for this system.
32 type: str
33 agent_status_traps:
34 description:
35 - When C(enabled), ensures the system sends a trap whenever the
36 SNMP agent starts running or stops running. This is usually enabled
37 by default on a BIG-IP.
38 type: str
39 choices:
40 - enabled
41 - disabled
42 agent_authentication_traps:
43 description:
44 - When C(enabled), ensures the system sends authentication warning
45 traps to the trap destinations. This is usually disabled by default on
46 a BIG-IP.
47 type: str
48 choices:
49 - enabled
50 - disabled
51 device_warning_traps:
52 description:
53 - When C(enabled), ensures the system sends device warning traps
54 to the trap destinations. This is usually enabled by default on a
55 BIG-IP.
56 type: str
57 choices:
58 - enabled
59 - disabled
60 location:
61 description:
62 - Specifies the description of this system's physical location.
63 type: str
64 extends_documentation_fragment: f5networks.f5_modules.f5
65 author:
66 - Tim Rupp (@caphrim007)
67 - Wojciech Wypior (@wojtek0806)
68 '''
69
70 EXAMPLES = r'''
71 - name: Set snmp contact
72 bigip_snmp:
73 contact: Joe User
74 provider:
75 password: secret
76 server: lb.mydomain.com
77 user: admin
78 delegate_to: localhost
79
80 - name: Set snmp location
81 bigip_snmp:
82 location: US West 1
83 provider:
84 password: secret
85 server: lb.mydomain.com
86 user: admin
87 delegate_to: localhost
88 '''
89
90 RETURN = r'''
91 agent_status_traps:
92 description: Value of the agent status traps.
93 returned: changed
94 type: str
95 sample: enabled
96 agent_authentication_traps:
97 description: Value of the authentication status traps.
98 returned: changed
99 type: str
100 sample: enabled
101 device_warning_traps:
102 description: Value of the warning status traps.
103 returned: changed
104 type: str
105 sample: enabled
106 contact:
107 description: The new value for the person who administers SNMP on the device.
108 returned: changed
109 type: str
110 sample: Joe User
111 location:
112 description: The new value for the system's physical location.
113 returned: changed
114 type: str
115 sample: US West 1a
116 allowed_addresses:
117 description: The new allowed addresses for SNMP client connections.
118 returned: changed
119 type: list
120 sample: ['127.0.0.0/8', 'foo.bar.com', '10.10.10.10']
121 '''
122 from datetime import datetime
123
124 from ansible.module_utils.basic import AnsibleModule
125 from ansible.module_utils.six import string_types
126
127 from ipaddress import ip_network
128
129 from ..module_utils.bigip import F5RestClient
130 from ..module_utils.common import (
131 F5ModuleError, AnsibleF5Parameters, f5_argument_spec, is_valid_hostname
132 )
133 from ..module_utils.icontrol import tmos_version
134 from ..module_utils.teem import send_teem
135
136
137 class Parameters(AnsibleF5Parameters):
138 api_map = {
139 'agentTrap': 'agent_status_traps',
140 'authTrap': 'agent_authentication_traps',
141 'bigipTraps': 'device_warning_traps',
142 'sysLocation': 'location',
143 'sysContact': 'contact',
144 'allowedAddresses': 'allowed_addresses',
145 }
146
147 updatables = [
148 'agent_status_traps',
149 'agent_authentication_traps',
150 'device_warning_traps',
151 'location',
152 'contact',
153 'allowed_addresses',
154 ]
155
156 returnables = [
157 'agent_status_traps',
158 'agent_authentication_traps',
159 'device_warning_traps',
160 'location', 'contact',
161 'allowed_addresses',
162 ]
163
164 api_attributes = [
165 'agentTrap',
166 'authTrap',
167 'bigipTraps',
168 'sysLocation',
169 'sysContact',
170 'allowedAddresses',
171 ]
172
173
174 class ApiParameters(Parameters):
175 @property
176 def allowed_addresses(self):
177 if self._values['allowed_addresses'] is None:
178 return None
179 result = list(set(self._values['allowed_addresses']))
180 result.sort()
181 return result
182
183
184 class ModuleParameters(Parameters):
185 @property
186 def allowed_addresses(self):
187 if self._values['allowed_addresses'] is None:
188 return None
189 result = []
190 addresses = self._values['allowed_addresses']
191 if isinstance(addresses, string_types):
192 if addresses in ['', 'none']:
193 return []
194 else:
195 addresses = [addresses]
196 if len(addresses) == 1 and addresses[0] in ['default', '']:
197 result = ['127.0.0.0/8']
198 return result
199 for address in addresses:
200 try:
201 # Check for valid IPv4 or IPv6 entries
202 ip_network(u'%s' % str(address))
203 result.append(address)
204 except ValueError:
205 # else fallback to checking reasonably well formatted hostnames
206 if is_valid_hostname(address):
207 result.append(str(address))
208 continue
209 raise F5ModuleError(
210 "The provided 'allowed_address' value {0} is not a valid IP or hostname".format(address)
211 )
212 result = list(set(result))
213 result.sort()
214 return result
215
216
217 class Changes(Parameters):
218 def to_return(self):
219 result = {}
220 try:
221 for returnable in self.returnables:
222 result[returnable] = getattr(self, returnable)
223 result = self._filter_params(result)
224 except Exception:
225 pass
226 return result
227
228
229 class UsableChanges(Changes):
230 pass
231
232
233 class ReportableChanges(Changes):
234 pass
235
236
237 class Difference(object):
238 def __init__(self, want, have=None):
239 self.want = want
240 self.have = have
241
242 def compare(self, param):
243 try:
244 result = getattr(self, param)
245 return result
246 except AttributeError:
247 return self.__default(param)
248
249 def __default(self, param):
250 attr1 = getattr(self.want, param)
251 try:
252 attr2 = getattr(self.have, param)
253 if attr1 != attr2:
254 return attr1
255 except AttributeError:
256 return attr1
257
258 @property
259 def allowed_addresses(self):
260 if self.want.allowed_addresses is None:
261 return None
262 if self.have.allowed_addresses is None:
263 if self.want.allowed_addresses:
264 return self.want.allowed_addresses
265 return None
266 want = set(self.want.allowed_addresses)
267 have = set(self.have.allowed_addresses)
268 if want != have:
269 result = list(want)
270 result.sort()
271 return result
272
273
274 class ModuleManager(object):
275 def __init__(self, *args, **kwargs):
276 self.module = kwargs.get('module', None)
277 self.client = F5RestClient(**self.module.params)
278 self.have = ApiParameters()
279 self.want = ModuleParameters(params=self.module.params)
280 self.changes = UsableChanges()
281
282 def _update_changed_options(self):
283 diff = Difference(self.want, self.have)
284 updatables = Parameters.updatables
285 changed = dict()
286 for k in updatables:
287 change = diff.compare(k)
288 if change is None:
289 continue
290 else:
291 if isinstance(change, dict):
292 changed.update(change)
293 else:
294 changed[k] = change
295 if changed:
296 self.changes = UsableChanges(params=changed)
297 return True
298 return False
299
300 def exec_module(self):
301 start = datetime.now().isoformat()
302 version = tmos_version(self.client)
303 result = dict()
304
305 changed = self.update()
306
307 reportable = ReportableChanges(params=self.changes.to_return())
308 changes = reportable.to_return()
309 result.update(**changes)
310 result.update(dict(changed=changed))
311 self._announce_deprecations(result)
312 send_teem(start, self.client, self.module, version)
313 return result
314
315 def _announce_deprecations(self, result):
316 warnings = result.pop('__warnings', [])
317 for warning in warnings:
318 self.module.deprecate(
319 msg=warning['msg'],
320 version=warning['version']
321 )
322
323 def should_update(self):
324 result = self._update_changed_options()
325 if result:
326 return True
327 return False
328
329 def update(self):
330 self.have = self.read_current_from_device()
331 if not self.should_update():
332 return False
333 if self.module.check_mode:
334 return True
335 self.update_on_device()
336 return True
337
338 def read_current_from_device(self):
339 uri = "https://{0}:{1}/mgmt/tm/sys/snmp/".format(
340 self.client.provider['server'],
341 self.client.provider['server_port'],
342 )
343 resp = self.client.api.get(uri)
344 try:
345 response = resp.json()
346 except ValueError as ex:
347 raise F5ModuleError(str(ex))
348
349 if 'code' in response and response['code'] == 400:
350 if 'message' in response:
351 raise F5ModuleError(response['message'])
352 else:
353 raise F5ModuleError(resp.content)
354 return ApiParameters(params=response)
355
356 def update_on_device(self):
357 params = self.changes.api_params()
358 uri = "https://{0}:{1}/mgmt/tm/sys/snmp/".format(
359 self.client.provider['server'],
360 self.client.provider['server_port'],
361 )
362 resp = self.client.api.patch(uri, json=params)
363 try:
364 response = resp.json()
365 except ValueError as ex:
366 raise F5ModuleError(str(ex))
367
368 if 'code' in response and response['code'] == 400:
369 if 'message' in response:
370 raise F5ModuleError(response['message'])
371 else:
372 raise F5ModuleError(resp.content)
373
374
375 class ArgumentSpec(object):
376 def __init__(self):
377 self.supports_check_mode = True
378 self.choices = ['enabled', 'disabled']
379 argument_spec = dict(
380 contact=dict(),
381 agent_status_traps=dict(
382 choices=self.choices
383 ),
384 agent_authentication_traps=dict(
385 choices=self.choices
386 ),
387 device_warning_traps=dict(
388 choices=self.choices
389 ),
390 location=dict(),
391 allowed_addresses=dict(type='raw')
392 )
393 self.argument_spec = {}
394 self.argument_spec.update(f5_argument_spec)
395 self.argument_spec.update(argument_spec)
396
397
398 def main():
399 spec = ArgumentSpec()
400
401 module = AnsibleModule(
402 argument_spec=spec.argument_spec,
403 supports_check_mode=spec.supports_check_mode
404 )
405
406 try:
407 mm = ModuleManager(module=module)
408 results = mm.exec_module()
409 module.exit_json(**results)
410 except F5ModuleError as ex:
411 module.fail_json(msg=str(ex))
412
413
414 if __name__ == '__main__':
415 main()