Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_device_network_services.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_network_services
18 short_description: Configure chassis network services settings on OpenManage Enterprise Modular
19 description: This module allows to configure the network services on OpenManage Enterprise Modular.
20 version_added: "4.3.0"
21 extends_documentation_fragment:
22 - dellemc.openmanage.omem_auth_options
23 options:
24 device_id:
25 type: int
26 description:
27 - The ID of the chassis for which the settings need to be updated.
28 - If the device ID is not specified, this module updates the network services settings for the I(hostname).
29 - I(device_id) is mutually exclusive with I(device_service_tag).
30 device_service_tag:
31 type: str
32 description:
33 - The service tag of the chassis for which the setting needs to be updated.
34 - If the device service tag is not specified, this module updates the network
35 services settings for the I(hostname).
36 - I(device_service_tag) is mutually exclusive with I(device_id).
37 snmp_settings:
38 type: dict
39 description: The settings for SNMP configuration.
40 suboptions:
41 enabled:
42 type: bool
43 required: true
44 description: Enables or disables the SNMP settings.
45 port_number:
46 type: int
47 description: The SNMP port number.
48 community_name:
49 type: str
50 description:
51 - The SNMP community string.
52 - Required when I(enabled) is C(true).
53 ssh_settings:
54 type: dict
55 description: The settings for SSH configuration.
56 suboptions:
57 enabled:
58 required: true
59 type: bool
60 description: Enables or disables the SSH settings.
61 port_number:
62 type: int
63 description: The port number for SSH service.
64 max_sessions:
65 type: int
66 description: Number of SSH sessions.
67 max_auth_retries:
68 type: int
69 description: The number of retries when the SSH session fails.
70 idle_timeout:
71 type: float
72 description: SSH idle timeout in minutes.
73 remote_racadm_settings:
74 type: dict
75 description: The settings for remote RACADM configuration.
76 suboptions:
77 enabled:
78 type: bool
79 required: true
80 description: Enables or disables the remote RACADM settings.
81 requirements:
82 - "python >= 3.9.6"
83 author:
84 - "Felix Stephen (@felixs88)"
85 - "Kritika Bhateja (@Kritika-Bhateja-03)"
86 notes:
87 - Run this module from a system that has direct access to Dell OpenManage Enterprise Modular.
88 - This module supports C(check_mode).
89 """
90
91 EXAMPLES = """
92 ---
93 - name: Update network services settings of a chassis using the device ID
94 dellemc.openmanage.ome_device_network_services:
95 hostname: "192.168.0.1"
96 username: "username"
97 password: "password"
98 ca_path: "/path/to/ca_cert.pem"
99 device_id: 25011
100 snmp_settings:
101 enabled: true
102 port_number: 161
103 community_name: public
104 ssh_settings:
105 enabled: false
106 remote_racadm_settings:
107 enabled: false
108
109 - name: Update network services settings of a chassis using the device service tag.
110 dellemc.openmanage.ome_device_network_services:
111 hostname: "192.168.0.2"
112 username: "username"
113 password: "password"
114 ca_path: "/path/to/ca_cert.pem"
115 device_service_tag: GHRT2RL
116 snmp_settings:
117 enabled: false
118 ssh_settings:
119 enabled: true
120 port_number: 22
121 max_sessions: 1
122 max_auth_retries: 3
123 idle_timeout: 1
124 remote_racadm_settings:
125 enabled: false
126
127 - name: Update network services settings of the host chassis.
128 dellemc.openmanage.ome_device_network_services:
129 hostname: "192.168.0.3"
130 username: "username"
131 password: "password"
132 ca_path: "/path/to/ca_cert.pem"
133 snmp_settings:
134 enabled: false
135 ssh_settings:
136 enabled: false
137 remote_racadm_settings:
138 enabled: true
139 """
140
141 RETURN = """
142 ---
143 msg:
144 type: str
145 description: Overall status of the network services settings.
146 returned: always
147 sample: "Successfully updated the network services settings."
148 network_services_details:
149 type: dict
150 description: returned when network services settings are updated successfully.
151 returned: success
152 sample: {
153 "EnableRemoteRacadm": true,
154 "SettingType": "NetworkServices",
155 "SnmpConfiguration": {
156 "PortNumber": 161,
157 "SnmpEnabled": true,
158 "SnmpV1V2Credential": {
159 "CommunityName": "public"
160 }
161 },
162 "SshConfiguration": {
163 "IdleTimeout": 60,
164 "MaxAuthRetries": 3,
165 "MaxSessions": 1,
166 "PortNumber": 22,
167 "SshEnabled": false
168 }
169 }
170 error_info:
171 description: Details of the HTTP Error.
172 returned: on HTTP error
173 type: dict
174 sample: {
175 "error": {
176 "code": "Base.1.0.GeneralError",
177 "message": "A general error has occurred. See ExtendedInfo for more information.",
178 "@Message.ExtendedInfo": [
179 {
180 "MessageId": "CAPP1042",
181 "RelatedProperties": [],
182 "Message": "Unable to update the network configuration because the SNMP PortNumber is already in use.",
183 "MessageArgs": ["SNMP PortNumber"],
184 "Severity": "Informational",
185 "Resolution": "Enter a different port number and retry the operation.",
186 }
187 ]
188 }
189 }
190 """
191
192
193 import json
194 import socket
195 from ssl import SSLError
196 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
197 from ansible.module_utils.urls import ConnectionError
198 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
199
200 DOMAIN_URI = "ManagementDomainService/Domains"
201 DEVICE_URI = "DeviceService/Devices"
202 NETWORK_SERVICE_API = "DeviceService/Devices({0})/Settings('NetworkServices')"
203 CONFIG_FAIL_MSG = "one of the following is required: snmp_settings, ssh_settings, remote_racadm_settings"
204 DOMAIN_FAIL_MSG = "The device location settings operation is supported only on " \
205 "OpenManage Enterprise Modular."
206 FETCH_FAIL_MSG = "Failed to retrieve the device information."
207 DEVICE_FAIL_MSG = "Unable to complete the operation because the entered target device {0} '{1}' is invalid."
208 NETWORK_SERVICE_FAIL_MSG = "Unable to complete the operation because the network services settings " \
209 "are not supported on the specified device."
210 CHANGES_FOUND = "Changes found to be applied."
211 NO_CHANGES_FOUND = "No changes found to be applied."
212 SUCCESS_MSG = "Successfully updated the network services settings."
213
214
215 def check_domain_service(module, rest_obj):
216 try:
217 rest_obj.invoke_request("GET", DOMAIN_URI, api_timeout=5)
218 except HTTPError as err:
219 err_message = json.loads(err)
220 if err_message["error"]["@Message.ExtendedInfo"][0]["MessageId"] == "CGEN1006":
221 module.exit_json(msg=DOMAIN_FAIL_MSG, failed=True)
222 return
223
224
225 def get_ip_from_host(hostname):
226 ipaddr = hostname
227 try:
228 result = socket.getaddrinfo(hostname, None)
229 last_element = result[-1]
230 ip_address = last_element[-1][0]
231 if ip_address:
232 ipaddr = ip_address
233 except socket.gaierror:
234 ipaddr = hostname
235 except Exception:
236 ipaddr = hostname
237 return ipaddr
238
239
240 def get_chassis_device(module, rest_obj):
241 key, value = None, None
242 ipaddress = get_ip_from_host(module.params["hostname"])
243 resp = rest_obj.invoke_request("GET", DOMAIN_URI)
244 for data in resp.json_data["value"]:
245 if ipaddress in data["PublicAddress"]:
246 key, value = ("Id", data["DeviceId"])
247 break
248 else:
249 module.exit_json(msg=FETCH_FAIL_MSG, failed=True)
250 return key, value
251
252
253 def check_mode_validation(module, loc_data, rest_obj):
254 req_snmp, req_ssh, req_comm_str, req_racadm = {}, {}, {}, {}
255 exist_snmp, exist_ssh, exist_comm_str, exist_racadm = {}, {}, {}, {}
256 payload = {"SettingType": "NetworkServices"}
257 snmp_enabled = module.params.get("snmp_settings")
258 if snmp_enabled is not None and snmp_enabled["enabled"] is True:
259 req_snmp.update({"SnmpEnabled": snmp_enabled["enabled"]})
260 req_comm_str.update({"CommunityName": module.params["snmp_settings"]["community_name"]})
261 exist_snmp.update({"SnmpEnabled": loc_data["SnmpConfiguration"]["SnmpEnabled"]})
262 exist_comm_str.update({"CommunityName": loc_data["SnmpConfiguration"]["SnmpV1V2Credential"]["CommunityName"]})
263 elif snmp_enabled is not None and snmp_enabled["enabled"] is False:
264 req_snmp.update({"SnmpEnabled": snmp_enabled["enabled"]})
265 exist_snmp.update({"SnmpEnabled": loc_data["SnmpConfiguration"]["SnmpEnabled"]})
266
267 if snmp_enabled is not None and snmp_enabled["enabled"] is True and snmp_enabled.get("port_number") is not None:
268 req_snmp.update({"PortNumber": snmp_enabled.get("port_number")})
269 exist_snmp.update({"PortNumber": loc_data["SnmpConfiguration"]["PortNumber"]})
270 ssh_enabled = module.params.get("ssh_settings")
271 if ssh_enabled is not None and ssh_enabled["enabled"] is True:
272 req_ssh.update({"SshEnabled": ssh_enabled["enabled"]})
273 exist_ssh.update({"SshEnabled": loc_data["SshConfiguration"]["SshEnabled"]})
274 elif ssh_enabled is not None and ssh_enabled["enabled"] is False:
275 req_ssh.update({"SshEnabled": ssh_enabled["enabled"]})
276 exist_ssh.update({"SshEnabled": loc_data["SshConfiguration"]["SshEnabled"]})
277
278 if ssh_enabled is not None and ssh_enabled["enabled"] is True and ssh_enabled.get("port_number") is not None:
279 req_ssh.update({"PortNumber": module.params["ssh_settings"]["port_number"]})
280 exist_ssh.update({"PortNumber": loc_data["SshConfiguration"]["PortNumber"]})
281 if ssh_enabled is not None and ssh_enabled["enabled"] is True and ssh_enabled.get("max_sessions") is not None:
282 req_ssh.update({"MaxSessions": module.params["ssh_settings"]["max_sessions"]})
283 exist_ssh.update({"MaxSessions": loc_data["SshConfiguration"]["MaxSessions"]})
284 if ssh_enabled is not None and ssh_enabled["enabled"] is True and ssh_enabled.get("max_auth_retries") is not None:
285 req_ssh.update({"MaxAuthRetries": module.params["ssh_settings"]["max_auth_retries"]})
286 exist_ssh.update({"MaxAuthRetries": loc_data["SshConfiguration"]["MaxAuthRetries"]})
287 if ssh_enabled is not None and ssh_enabled["enabled"] is True and ssh_enabled.get("idle_timeout") is not None:
288 req_ssh.update({"IdleTimeout": int(module.params["ssh_settings"]["idle_timeout"] * 60)})
289 exist_ssh.update({"IdleTimeout": int(loc_data["SshConfiguration"]["IdleTimeout"])})
290 recadm_enabled = module.params.get("remote_racadm_settings")
291 if recadm_enabled is not None and recadm_enabled["enabled"] is True:
292 req_racadm = {"EnableRemoteRacadm": recadm_enabled["enabled"]}
293 exist_racadm = {"EnableRemoteRacadm": loc_data["EnableRemoteRacadm"]}
294 elif recadm_enabled is not None and recadm_enabled["enabled"] is False:
295 req_racadm = {"EnableRemoteRacadm": recadm_enabled["enabled"]}
296 exist_racadm = {"EnableRemoteRacadm": loc_data["EnableRemoteRacadm"]}
297 changes = [bool(set(req_snmp.items()) ^ set(exist_snmp.items())) or
298 bool(set(req_ssh.items()) ^ set(exist_ssh.items())) or
299 bool(set(req_comm_str.items()) ^ set(exist_comm_str.items())) or
300 bool(set(req_racadm.items()) ^ set(exist_racadm.items()))]
301 if module.check_mode and any(changes) is True:
302 loc_data["SshConfiguration"]["IdleTimeout"] = loc_data["SshConfiguration"]["IdleTimeout"] / 60
303 module.exit_json(msg=CHANGES_FOUND, changed=True)
304 elif module.check_mode and all(changes) is False:
305 loc_data["SshConfiguration"]["IdleTimeout"] = loc_data["SshConfiguration"]["IdleTimeout"] / 60
306 module.exit_json(msg=NO_CHANGES_FOUND)
307 elif not module.check_mode and all(changes) is False:
308 loc_data["SshConfiguration"]["IdleTimeout"] = loc_data["SshConfiguration"]["IdleTimeout"] / 60
309 module.exit_json(msg=NO_CHANGES_FOUND)
310 else:
311 payload.update(loc_data)
312 payload["SnmpConfiguration"].update(req_snmp) if req_snmp else None
313 payload["SnmpConfiguration"]["SnmpV1V2Credential"].update(req_comm_str) if req_comm_str else None
314 payload["SshConfiguration"].update(req_ssh) if req_ssh else None
315 payload.update(req_racadm) if req_racadm else None
316 return payload
317
318
319 def fetch_device_details(module, rest_obj):
320 device_id, tag, final_resp = module.params.get("device_id"), module.params.get("device_service_tag"), {}
321 if device_id is None and tag is None:
322 key, value = get_chassis_device(module, rest_obj)
323 device_id = value
324 else:
325 key, value = ("Id", device_id) if device_id is not None else ("DeviceServiceTag", tag)
326 param_value = "{0} eq {1}".format(key, value) if key == "Id" else "{0} eq '{1}'".format(key, value)
327 resp = rest_obj.invoke_request("GET", DEVICE_URI, query_param={"$filter": param_value})
328 resp_data = resp.json_data.get("value")
329 rename_key = "id" if key == "Id" else "service tag"
330 if not resp_data:
331 module.exit_json(msg=DEVICE_FAIL_MSG.format(rename_key, value),
332 failed=True)
333 if key == "DeviceServiceTag" and resp_data[0]["DeviceServiceTag"] == tag:
334 device_id = resp_data[0]["Id"]
335 elif key == "Id" and resp_data[0]["Id"] == device_id:
336 device_id = resp_data[0]["Id"]
337 else:
338 module.exit_json(msg=DEVICE_FAIL_MSG.format(rename_key, value),
339 failed=True)
340 try:
341 loc_resp = rest_obj.invoke_request("GET", NETWORK_SERVICE_API.format(device_id))
342 except HTTPError as err:
343 if err.code == 404:
344 module.exit_json(msg=NETWORK_SERVICE_FAIL_MSG,
345 failed=True)
346 err_message = json.load(err)
347 error_msg = err_message.get('error', {}).get('@Message.ExtendedInfo')
348 if error_msg and error_msg[0].get("MessageId") == "CGEN1004":
349 module.exit_json(msg=NETWORK_SERVICE_FAIL_MSG,
350 failed=True)
351 else:
352 loc_resp_data = rest_obj.strip_substr_dict(loc_resp.json_data)
353 payload = check_mode_validation(module, loc_resp_data, rest_obj)
354 final_resp = rest_obj.invoke_request("PUT", NETWORK_SERVICE_API.format(device_id), data=payload)
355 return final_resp
356
357
358 def main():
359 snmp_options = {"enabled": {"type": "bool", "required": True},
360 "port_number": {"type": "int", "required": False},
361 "community_name": {"type": "str", "required": False}}
362 ssh_options = {"enabled": {"type": "bool", "required": True},
363 "port_number": {"type": "int", "required": False},
364 "max_sessions": {"type": "int", "required": False},
365 "max_auth_retries": {"type": "int", "required": False},
366 "idle_timeout": {"type": "float", "required": False}}
367 racadm_options = {"enabled": {"type": "bool", "required": True}}
368 specs = {
369 "device_id": {"required": False, "type": "int"},
370 "device_service_tag": {"required": False, "type": "str"},
371 "snmp_settings": {"type": "dict", "required": False, "options": snmp_options,
372 "required_if": [["enabled", True, ("community_name",)]]},
373 "ssh_settings": {"type": "dict", "required": False, "options": ssh_options},
374 "remote_racadm_settings": {"type": "dict", "required": False, "options": racadm_options},
375 }
376
377 module = OmeAnsibleModule(
378 argument_spec=specs,
379 mutually_exclusive=[('device_id', 'device_service_tag')],
380 required_one_of=[["snmp_settings", "ssh_settings", "remote_racadm_settings"]],
381 supports_check_mode=True,
382 )
383 if not any([module.params.get("snmp_settings"), module.params.get("ssh_settings"),
384 module.params.get("remote_racadm_settings")]):
385 module.exit_json(msg=CONFIG_FAIL_MSG, failed=True)
386 try:
387 with RestOME(module.params, req_session=True) as rest_obj:
388 check_domain_service(module, rest_obj)
389 resp = fetch_device_details(module, rest_obj)
390 resp_data = resp.json_data
391 resp_data["SshConfiguration"]["IdleTimeout"] = resp_data["SshConfiguration"]["IdleTimeout"] / 60
392 module.exit_json(msg=SUCCESS_MSG, network_services_details=resp_data, changed=True)
393 except HTTPError as err:
394 module.exit_json(msg=str(err), error_info=json.load(err),
395 failed=True)
396 except URLError as err:
397 module.exit_json(msg=str(err), unreachable=True)
398 except (IOError, ValueError, SSLError, TypeError, ConnectionError, AttributeError, IndexError, KeyError, OSError) as err:
399 module.exit_json(msg=str(err), failed=True)
400
401
402 if __name__ == '__main__':
403 main()