Debian Codegraph @

ansible_collections/community/general/plugins/modules/spectrum_model_attrs.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2021, Tyler Gates <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: spectrum_model_attrs
12 short_description: Enforce a model's attributes in CA Spectrum
13 description:
14 - This module can be used to enforce a model's attributes in CA Spectrum.
15 version_added: 2.5.0
16 author:
17 - Tyler Gates (@tgates81)
18 notes:
19 - Tested on CA Spectrum version 10.4.2.0.189.
20 - Model creation and deletion are not possible with this module. For that use M(community.general.spectrum_device) instead.
21 extends_documentation_fragment:
22 - community.general._attributes
23 attributes:
24 check_mode:
25 support: full
26 diff_mode:
27 support: none
28 options:
29 url:
30 description:
31 - URL of OneClick server.
32 type: str
33 required: true
34 url_username:
35 description:
36 - OneClick username.
37 type: str
38 required: true
39 aliases: [username]
40 url_password:
41 description:
42 - OneClick password.
43 type: str
44 required: true
45 aliases: [password]
46 use_proxy:
47 description:
48 - If V(false), it does not use a proxy, even if one is defined in an environment variable on the target hosts.
49 default: true
50 type: bool
51 name:
52 description:
53 - Model name.
54 type: str
55 required: true
56 type:
57 description:
58 - Model type.
59 type: str
60 required: true
61 validate_certs:
62 description:
63 - Validate SSL certificates. Only change this to V(false) if you can guarantee that you are talking to the correct endpoint
64 and there is no man-in-the-middle attack happening.
65 type: bool
66 default: true
67 attributes:
68 description:
69 - A list of attribute names and values to enforce.
70 - All values and parameters are case sensitive and must be provided as strings only.
71 required: true
72 type: list
73 elements: dict
74 suboptions:
75 name:
76 description:
77 - Attribute name OR hex ID.
78 - 'Currently defined names are:'
79 - C(App_Manufacturer) (C(0x230683));
80 - C(CollectionsModelNameString) (C(0x12adb));
81 - C(Condition) (C(0x1000a));
82 - C(Criticality) (C(0x1290c));
83 - C(DeviceType) (C(0x23000e));
84 - C(isManaged) (C(0x1295d));
85 - C(Model_Class) (C(0x11ee8));
86 - C(Model_Handle) (C(0x129fa));
87 - C(Model_Name) (C(0x1006e));
88 - C(Modeltype_Handle) (C(0x10001));
89 - C(Modeltype_Name) (C(0x10000));
90 - C(Network_Address) (C(0x12d7f));
91 - C(Notes) (C(0x11564));
92 - C(ServiceDesk_Asset_ID) (C(0x12db9));
93 - C(TopologyModelNameString) (C(0x129e7));
94 - C(sysDescr) (C(0x10052));
95 - C(sysName) (C(0x10b5b));
96 - C(Vendor_Name) (C(0x11570));
97 - C(Description) (C(0x230017)).
98 - Hex IDs are the direct identifiers in Spectrum and always work.
99 - 'To lookup hex IDs go to the UI: Locator -> Devices -> By Model Name -> <enter any model> -> Attributes tab.'
100 type: str
101 required: true
102 value:
103 description:
104 - Attribute value. Empty strings should be V("") or V(null).
105 type: str
106 required: true
107 """
108
109 EXAMPLES = r"""
110 - name: Enforce maintenance mode for modelxyz01 with a note about why
111 community.general.spectrum_model_attrs:
112 url: "http://oneclick.url.com"
113 username: "{{ oneclick_username }}"
114 password: "{{ oneclick_password }}"
115 name: "modelxyz01"
116 type: "Host_Device"
117 validate_certs: true
118 attributes:
119 - name: "isManaged"
120 value: "false"
121 - name: "Notes"
122 value: >-
123 MM set on {{ ansible_date_time.iso8601 }} via CO {{ CO }}
124 by {{ tower_user_name | default(ansible_user_id) }}
125 delegate_to: localhost
126 register: spectrum_model_attrs_status
127 """
128
129 RETURN = r"""
130 msg:
131 description: Informational message on the job result.
132 type: str
133 returned: always
134 sample: 'Success'
135 changed_attrs:
136 description: Dictionary of changed name or hex IDs (whichever was specified) to their new corresponding values.
137 type: dict
138 returned: always
139 sample: {"Notes": "MM set on 2021-02-03T22:04:02Z via CO CO9999 by tgates", "isManaged": "true"}
140 """
141
142
143 import json
144 import re
145 import xml.etree.ElementTree as ET
146 from urllib.parse import quote
147
148 from ansible.module_utils.basic import AnsibleModule
149 from ansible.module_utils.urls import fetch_url
150
151
152 class spectrum_model_attrs:
153 def __init__(self, module):
154 self.module = module
155 self.url = module.params["url"]
156 # If the user did not define a full path to the restul space in url:
157 # params, add what we believe it to be.
158 if not re.search("\\/.+", self.url.split("://")[1]):
159 self.url = f"{self.url.rstrip('/')}/spectrum/restful"
160 # Align these with what is defined in OneClick's UI under:
161 # Locator -> Devices -> By Model Name -> <enter any model> ->
162 # Attributes tab.
163 self.attr_map = dict(
164 App_Manufacturer=hex(0x230683),
165 CollectionsModelNameString=hex(0x12ADB),
166 Condition=hex(0x1000A),
167 Criticality=hex(0x1290C),
168 DeviceType=hex(0x23000E),
169 isManaged=hex(0x1295D),
170 Model_Class=hex(0x11EE8),
171 Model_Handle=hex(0x129FA),
172 Model_Name=hex(0x1006E),
173 Modeltype_Handle=hex(0x10001),
174 Modeltype_Name=hex(0x10000),
175 Network_Address=hex(0x12D7F),
176 Notes=hex(0x11564),
177 ServiceDesk_Asset_ID=hex(0x12DB9),
178 TopologyModelNameString=hex(0x129E7),
179 sysDescr=hex(0x10052),
180 sysName=hex(0x10B5B),
181 Vendor_Name=hex(0x11570),
182 Description=hex(0x230017),
183 )
184 self.search_qualifiers = [
185 "and",
186 "or",
187 "not",
188 "greater-than",
189 "greater-than-or-equals",
190 "less-than",
191 "less-than-or-equals",
192 "equals",
193 "equals-ignore-case",
194 "does-not-equal",
195 "does-not-equal-ignore-case",
196 "has-prefix",
197 "does-not-have-prefix",
198 "has-prefix-ignore-case",
199 "does-not-have-prefix-ignore-case",
200 "has-substring",
201 "does-not-have-substring",
202 "has-substring-ignore-case",
203 "does-not-have-substring-ignore-case",
204 "has-suffix",
205 "does-not-have-suffix",
206 "has-suffix-ignore-case",
207 "does-not-have-suffix-ignore-case",
208 "has-pcre",
209 "has-pcre-ignore-case",
210 "has-wildcard",
211 "has-wildcard-ignore-case",
212 "is-derived-from",
213 "not-is-derived-from",
214 ]
215
216 self.resp_namespace = dict(ca="http://www.ca.com/spectrum/restful/schema/response")
217
218 self.result = dict(msg="", changed_attrs=dict())
219 self.success_msg = "Success"
220
221 def build_url(self, path):
222 """
223 Build a sane Spectrum restful API URL
224 :param path: The path to append to the restful base
225 :type path: str
226 :returns: Complete restful API URL
227 :rtype: str
228 """
229
230 return f"{self.url.rstrip('/')}/{path.lstrip('/')}"
231
232 def attr_id(self, name):
233 """
234 Get attribute hex ID
235 :param name: The name of the attribute to retrieve the hex ID for
236 :type name: str
237 :returns: Translated hex ID of name, or None if no translation found
238 :rtype: str or None
239 """
240
241 try:
242 return self.attr_map[name]
243 except KeyError:
244 return None
245
246 def attr_name(self, _id):
247 """
248 Get attribute name from hex ID
249 :param _id: The hex ID to lookup a name for
250 :type _id: str
251 :returns: Translated name of hex ID, or None if no translation found
252 :rtype: str or None
253 """
254
255 for name, m_id in list(self.attr_map.items()):
256 if _id == m_id:
257 return name
258 return None
259
260 def urlencode(self, string):
261 """
262 URL Encode a string
263 :param: string: The string to URL encode
264 :type string: str
265 :returns: URL encode version of supplied string
266 :rtype: str
267 """
268
269 return quote(string, "<>%-_.!*'():?#/@&+,;=")
270
271 def update_model(self, model_handle, attrs):
272 """
273 Update a model's attributes
274 :param model_handle: The model's handle ID
275 :type model_handle: str
276 :param attrs: Model's attributes to update. {'<name/id>': '<attr>'}
277 :type attrs: dict
278 :returns: Nothing; exits on error or updates self.results
279 :rtype: None
280 """
281
282 # Build the update URL
283 update_url = self.build_url(f"/model/{model_handle}?")
284 for name, val in list(attrs.items()):
285 if val is None:
286 # None values should be converted to empty strings
287 val = ""
288 val = self.urlencode(str(val))
289 if not update_url.endswith("?"):
290 update_url += "&"
291
292 update_url += f"attr={self.attr_id(name) or name}&val={val}"
293
294 # POST to /model to update the attributes, or fail.
295 resp, info = fetch_url(
296 self.module,
297 update_url,
298 method="PUT",
299 headers={"Content-Type": "application/json", "Accept": "application/json"},
300 use_proxy=self.module.params["use_proxy"],
301 )
302 status_code = info["status"]
303 if status_code >= 400:
304 body = info["body"]
305 else:
306 body = "" if resp is None else resp.read()
307 if status_code != 200:
308 self.result["msg"] = f"HTTP PUT error {status_code}: {update_url}: {body}"
309 self.module.fail_json(**self.result)
310
311 # Load and parse the JSON response and either fail or set results.
312 json_resp = json.loads(body)
313 """
314 Example success response:
315 {'model-update-response-list':{'model-responses':{'model':{'@error':'Success','@mh':'0x1010e76','attribute':{'@error':'Success','@id':'0x1295d'}}}}}"
316 Example failure response:
317 {'model-update-response-list': {'model-responses': {'model': {'@error': 'PartialFailure', '@mh': '0x1010e76', 'attribute': {'@error-message': 'brn0vlappua001: You do not have permission to set attribute Network_Address for this model.', '@error': 'Error', '@id': '0x12d7f'}}}}}
318 """ # noqa
319 model_resp = json_resp["model-update-response-list"]["model-responses"]["model"]
320 if model_resp["@error"] != "Success":
321 # I'm not 100% confident on the expected failure structure so just
322 # dump all of ['attribute'].
323 self.result["msg"] = str(model_resp["attribute"])
324 self.module.fail_json(**self.result)
325
326 # Should be OK if we get to here, set results.
327 self.result["msg"] = self.success_msg
328 self.result["changed_attrs"].update(attrs)
329 self.result["changed"] = True
330
331 def find_model(self, search_criteria, ret_attrs=None):
332 """
333 Search for a model in /models
334 :param search_criteria: The XML <rs:search-criteria>
335 :type search_criteria: str
336 :param ret_attrs: List of attributes by name or ID to return back
337 (default is Model_Handle)
338 :type ret_attrs: list
339 returns: Dictionary mapping of ret_attrs to values: {ret_attr: ret_val}
340 rtype: dict
341 """
342
343 # If no return attributes were asked for, return Model_Handle.
344 if ret_attrs is None:
345 ret_attrs = ["Model_Handle"]
346
347 # Set the XML <rs:requested-attribute id=<id>> tags. If no hex ID
348 # is found for the name, assume it is already in hex. {name: hex ID}
349 rqstd_attrs = ""
350 for ra in ret_attrs:
351 _id = self.attr_id(ra) or ra
352 rqstd_attrs = f'{rqstd_attrs}<rs:requested-attribute id="{_id}" />'
353
354 # Build the complete XML search query for HTTP POST.
355 xml = f"""<?xml version="1.0" encoding="UTF-8"?>
356 <rs:model-request throttlesize="5"
357 xmlns:rs="http://www.ca.com/spectrum/restful/schema/request"
358 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
359 xsi:schemaLocation="http://www.ca.com/spectrum/restful/schema/request ../../../xsd/Request.xsd">
360 <rs:target-models>
361 <rs:models-search>
362 <rs:search-criteria xmlns="http://www.ca.com/spectrum/restful/schema/filter">
363 {search_criteria}
364 </rs:search-criteria>
365 </rs:models-search>
366 </rs:target-models>
367 {rqstd_attrs}
368 </rs:model-request>
369 """
370
371 # POST to /models and fail on errors.
372 url = self.build_url("/models")
373 resp, info = fetch_url(
374 self.module,
375 url,
376 data=xml,
377 method="POST",
378 use_proxy=self.module.params["use_proxy"],
379 headers={"Content-Type": "application/xml", "Accept": "application/xml"},
380 )
381 status_code = info["status"]
382 if status_code >= 400:
383 body = info["body"]
384 else:
385 body = "" if resp is None else resp.read()
386 if status_code != 200:
387 self.result["msg"] = f"HTTP POST error {status_code}: {url}: {body}"
388 self.module.fail_json(**self.result)
389
390 # Parse through the XML response and fail on any detected errors.
391 root = ET.fromstring(body)
392 total_models = int(root.attrib["total-models"])
393 error = root.attrib["error"]
394 model_responses = root.find("ca:model-responses", self.resp_namespace)
395 if total_models < 1:
396 self.result["msg"] = f"No models found matching search criteria `{search_criteria}'"
397 self.module.fail_json(**self.result)
398 elif total_models > 1:
399 self.result["msg"] = (
400 f"More than one model found ({total_models}): `{ET.tostring(model_responses, encoding='unicode')}'"
401 )
402 self.module.fail_json(**self.result)
403 if error != "EndOfResults":
404 self.result["msg"] = (
405 f"Unexpected search response `{error}': {ET.tostring(model_responses, encoding='unicode')}"
406 )
407 self.module.fail_json(**self.result)
408 model = model_responses.find("ca:model", self.resp_namespace)
409 attrs = model.findall("ca:attribute", self.resp_namespace)
410 if not attrs:
411 self.result["msg"] = "No attributes returned."
412 self.module.fail_json(**self.result)
413
414 # XML response should be successful. Iterate and set each returned
415 # attribute ID/name and value for return.
416 ret = dict()
417 for attr in attrs:
418 attr_id = attr.get("id")
419 attr_name = self.attr_name(attr_id)
420 # Note: all values except empty strings (None) are strings only!
421 attr_val = attr.text
422 key = attr_name if attr_name in ret_attrs else attr_id
423 ret[key] = attr_val
424 ret_attrs.remove(key)
425 return ret
426
427 def find_model_by_name_type(self, mname, mtype, ret_attrs=None):
428 """
429 Find a model by name and type
430 :param mname: Model name
431 :type mname: str
432 :param mtype: Model type
433 :type mtype: str
434 :param ret_attrs: List of attributes by name or ID to return back
435 (default is Model_Handle)
436 :type ret_attrs: list
437 returns: find_model(): Dictionary mapping of ret_attrs to values:
438 {ret_attr: ret_val}
439 rtype: dict
440 """
441
442 # If no return attributes were asked for, return Model_Handle.
443 if ret_attrs is None:
444 ret_attrs = ["Model_Handle"]
445
446 """This is basically as follows:
447 <filtered-models>
448 <and>
449 <equals>
450 <attribute id=...>
451 <value>...</value>
452 </attribute>
453 </equals>
454 <equals>
455 <attribute...>
456 </equals>
457 </and>
458 </filtered-models>
459 """
460
461 # Parent filter tag
462 filtered_models = ET.Element("filtered-models")
463 # Logically and
464 _and = ET.SubElement(filtered_models, "and")
465
466 # Model Name
467 MN_equals = ET.SubElement(_and, "equals")
468 Model_Name = ET.SubElement(MN_equals, "attribute", {"id": self.attr_map["Model_Name"]})
469 MN_value = ET.SubElement(Model_Name, "value")
470 MN_value.text = mname
471
472 # Model Type Name
473 MTN_equals = ET.SubElement(_and, "equals")
474 Modeltype_Name = ET.SubElement(MTN_equals, "attribute", {"id": self.attr_map["Modeltype_Name"]})
475 MTN_value = ET.SubElement(Modeltype_Name, "value")
476 MTN_value.text = mtype
477
478 return self.find_model(ET.tostring(filtered_models, encoding="unicode"), ret_attrs)
479
480 def ensure_model_attrs(self):
481 # Get a list of all requested attribute names/IDs plus Model_Handle and
482 # use them to query the values currently set. Store finding in a
483 # dictionary.
484 req_attrs = []
485 for attr in self.module.params["attributes"]:
486 req_attrs.append(attr["name"])
487 if "Model_Handle" not in req_attrs:
488 req_attrs.append("Model_Handle")
489
490 # Survey attributes currently set and store in a dict.
491 cur_attrs = self.find_model_by_name_type(self.module.params["name"], self.module.params["type"], req_attrs)
492
493 # Iterate through the requested attributes names/IDs values pair and
494 # compare with those currently set. If different, attempt to change.
495 Model_Handle = cur_attrs.pop("Model_Handle")
496 for attr in self.module.params["attributes"]:
497 req_name = attr["name"]
498 req_val = attr["value"]
499 if req_val == "":
500 # The API will return None on empty string
501 req_val = None
502 if cur_attrs[req_name] != req_val:
503 if self.module.check_mode:
504 self.result["changed_attrs"][req_name] = req_val
505 self.result["msg"] = self.success_msg
506 self.result["changed"] = True
507 continue
508 self.update_model(Model_Handle, {req_name: req_val})
509
510 self.module.exit_json(**self.result)
511
512
513 def run_module():
514 argument_spec = dict(
515 url=dict(type="str", required=True),
516 url_username=dict(type="str", required=True, aliases=["username"]),
517 url_password=dict(type="str", required=True, aliases=["password"], no_log=True),
518 validate_certs=dict(type="bool", default=True),
519 use_proxy=dict(type="bool", default=True),
520 name=dict(type="str", required=True),
521 type=dict(type="str", required=True),
522 attributes=dict(
523 type="list",
524 required=True,
525 elements="dict",
526 options=dict(name=dict(type="str", required=True), value=dict(type="str", required=True)),
527 ),
528 )
529 module = AnsibleModule(
530 supports_check_mode=True,
531 argument_spec=argument_spec,
532 )
533
534 try:
535 sm = spectrum_model_attrs(module)
536 sm.ensure_model_attrs()
537 except Exception as e:
538 module.fail_json(msg=f"Failed to ensure attribute(s) on `{module.params['name']}' with exception: {e}")
539
540
541 def main():
542 run_module()
543
544
545 if __name__ == "__main__":
546 main()