Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 10.0.1
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 __metaclass__ = type
14
15 DOCUMENTATION = """
16 ---
17 module: ome_device_location
18 short_description: Configure device location settings on OpenManage Enterprise Modular
19 description: This module allows to configure the device location settings of the chassis
20 on OpenManage Enterprise Modular.
21 version_added: "4.2.0"
22 extends_documentation_fragment:
23 - dellemc.openmanage.omem_auth_options
24 options:
25 device_id:
26 type: int
27 description:
28 - The ID of the chassis for which the settings need to be updated.
29 - If the device ID is not specified, this module updates
30 the location settings for the I(hostname).
31 - I(device_id) is mutually exclusive with I(device_service_tag).
32 device_service_tag:
33 type: str
34 description:
35 - The service tag of the chassis for which the settings need to be updated.
36 - If the device service tag is not specified, this module updates
37 the location settings for the I(hostname).
38 - I(device_service_tag) is mutually exclusive with I(device_id).
39 data_center:
40 type: str
41 description: The data center name of the chassis.
42 room:
43 type: str
44 description: The room of the chassis.
45 aisle:
46 type: str
47 description: The aisle of the chassis.
48 rack:
49 type: str
50 description: The rack name of the chassis.
51 rack_slot:
52 type: int
53 description: The rack slot number of the chassis.
54 location:
55 type: str
56 description: The physical location of the chassis.
57 requirements:
58 - "python >= 3.9.6"
59 author:
60 - "Felix Stephen (@felixs88)"
61 notes:
62 - Run this module from a system that has direct access to Dell OpenManage Enterprise Modular.
63 - This module supports C(check_mode).
64 """
65
66 EXAMPLES = """
67 ---
68 - name: Update device location settings of a chassis using the device ID.
69 dellemc.openmanage.ome_device_location:
70 hostname: "192.168.0.1"
71 username: "username"
72 password: "password"
73 ca_path: "/path/to/ca_cert.pem"
74 device_id: 25011
75 data_center: data center 1
76 room: room 1
77 aisle: aisle 1
78 rack: rack 1
79 rack_slot: 2
80 location: location 1
81
82 - name: Update device location settings of a chassis using the device service tag.
83 dellemc.openmanage.ome_device_location:
84 hostname: "192.168.0.1"
85 username: "username"
86 password: "password"
87 ca_path: "/path/to/ca_cert.pem"
88 device_service_tag: GHRT2RL
89 data_center: data center 2
90 room: room 7
91 aisle: aisle 4
92 rack: rack 6
93 rack_slot: 22
94 location: location 5
95
96 - name: Update device location settings of the host chassis.
97 dellemc.openmanage.ome_device_location:
98 hostname: "192.168.0.1"
99 username: "username"
100 password: "password"
101 ca_path: "/path/to/ca_cert.pem"
102 data_center: data center 3
103 room: room 3
104 aisle: aisle 1
105 rack: rack 7
106 rack_slot: 10
107 location: location 9
108 """
109
110 RETURN = """
111 ---
112 msg:
113 type: str
114 description: Overall status of the device location settings.
115 returned: always
116 sample: "Successfully updated the location settings."
117 location_details:
118 type: dict
119 description: returned when location settings are updated successfully.
120 returned: success
121 sample: {
122 "Aisle": "aisle 1",
123 "DataCenter": "data center 1",
124 "Location": "location 1",
125 "RackName": "rack 1",
126 "RackSlot": 2,
127 "Room": "room 1",
128 "SettingType": "Location"
129 }
130 error_info:
131 description: Details of the HTTP Error.
132 returned: on HTTP error
133 type: dict
134 sample: {
135 "error": {
136 "code": "Base.1.0.GeneralError",
137 "message": "A general error has occurred. See ExtendedInfo for more information.",
138 "@Message.ExtendedInfo": [
139 {
140 "MessageId": "GEN1234",
141 "RelatedProperties": [],
142 "Message": "Unable to process the request because an error occurred.",
143 "MessageArgs": [],
144 "Severity": "Critical",
145 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
146 }
147 ]
148 }
149 }
150 """
151
152
153 import json
154 import socket
155 from ssl import SSLError
156 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
157 from ansible.module_utils.urls import ConnectionError
158 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
159
160 LOCATION_API = "DeviceService/Devices({0})/Settings('Location')"
161 DEVICE_URI = "DeviceService/Devices"
162 DOMAIN_URI = "ManagementDomainService/Domains"
163 DEVICE_FAIL_MSG = "Unable to complete the operation because the entered target device {0} '{1}' is invalid."
164
165
166 def check_domain_service(module, rest_obj):
167 try:
168 rest_obj.invoke_request("GET", DOMAIN_URI, api_timeout=5)
169 except HTTPError as err:
170 err_message = json.load(err)
171 if err_message["error"]["@Message.ExtendedInfo"][0]["MessageId"] == "CGEN1006":
172 module.exit_json(msg="The device location settings operation is supported only on "
173 "OpenManage Enterprise Modular systems.", failed=True)
174 return
175
176
177 def validate_dictionary(module, loc_resp):
178 data_center = module.params.get("data_center")
179 room = module.params.get("room")
180 aisle = module.params.get("aisle")
181 rack = module.params.get("rack")
182 rack_slot = module.params.get("rack_slot")
183 location = module.params.get("location")
184 req_dict = {"DataCenter": data_center, "Room": room, "Aisle": aisle, "RackName": rack, "Location": location}
185 req_filter_none = dict((k, v) for k, v in req_dict.items() if v is not None)
186 keys = list(req_filter_none.keys())
187 exit_dict = dict((k, v) for k, v in loc_resp.items() if k in keys and v is not None)
188 if rack_slot is not None:
189 req_dict.update({"RackSlot": rack_slot})
190 req_filter_none.update({"RackSlot": rack_slot})
191 exit_dict.update({"RackSlot": loc_resp["RackSlot"]})
192 diff = bool(set(req_filter_none.items()) ^ set(exit_dict.items()))
193 if not diff and not module.check_mode:
194 module.exit_json(msg="No changes found to be applied.")
195 elif not diff and module.check_mode:
196 module.exit_json(msg="No changes found to be applied.")
197 elif diff and module.check_mode:
198 module.exit_json(msg="Changes found to be applied.", changed=True)
199 payload_dict = {"SettingType": "Location"}
200 payload_dict.update(dict((k, v) for k, v in loc_resp.items() if k in req_dict.keys()))
201 payload_dict.update(req_filter_none)
202 if req_filter_none.get("RackSlot") is None:
203 payload_dict.update({"RackSlot": loc_resp.get("RackSlot")})
204 return payload_dict
205
206
207 def get_ip_from_host(hostname):
208 ipaddr = hostname
209 try:
210 result = socket.getaddrinfo(hostname, None)
211 last_element = result[-1]
212 ip_address = last_element[-1][0]
213 if ip_address:
214 ipaddr = ip_address
215 except socket.gaierror:
216 ipaddr = hostname
217 except Exception:
218 ipaddr = hostname
219 return ipaddr
220
221
222 def standalone_chassis(module, rest_obj):
223 key, value = None, None
224 ipaddress = get_ip_from_host(module.params["hostname"])
225 resp = rest_obj.invoke_request("GET", DOMAIN_URI)
226 for data in resp.json_data["value"]:
227 if ipaddress in data["PublicAddress"]:
228 key, value = ("Id", data["DeviceId"])
229 break
230 else:
231 module.exit_json(msg="Failed to fetch the device information.", failed=True)
232 return key, value
233
234
235 def device_validation(module, rest_obj):
236 final_resp = {}
237 device_id, tag = module.params.get("device_id"), module.params.get("device_service_tag")
238 if device_id is None and tag is None:
239 key, value = standalone_chassis(module, rest_obj)
240 device_id = value
241 else:
242 key, value = ("Id", device_id) if device_id is not None else ("DeviceServiceTag", tag)
243 param_value = "{0} eq {1}".format(key, value) if key == "Id" else "{0} eq '{1}'".format(key, value)
244 resp = rest_obj.invoke_request("GET", DEVICE_URI, query_param={"$filter": param_value})
245 resp_data = resp.json_data.get("value")
246 rename_key = "id" if key == "Id" else "service tag"
247 if not resp_data:
248 module.exit_json(msg=DEVICE_FAIL_MSG.format(rename_key, value), failed=True)
249 if key == "DeviceServiceTag" and resp_data[0]["DeviceServiceTag"] == tag:
250 device_id = resp_data[0]["Id"]
251 elif key == "Id" and resp_data[0]["Id"] == device_id:
252 device_id = resp_data[0]["Id"]
253 else:
254 module.exit_json(msg=DEVICE_FAIL_MSG.format(rename_key, value), failed=True)
255 try:
256 loc_resp = rest_obj.invoke_request("GET", LOCATION_API.format(device_id))
257 except HTTPError as err:
258 err_message = json.load(err)
259 error_msg = err_message.get('error', {}).get('@Message.ExtendedInfo')
260 if error_msg and error_msg[0].get("MessageId") == "CGEN1004":
261 module.exit_json(msg="Unable to complete the operation because the location settings "
262 "are not supported on the specified device.", failed=True)
263 else:
264 payload = validate_dictionary(module, loc_resp.json_data)
265 final_resp = rest_obj.invoke_request("PUT", LOCATION_API.format(device_id), data=payload)
266 return final_resp
267
268
269 def main():
270 specs = {
271 "device_id": {"required": False, "type": "int"},
272 "device_service_tag": {"required": False, "type": "str"},
273 "data_center": {"required": False, "type": "str"},
274 "room": {"required": False, "type": "str"},
275 "aisle": {"required": False, "type": "str"},
276 "rack": {"required": False, "type": "str"},
277 "rack_slot": {"required": False, "type": "int"},
278 "location": {"required": False, "type": "str"},
279 }
280
281 module = OmeAnsibleModule(
282 argument_spec=specs,
283 mutually_exclusive=[('device_id', 'device_service_tag')],
284 supports_check_mode=True
285 )
286 try:
287 with RestOME(module.params, req_session=True) as rest_obj:
288 check_domain_service(module, rest_obj)
289 resp = device_validation(module, rest_obj)
290 module.exit_json(msg="Successfully updated the location settings.",
291 location_details=resp.json_data, changed=True)
292 except HTTPError as err:
293 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
294 except URLError as err:
295 module.exit_json(msg=str(err), unreachable=True)
296 except (IOError, ValueError, SSLError, TypeError, ConnectionError, AttributeError, IndexError, KeyError, OSError) as err:
297 module.exit_json(msg=str(err), failed=True)
298
299
300 if __name__ == '__main__':
301 main()