Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Renato Orgito <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: spectrum_device
11 short_description: Creates/deletes devices in CA Spectrum
12 description:
13 - This module allows you to create and delete devices in CA Spectrum U(https://www.ca.com/us/products/ca-spectrum.html).
14 - Tested on CA Spectrum 9.4.2, 10.1.1 and 10.2.1.
15 author: "Renato Orgito (@orgito)"
16 extends_documentation_fragment:
17 - community.general._attributes
18 attributes:
19 check_mode:
20 support: full
21 diff_mode:
22 support: none
23 options:
24 device:
25 type: str
26 aliases: [host, name]
27 required: true
28 description:
29 - IP address of the device.
30 - If a hostname is given, it is resolved to the IP address.
31 community:
32 type: str
33 description:
34 - SNMP community used for device discovery.
35 - Required when O(state=present).
36 required: true
37 landscape:
38 type: str
39 required: true
40 description:
41 - Landscape handle of the SpectroServer to which add or remove the device.
42 state:
43 type: str
44 description:
45 - On V(present) creates the device when it does not exist.
46 - On V(absent) removes the device when it exists.
47 choices: ['present', 'absent']
48 default: 'present'
49 url:
50 type: str
51 aliases: [oneclick_url]
52 required: true
53 description:
54 - HTTP, HTTPS URL of the Oneclick server in the form V((http|https\)://host.domain[:port]).
55 url_username:
56 type: str
57 aliases: [oneclick_user]
58 required: true
59 description:
60 - Oneclick user name.
61 url_password:
62 type: str
63 aliases: [oneclick_password]
64 required: true
65 description:
66 - Oneclick user password.
67 use_proxy:
68 description:
69 - If V(false), it does not use a proxy, even if one is defined in an environment variable on the target hosts.
70 default: true
71 type: bool
72 validate_certs:
73 description:
74 - If V(false), SSL certificates are not validated. This should only be used on personally controlled sites using self-signed
75 certificates.
76 default: true
77 type: bool
78 agentport:
79 type: int
80 description:
81 - UDP port used for SNMP discovery.
82 default: 161
83 notes:
84 - The devices are created inside the I(Universe) container of the specified landscape.
85 - All the operations are performed only on the specified landscape.
86 """
87
88 EXAMPLES = r"""
89 - name: Add device to CA Spectrum
90 local_action:
91 module: spectrum_device
92 device: '{{ ansible_host }}'
93 community: secret
94 landscape: '0x100000'
95 oneclick_url: http://oneclick.example.com:8080
96 oneclick_user: username
97 oneclick_password: password
98 state: present
99
100
101 - name: Remove device from CA Spectrum
102 local_action:
103 module: spectrum_device
104 device: '{{ ansible_host }}'
105 landscape: '{{ landscape_handle }}'
106 oneclick_url: http://oneclick.example.com:8080
107 oneclick_user: username
108 oneclick_password: password
109 use_proxy: false
110 state: absent
111 """
112
113 RETURN = r"""
114 device:
115 description: Device data when O(state=present).
116 returned: success
117 type: dict
118 sample:
119 {
120 "model_handle": "0x1007ab",
121 "landscape": "0x100000",
122 "address": "10.10.5.1"
123 }
124 """
125
126 import xml.etree.ElementTree as ET
127 from socket import gaierror, gethostbyname
128
129 from ansible.module_utils.basic import AnsibleModule
130 from ansible.module_utils.urls import fetch_url
131
132
133 def request(resource, xml=None, method=None):
134 headers = {"Content-Type": "application/xml", "Accept": "application/xml"}
135
136 url = f"{module.params['oneclick_url']}/spectrum/restful/{resource}"
137
138 response, info = fetch_url(module, url, data=xml, method=method, headers=headers, timeout=45)
139
140 if info["status"] == 401:
141 module.fail_json(msg="failed to authenticate to Oneclick server")
142
143 if info["status"] not in (200, 201, 204):
144 module.fail_json(msg=info["msg"])
145
146 return response.read()
147
148
149 def post(resource, xml=None):
150 return request(resource, xml=xml, method="POST")
151
152
153 def delete(resource):
154 return request(resource, xml=None, method="DELETE")
155
156
157 def get_ip():
158 try:
159 device_ip = gethostbyname(module.params.get("device"))
160 except gaierror:
161 module.fail_json(msg=f"failed to resolve device ip address for '{module.params.get('device')}'")
162
163 return device_ip
164
165
166 def get_device(device_ip):
167 """Query OneClick for the device using the IP Address"""
168 resource = "/models"
169 landscape_min = f"0x{int(module.params.get('landscape'), 16):x}"
170 landscape_max = f"0x{int(module.params.get('landscape'), 16) + 0x100000:x}"
171
172 xml = f"""<?xml version="1.0" encoding="UTF-8"?>
173 <rs:model-request throttlesize="5"
174 xmlns:rs="http://www.ca.com/spectrum/restful/schema/request"
175 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
176 xsi:schemaLocation="http://www.ca.com/spectrum/restful/schema/request ../../../xsd/Request.xsd">
177 <rs:target-models>
178 <rs:models-search>
179 <rs:search-criteria xmlns="http://www.ca.com/spectrum/restful/schema/filter">
180 <action-models>
181 <filtered-models>
182 <and>
183 <equals>
184 <model-type>SearchManager</model-type>
185 </equals>
186 <greater-than>
187 <attribute id="0x129fa">
188 <value>{landscape_min}</value>
189 </attribute>
190 </greater-than>
191 <less-than>
192 <attribute id="0x129fa">
193 <value>{landscape_max}</value>
194 </attribute>
195 </less-than>
196 </and>
197 </filtered-models>
198 <action>FIND_DEV_MODELS_BY_IP</action>
199 <attribute id="AttributeID.NETWORK_ADDRESS">
200 <value>{device_ip}</value>
201 </attribute>
202 </action-models>
203 </rs:search-criteria>
204 </rs:models-search>
205 </rs:target-models>
206 <rs:requested-attribute id="0x12d7f" /> <!--Network Address-->
207 </rs:model-request>
208 """
209
210 result = post(resource, xml=xml)
211
212 root = ET.fromstring(result)
213
214 if root.get("total-models") == "0":
215 return None
216
217 namespace = dict(ca="http://www.ca.com/spectrum/restful/schema/response")
218
219 # get the first device
220 model = root.find("ca:model-responses", namespace).find("ca:model", namespace)
221
222 if model.get("error"):
223 module.fail_json(msg=f"error checking device: {model.get('error')}")
224
225 # get the attributes
226 model_handle = model.get("mh")
227
228 model_address = model.find('./*[@id="0x12d7f"]').text
229
230 # derive the landscape handler from the model handler of the device
231 model_landscape = f"0x{int(model_handle, 16) // 0x100000 * 0x100000:x}"
232
233 device = dict(model_handle=model_handle, address=model_address, landscape=model_landscape)
234
235 return device
236
237
238 def add_device():
239 device_ip = get_ip()
240 device = get_device(device_ip)
241
242 if device:
243 module.exit_json(changed=False, device=device)
244
245 if module.check_mode:
246 device = dict(model_handle=None, address=device_ip, landscape=f"0x{int(module.params.get('landscape'), 16):x}")
247 module.exit_json(changed=True, device=device)
248
249 resource = f"model?ipaddress={device_ip}&commstring={module.params.get('community')}"
250 resource += f"&landscapeid={module.params.get('landscape')}"
251
252 if module.params.get("agentport", None):
253 resource += f"&agentport={module.params.get('agentport', 161)}"
254
255 result = post(resource)
256 root = ET.fromstring(result)
257
258 if root.get("error") != "Success":
259 module.fail_json(msg=root.get("error-message"))
260
261 namespace = dict(ca="http://www.ca.com/spectrum/restful/schema/response")
262 model = root.find("ca:model", namespace)
263
264 model_handle = model.get("mh")
265 model_landscape = f"0x{int(model_handle, 16) // 0x100000 * 0x100000:x}"
266
267 device = dict(
268 model_handle=model_handle,
269 address=device_ip,
270 landscape=model_landscape,
271 )
272
273 module.exit_json(changed=True, device=device)
274
275
276 def remove_device():
277 device_ip = get_ip()
278 device = get_device(device_ip)
279
280 if device is None:
281 module.exit_json(changed=False)
282
283 if module.check_mode:
284 module.exit_json(changed=True)
285
286 resource = f"/model/{device['model_handle']}"
287 result = delete(resource)
288
289 root = ET.fromstring(result)
290
291 namespace = dict(ca="http://www.ca.com/spectrum/restful/schema/response")
292 error = root.find("ca:error", namespace).text
293
294 if error != "Success":
295 error_message = root.find("ca:error-message", namespace).text
296 module.fail_json(msg=f"{error} {error_message}")
297
298 module.exit_json(changed=True)
299
300
301 def main():
302 global module
303 module = AnsibleModule(
304 argument_spec=dict(
305 device=dict(required=True, aliases=["host", "name"]),
306 landscape=dict(required=True),
307 state=dict(choices=["present", "absent"], default="present"),
308 community=dict(required=True, no_log=True), # @TODO remove the 'required', given the required_if ?
309 agentport=dict(type="int", default=161),
310 url=dict(required=True, aliases=["oneclick_url"]),
311 url_username=dict(required=True, aliases=["oneclick_user"]),
312 url_password=dict(required=True, no_log=True, aliases=["oneclick_password"]),
313 use_proxy=dict(type="bool", default=True),
314 validate_certs=dict(type="bool", default=True),
315 ),
316 required_if=[("state", "present", ["community"])],
317 supports_check_mode=True,
318 )
319
320 if module.params.get("state") == "present":
321 add_device()
322 else:
323 remove_device()
324
325
326 if __name__ == "__main__":
327 main()