Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_device_group.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 10.0.0
7 # Copyright (C) 2021-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
8
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10 #
11
12 from __future__ import (absolute_import, division, print_function)
13
14 __metaclass__ = type
15
16 DOCUMENTATION = """
17 ---
18 module: ome_device_group
19 short_description: Add or remove device(s) from a static device group on OpenManage Enterprise
20 version_added: "3.3.0"
21 description: This module allows to add or remove device(s) from a static device group on OpenManage Enterprise.
22 extends_documentation_fragment:
23 - dellemc.openmanage.oment_auth_options
24 options:
25 state:
26 type: str
27 description:
28 - C(present) allows to add the device(s) to a static device group.
29 - C(absent) allows to remove the device(s) from a static device group.
30 choices: [present, absent]
31 default: present
32 name:
33 type: str
34 description:
35 - Name of the static group.
36 - I(name) is mutually exclusive with I(group_id).
37 group_id:
38 type: int
39 description:
40 - ID of the static device.
41 - I(group_id) is mutually exclusive with I(name).
42 device_ids:
43 type: list
44 elements: int
45 description:
46 - List of ID(s) of the device(s) to be added or removed from the device group.
47 - I(device_ids) is mutually exclusive with I(device_service_tags) and I(ip_addresses).
48 device_service_tags:
49 type: list
50 elements: str
51 description:
52 - List of service tag(s) of the device(s) to be added or removed from the device group.
53 - I(device_service_tags) is mutually exclusive with I(device_ids) and I(ip_addresses).
54 ip_addresses:
55 type: list
56 elements: str
57 description:
58 - List of IPs of the device(s) to be added or removed from the device group.
59 - I(ip_addresses) is mutually exclusive with I(device_ids) and I(device_service_tags).
60 - "Supported IP address range formats:"
61 - " - 192.35.0.1"
62 - " - 10.36.0.0-192.36.0.255"
63 - " - 192.37.0.0/24"
64 - " - fe80::ffff:ffff:ffff:ffff"
65 - " - fe80::ffff:192.0.2.0/125"
66 - " - fe80::ffff:ffff:ffff:1111-fe80::ffff:ffff:ffff:ffff"
67 - C(NOTE) Hostname is not supported.
68 - C(NOTE) I(ip_addresses) requires python's netaddr packages to work on IP Addresses.
69 - C(NOTE) This module reports success even if one of the IP addresses provided in the I(ip_addresses) list is
70 available in OpenManage Enterprise.The module reports failure only if none of the IP addresses provided in the
71 list are available in OpenManage Enterprise.
72 requirements:
73 - "python >= 3.9.6"
74 - "netaddr >= 0.7.19"
75 author:
76 - "Felix Stephen (@felixs88)"
77 - "Sajna Shetty(@Sajna-Shetty)"
78 - "Abhishek Sinha (@Abhishek-Dell)"
79 - "Sapana Gupta (@sapana05)"
80 notes:
81 - Run this module from a system that has direct access to Dell OpenManage Enterprise.
82 - This module supports C(check_mode).
83 """
84
85 EXAMPLES = """
86 ---
87 - name: Add devices to a static device group by using the group name and device IDs
88 dellemc.openmanage.ome_device_group:
89 hostname: "192.168.0.1"
90 username: "username"
91 password: "password"
92 ca_path: "/path/to/ca_cert.pem"
93 name: "Storage Services"
94 device_ids:
95 - 11111
96 - 11112
97 - 11113
98
99 - name: Add devices to a static device group by using the group name and device service tags
100 dellemc.openmanage.ome_device_group:
101 hostname: "192.168.0.1"
102 username: "username"
103 password: "password"
104 ca_path: "/path/to/ca_cert.pem"
105 name: "Storage Services"
106 device_service_tags:
107 - GHRT2RL
108 - KJHDF3S
109 - LKIJNG6
110
111 - name: Add devices to a static device group by using the group ID and device service tags
112 dellemc.openmanage.ome_device_group:
113 hostname: "192.168.0.1"
114 username: "username"
115 password: "password"
116 ca_path: "/path/to/ca_cert.pem"
117 group_id: 12345
118 device_service_tags:
119 - GHRT2RL
120 - KJHDF3S
121
122 - name: Add devices to a static device group by using the group name and IPv4 addresses
123 dellemc.openmanage.ome_device_group:
124 hostname: "192.168.0.1"
125 username: "username"
126 password: "password"
127 ca_path: "/path/to/ca_cert.pem"
128 name: "Storage Services"
129 ip_addresses:
130 - 192.35.0.1
131 - 192.35.0.5
132
133 - name: Add devices to a static device group by using the group ID and IPv6 addresses
134 dellemc.openmanage.ome_device_group:
135 hostname: "192.168.0.1"
136 username: "username"
137 password: "password"
138 ca_path: "/path/to/ca_cert.pem"
139 group_id: 12345
140 ip_addresses:
141 - fe80::ffff:ffff:ffff:ffff
142 - fe80::ffff:ffff:ffff:2222
143
144 - name: Add devices to a static device group by using the group ID and supported IPv4 and IPv6 address formats.
145 dellemc.openmanage.ome_device_group:
146 hostname: "192.168.0.1"
147 username: "username"
148 password: "password"
149 ca_path: "/path/to/ca_cert.pem"
150 group_id: 12345
151 ip_addresses:
152 - 192.35.0.1
153 - 10.36.0.0-192.36.0.255
154 - 192.37.0.0/24
155 - fe80::ffff:ffff:ffff:ffff
156 - ::ffff:192.0.2.0/125
157 - fe80::ffff:ffff:ffff:1111-fe80::ffff:ffff:ffff:ffff
158
159 - name: Remove devices from a static device group by using the group name and device IDs
160 dellemc.openmanage.ome_device_group:
161 hostname: "192.168.0.1"
162 username: "username"
163 password: "password"
164 ca_path: "/path/to/ca_cert.pem"
165 state: "absent"
166 name: "Storage Services"
167 device_ids:
168 - 11111
169 - 11112
170 - 11113
171
172 - name: Remove devices from a static device group by using the group name and device service tags
173 dellemc.openmanage.ome_device_group:
174 hostname: "192.168.0.1"
175 username: "username"
176 password: "password"
177 ca_path: "/path/to/ca_cert.pem"
178 state: "absent"
179 name: "Storage Services"
180 device_service_tags:
181 - GHRT2RL
182 - KJHDF3S
183 - LKIJNG6
184
185 - name: Remove devices from a static device group by using the group ID and device service tags
186 dellemc.openmanage.ome_device_group:
187 hostname: "192.168.0.1"
188 username: "username"
189 password: "password"
190 ca_path: "/path/to/ca_cert.pem"
191 state: "absent"
192 group_id: 12345
193 device_service_tags:
194 - GHRT2RL
195 - KJHDF3S
196
197 - name: Remove devices from a static device group by using the group name and IPv4 addresses
198 dellemc.openmanage.ome_device_group:
199 hostname: "192.168.0.1"
200 username: "username"
201 password: "password"
202 ca_path: "/path/to/ca_cert.pem"
203 state: "absent"
204 name: "Storage Services"
205 ip_addresses:
206 - 192.35.0.1
207 - 192.35.0.5
208
209 - name: Remove devices from a static device group by using the group ID and IPv6 addresses
210 dellemc.openmanage.ome_device_group:
211 hostname: "192.168.0.1"
212 username: "username"
213 password: "password"
214 ca_path: "/path/to/ca_cert.pem"
215 state: "absent"
216 group_id: 12345
217 ip_addresses:
218 - fe80::ffff:ffff:ffff:ffff
219 - fe80::ffff:ffff:ffff:2222
220
221 - name: Remove devices from a static device group by using the group ID and supported IPv4 and IPv6 address formats.
222 dellemc.openmanage.ome_device_group:
223 hostname: "192.168.0.1"
224 username: "username"
225 password: "password"
226 ca_path: "/path/to/ca_cert.pem"
227 state: "absent"
228 group_id: 12345
229 ip_addresses:
230 - 192.35.0.1
231 - 10.36.0.0-192.36.0.255
232 - 192.37.0.0/24
233 - fe80::ffff:ffff:ffff:ffff
234 - ::ffff:192.0.2.0/125
235 - fe80::ffff:ffff:ffff:1111-fe80::ffff:ffff:ffff:ffff
236 """
237
238
239 RETURN = """
240 ---
241 msg:
242 type: str
243 description: Overall status of the device group settings.
244 returned: always
245 sample:
246 - "Successfully added member(s) to the device group."
247 group_id:
248 type: int
249 description: ID of the group.
250 returned: success
251 sample: 21078
252 ip_addresses_added:
253 type: list
254 description: IP Addresses which are added to the device group.
255 returned: success
256 sample: 21078
257 error_info:
258 description: Details of the HTTP Error.
259 returned: on HTTP error
260 type: dict
261 sample: {
262 "error": {
263 "code": "Base.1.0.GeneralError",
264 "message": "A general error has occurred. See ExtendedInfo for more information.",
265 "@Message.ExtendedInfo": [
266 {
267 "MessageId": "GEN1234",
268 "RelatedProperties": [],
269 "Message": "Unable to process the request because an error occurred.",
270 "MessageArgs": [],
271 "Severity": "Critical",
272 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
273 }
274 ]
275 }
276 }
277 """
278
279 import json
280 from ssl import SSLError
281 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
282 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
283 from ansible.module_utils.urls import ConnectionError
284
285 try:
286 from netaddr import IPAddress, IPNetwork, IPRange
287 from netaddr.core import AddrFormatError
288
289 HAS_NETADDR = True
290 except ImportError:
291 HAS_NETADDR = False
292
293 GROUP_URI = "GroupService/Groups"
294 DEVICE_URI = "DeviceService/Devices"
295 ADD_MEMBER_URI = "GroupService/Actions/GroupService.AddMemberDevices"
296 REMOVE_MEMBER_URI = "GroupService/Actions/GroupService.RemoveMemberDevices"
297 ADD_STATIC_GROUP_MESSAGE = "Devices can be added only to the static device groups created using OpenManage Enterprise."
298 REMOVE_STATIC_GROUP_MESSAGE = "Devices can be removed only from the static device groups created using OpenManage Enterprise."
299 NETADDR_ERROR = "The module requires python's netaddr be installed on the ansible controller to work on IP Addresses."
300 INVALID_IP_FORMAT = "The format {0} of the IP address provided is not supported or invalid."
301 IP_NOT_EXISTS = "The IP addresses provided do not exist in OpenManage Enterprise."
302
303
304 def validate_group(group_resp, module, identifier, identifier_val):
305 if not group_resp:
306 module.exit_json(msg="Unable to complete the operation because the entered "
307 "target group {identifier} '{val}' is invalid.".format(identifier=identifier,
308 val=identifier_val), failed=True)
309 system_groups = group_resp["TypeId"]
310 membership_id = group_resp["MembershipTypeId"]
311 if system_groups != 3000 or (system_groups == 3000 and membership_id == 24):
312 msg = ADD_STATIC_GROUP_MESSAGE if module.params.get("state", "present") == "present" else \
313 REMOVE_STATIC_GROUP_MESSAGE
314 module.exit_json(msg=msg, failed=True)
315
316
317 def get_group_id(rest_obj, module):
318 group_name = module.params.get("name")
319 group_id = module.params.get("group_id")
320 if group_name is not None:
321 group_resp = rest_obj.invoke_request("GET", GROUP_URI,
322 query_param={"$filter": "Name eq '{0}'".format(group_name)})
323 value = group_resp.json_data.get("value")
324 if value:
325 value = value[0]
326 else:
327 value = []
328 validate_group(value, module, "name", group_name)
329 group_id = value["Id"]
330
331 else:
332 uri = GROUP_URI + "(" + str(group_id) + ")"
333 try:
334 group_resp = rest_obj.invoke_request("GET", uri)
335 validate_group(group_resp.json_data, module, "Id", group_id)
336 except HTTPError:
337 validate_group({}, module, "Id", group_id)
338 return group_id
339
340
341 def get_all_ips(ip_addresses, module):
342 ip_addresses_list = []
343 for ip in ip_addresses:
344 try:
345 if "/" in ip:
346 cidr_list = IPNetwork(ip)
347 ip_addresses_list.append(cidr_list)
348 elif "-" in ip and ip.count("-") == 1:
349 range_addr = ip.split("-")
350 range_list = IPRange(range_addr[0], range_addr[1])
351 ip_addresses_list.append(range_list)
352 else:
353 single_ip = IPAddress(ip)
354 ip_addresses_list.append(single_ip)
355 except (AddrFormatError, ValueError):
356 module.exit_json(msg=INVALID_IP_FORMAT.format(ip), failed=True)
357 return ip_addresses_list
358
359
360 def get_device_id_from_ip(ip_addresses, device_list, module):
361 ip_map = dict(
362 [(each_device["DeviceManagement"][0]["NetworkAddress"], each_device["Id"]) for each_device in device_list
363 if each_device["DeviceManagement"]])
364 device_id_list_map = {}
365 for available_ip, device_id in ip_map.items():
366 for ip_formats in ip_addresses:
367 if isinstance(ip_formats, IPAddress):
368 try:
369 ome_ip = IPAddress(available_ip)
370 except AddrFormatError:
371 ome_ip = IPAddress(available_ip.replace(']', '').replace('[', ''))
372 if ome_ip == ip_formats:
373 device_id_list_map.update({device_id: str(ip_formats)})
374 if not isinstance(ip_formats, IPAddress):
375 try:
376 ome_ip = IPAddress(available_ip)
377 except AddrFormatError:
378 ome_ip = IPAddress(available_ip.replace(']', '').replace('[', ''))
379 if ome_ip in ip_formats:
380 device_id_list_map.update({device_id: str(ome_ip)})
381 if len(device_id_list_map) == 0:
382 module.exit_json(msg=IP_NOT_EXISTS, failed=True)
383 return device_id_list_map
384
385
386 def get_device_id(rest_obj, module):
387 device_id_list = module.params.get("device_ids")
388 device_tag_list = module.params.get("device_service_tags")
389 ip_addresses = module.params.get("ip_addresses")
390 device_list = rest_obj.get_all_report_details(DEVICE_URI)
391 invalid, each_device_list, each_tag_to_id = [], [], []
392 if device_id_list or device_tag_list:
393 if device_id_list:
394 key = "Id"
395 each_device_list = device_id_list
396 elif device_tag_list:
397 key = "DeviceServiceTag"
398 each_device_list = device_tag_list
399
400 for each in each_device_list:
401 each_device = list(filter(lambda d: d[key] in [each], device_list["report_list"]))
402 if key == "DeviceServiceTag" and each_device:
403 each_tag_to_id.append(each_device[0]["Id"])
404 if not each_device:
405 invalid.append(str(each))
406 if invalid:
407 value = "id" if key == "Id" else "service tag"
408 module.exit_json(msg="Unable to complete the operation because the entered "
409 "target device {0}(s) '{1}' are invalid.".format(value, ",".join(set(invalid))), failed=True)
410 if each_tag_to_id:
411 each_device_list = each_tag_to_id
412 else:
413 all_ips = get_all_ips(ip_addresses, module)
414 each_device_list = get_device_id_from_ip(all_ips, device_list["report_list"], module)
415 key = "IPAddresses"
416 return each_device_list, key
417
418
419 def add_member_to_group(module, rest_obj, group_id, device_id, key):
420 group_device = rest_obj.get_all_report_details("{0}({1})/Devices".format(GROUP_URI, group_id))
421 device_exists, device_not_exists, added_ips = [], [], []
422 if key != "IPAddresses":
423 for each in device_id:
424 each_device = list(filter(lambda d: d["Id"] in [each], group_device["report_list"]))
425 if each_device:
426 tag_or_id = each_device[0][key] if key == "DeviceServiceTag" else each
427 device_exists.append(str(tag_or_id))
428 else:
429 device_not_exists.append(each)
430 else:
431 already_existing_id = []
432 for device in group_device["report_list"]:
433 if device["Id"] in device_id:
434 device_exists.append(device_id[device["Id"]])
435 already_existing_id.append(device["Id"])
436 device_not_exists = list(set(device_id.keys()) - set(already_existing_id))
437 added_ips = [ip for d_id, ip in device_id.items() if d_id in device_not_exists]
438 if module.check_mode and device_not_exists:
439 module.exit_json(msg="Changes found to be applied.", changed=True, group_id=group_id)
440 elif module.check_mode and not device_not_exists:
441 module.exit_json(msg="No changes found to be applied.", group_id=group_id)
442
443 if device_exists and not device_not_exists:
444 module.exit_json(
445 msg="No changes found to be applied.",
446 group_id=group_id
447 )
448 payload = {"GroupId": group_id, "MemberDeviceIds": device_not_exists}
449 response = rest_obj.invoke_request("POST", ADD_MEMBER_URI, data=payload)
450 return response, added_ips
451
452
453 def get_current_member_of_group(rest_obj, group_id):
454 group_device = rest_obj.get_all_report_details("{0}({1})/Devices".format(GROUP_URI, group_id))
455
456 device_id_list = [each["Id"] for each in group_device["report_list"]]
457 return device_id_list
458
459
460 def remove_member_from_group(module, rest_obj, group_id, device_id, current_device_list):
461 payload_device_list = [each_id for each_id in device_id if each_id in current_device_list]
462
463 if module.check_mode and payload_device_list:
464 module.exit_json(msg="Changes found to be applied.", changed=True, group_id=group_id)
465
466 if not payload_device_list:
467 module.exit_json(msg="No changes found to be applied.", group_id=group_id)
468
469 payload = {"GroupId": group_id, "MemberDeviceIds": payload_device_list}
470 response = rest_obj.invoke_request("POST", REMOVE_MEMBER_URI, data=payload)
471 return response
472
473
474 def main():
475 specs = {
476 "name": {"type": "str"},
477 "group_id": {"type": "int"},
478 "state": {"required": False, "type": "str", "choices": ["present", "absent"], "default": "present"},
479 "device_service_tags": {"required": False, "type": "list", "elements": 'str'},
480 "device_ids": {"required": False, "type": "list", "elements": 'int'},
481 "ip_addresses": {"required": False, "type": "list", "elements": 'str'},
482 }
483
484 module = OmeAnsibleModule(
485 argument_spec=specs,
486 required_if=[
487 ["state", "present", ("device_ids", "device_service_tags", "ip_addresses"), True],
488 ],
489 mutually_exclusive=[
490 ("name", "group_id"),
491 ("device_ids", "device_service_tags", "ip_addresses"),
492 ],
493 required_one_of=[("name", "group_id"),
494 ("device_ids", "device_service_tags", "ip_addresses")],
495 supports_check_mode=True
496 )
497
498 try:
499 if module.params.get("ip_addresses") and not HAS_NETADDR:
500 module.exit_json(msg=NETADDR_ERROR, failed=True)
501 with RestOME(module.params, req_session=True) as rest_obj:
502 group_id = get_group_id(rest_obj, module)
503 device_id, key = get_device_id(rest_obj, module)
504 if module.params["state"] == "present":
505 response, added_ips = add_member_to_group(module, rest_obj, group_id, device_id, key)
506 if added_ips:
507 module.exit_json(msg="Successfully added member(s) to the device group.",
508 group_id=group_id, changed=True, ip_addresses_added=added_ips)
509 module.exit_json(msg="Successfully added member(s) to the device group.",
510 group_id=group_id, changed=True)
511 else:
512 current_device_list = get_current_member_of_group(rest_obj, group_id)
513 remove_member_from_group(module, rest_obj, group_id, device_id, current_device_list)
514 module.exit_json(msg="Successfully removed member(s) from the device group.", changed=True)
515 except HTTPError as err:
516 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
517 except URLError as err:
518 module.exit_json(msg=str(err), unreachable=True)
519 except (IOError, ValueError, SSLError, TypeError, ConnectionError, AttributeError,
520 IndexError, KeyError, OSError) as err:
521 module.exit_json(msg=str(err), failed=True)
522
523
524 if __name__ == '__main__':
525 main()