Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2019 Dell EMC Inc.
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: idrac_redfish_config
11 short_description: Manages servers through iDRAC using Dell Redfish APIs
12 description:
13 - For use with Dell iDRAC operations that require Redfish OEM extensions.
14 - Builds Redfish URIs locally and sends them to remote iDRAC controllers to set or update a configuration attribute.
15 extends_documentation_fragment:
16 - community.general._attributes
17 - community.general._redfish
18 attributes:
19 check_mode:
20 support: none
21 diff_mode:
22 support: none
23 options:
24 category:
25 required: true
26 type: str
27 description:
28 - Category to execute on iDRAC.
29 command:
30 required: true
31 description:
32 - List of commands to execute on iDRAC.
33 - V(SetManagerAttributes), V(SetLifecycleControllerAttributes) and V(SetSystemAttributes) are mutually exclusive commands
34 when O(category) is V(Manager).
35 type: list
36 elements: str
37 baseuri:
38 required: true
39 description:
40 - Base URI of iDRAC.
41 type: str
42 username:
43 description:
44 - Username for authenticating to iDRAC.
45 type: str
46 password:
47 description:
48 - Password for authenticating to iDRAC.
49 type: str
50 auth_token:
51 description:
52 - Security token for authenticating to iDRAC.
53 type: str
54 version_added: 2.3.0
55 manager_attributes:
56 description:
57 - Dictionary of iDRAC attribute name and value pairs to update.
58 default: {}
59 type: 'dict'
60 version_added: '0.2.0'
61 timeout:
62 description:
63 - Timeout in seconds for HTTP requests to iDRAC.
64 default: 10
65 type: int
66 resource_id:
67 description:
68 - ID of the System, Manager or Chassis to modify.
69 type: str
70 version_added: '0.2.0'
71 validate_certs:
72 version_added: 10.6.0
73 ca_path:
74 version_added: 10.6.0
75 ciphers:
76 version_added: 10.6.0
77
78 author: "Jose Delarosa (@jose-delarosa)"
79 """
80
81 EXAMPLES = r"""
82 - name: Enable NTP and set NTP server and Time zone attributes in iDRAC
83 community.general.idrac_redfish_config:
84 category: Manager
85 command: SetManagerAttributes
86 resource_id: iDRAC.Embedded.1
87 manager_attributes:
88 NTPConfigGroup.1.NTPEnable: "Enabled"
89 NTPConfigGroup.1.NTP1: "{{ ntpserver1 }}"
90 Time.1.Timezone: "{{ timezone }}"
91 baseuri: "{{ baseuri }}"
92 username: "{{ username}}"
93 password: "{{ password }}"
94
95 - name: Enable Syslog and set Syslog servers in iDRAC
96 community.general.idrac_redfish_config:
97 category: Manager
98 command: SetManagerAttributes
99 resource_id: iDRAC.Embedded.1
100 manager_attributes:
101 SysLog.1.SysLogEnable: "Enabled"
102 SysLog.1.Server1: "{{ syslog_server1 }}"
103 SysLog.1.Server2: "{{ syslog_server2 }}"
104 baseuri: "{{ baseuri }}"
105 username: "{{ username}}"
106 password: "{{ password }}"
107
108 - name: Configure SNMP community string, port, protocol and trap format
109 community.general.idrac_redfish_config:
110 category: Manager
111 command: SetManagerAttributes
112 resource_id: iDRAC.Embedded.1
113 manager_attributes:
114 SNMP.1.AgentEnable: "Enabled"
115 SNMP.1.AgentCommunity: "public_community_string"
116 SNMP.1.TrapFormat: "SNMPv1"
117 SNMP.1.SNMPProtocol: "All"
118 SNMP.1.DiscoveryPort: 161
119 SNMP.1.AlertPort: 162
120 baseuri: "{{ baseuri }}"
121 username: "{{ username}}"
122 password: "{{ password }}"
123
124 - name: Enable CSIOR
125 community.general.idrac_redfish_config:
126 category: Manager
127 command: SetLifecycleControllerAttributes
128 resource_id: iDRAC.Embedded.1
129 manager_attributes:
130 LCAttributes.1.CollectSystemInventoryOnRestart: "Enabled"
131 baseuri: "{{ baseuri }}"
132 username: "{{ username}}"
133 password: "{{ password }}"
134
135 - name: Set Power Supply Redundancy Policy to A/B Grid Redundant
136 community.general.idrac_redfish_config:
137 category: Manager
138 command: SetSystemAttributes
139 resource_id: iDRAC.Embedded.1
140 manager_attributes:
141 ServerPwr.1.PSRedPolicy: "A/B Grid Redundant"
142 baseuri: "{{ baseuri }}"
143 username: "{{ username}}"
144 password: "{{ password }}"
145 """
146
147 RETURN = r"""
148 msg:
149 description: Message with action result or error description.
150 returned: always
151 type: str
152 sample: "Action was successful"
153 """
154
155 from ansible.module_utils.basic import AnsibleModule
156 from ansible.module_utils.common.validation import check_mutually_exclusive, check_required_arguments
157
158 from ansible_collections.community.general.plugins.module_utils._redfish_utils import (
159 REDFISH_COMMON_ARGUMENT_SPEC,
160 RedfishUtils,
161 )
162
163
164 class IdracRedfishUtils(RedfishUtils):
165 def set_manager_attributes(self, command):
166 result = {}
167 required_arg_spec = {"manager_attributes": {"required": True}}
168
169 try:
170 check_required_arguments(required_arg_spec, self.module.params)
171
172 except TypeError as e:
173 self.module.fail_json(msg=f"{e}")
174
175 key = "Attributes"
176 command_manager_attributes_uri_map = {
177 "SetManagerAttributes": self.manager_uri,
178 "SetLifecycleControllerAttributes": "/redfish/v1/Managers/LifecycleController.Embedded.1",
179 "SetSystemAttributes": "/redfish/v1/Managers/System.Embedded.1",
180 }
181 manager_uri = command_manager_attributes_uri_map.get(command, self.manager_uri)
182
183 attributes = self.module.params["manager_attributes"]
184
185 attrs_to_patch = {}
186 attrs_skipped = {}
187 attrs_bad = {} # Store attrs which were not found in the system
188
189 # Search for key entry and extract URI from it
190 response = self.get_request(f"{self.root_uri}{manager_uri}/{key}")
191 if response["ret"] is False:
192 return response
193 result["ret"] = True
194 data = response["data"]
195
196 if key not in data:
197 return {"ret": False, "msg": f"{command}: Key {key} not found", "warning": ""}
198
199 for attr_name, attr_value in attributes.items():
200 # Check if attribute exists
201 if attr_name not in data["Attributes"]:
202 # Skip and proceed to next attribute if this isn't valid
203 attrs_bad.update({attr_name: attr_value})
204 continue
205
206 # Find out if value is already set to what we want. If yes, exclude
207 # those attributes
208 if data["Attributes"][attr_name] == attr_value:
209 attrs_skipped.update({attr_name: attr_value})
210 else:
211 attrs_to_patch.update({attr_name: attr_value})
212
213 warning = ""
214 if attrs_bad:
215 warning = f"Incorrect attributes {attrs_bad}"
216
217 if not attrs_to_patch:
218 return {
219 "ret": True,
220 "changed": False,
221 "msg": "No changes made. Manager attributes already set.",
222 "warning": warning,
223 }
224
225 payload = {"Attributes": attrs_to_patch}
226 response = self.patch_request(f"{self.root_uri}{manager_uri}/{key}", payload)
227 if response["ret"] is False:
228 return response
229
230 return {
231 "ret": True,
232 "changed": True,
233 "msg": f"{command}: Modified Manager attributes {attrs_to_patch}",
234 "warning": warning,
235 }
236
237
238 CATEGORY_COMMANDS_ALL = {"Manager": ["SetManagerAttributes", "SetLifecycleControllerAttributes", "SetSystemAttributes"]}
239
240
241 # list of mutually exclusive commands for a category
242 CATEGORY_COMMANDS_MUTUALLY_EXCLUSIVE = {
243 "Manager": [["SetManagerAttributes", "SetLifecycleControllerAttributes", "SetSystemAttributes"]]
244 }
245
246
247 def main():
248 result = {}
249 argument_spec = dict(
250 category=dict(required=True),
251 command=dict(required=True, type="list", elements="str"),
252 baseuri=dict(required=True),
253 username=dict(),
254 password=dict(no_log=True),
255 auth_token=dict(no_log=True),
256 manager_attributes=dict(type="dict", default={}),
257 timeout=dict(type="int", default=10),
258 resource_id=dict(),
259 )
260 argument_spec.update(REDFISH_COMMON_ARGUMENT_SPEC)
261 module = AnsibleModule(
262 argument_spec,
263 required_together=[
264 ("username", "password"),
265 ],
266 required_one_of=[
267 ("username", "auth_token"),
268 ],
269 mutually_exclusive=[
270 ("username", "auth_token"),
271 ],
272 supports_check_mode=False,
273 )
274
275 category = module.params["category"]
276 command_list = module.params["command"]
277
278 # admin credentials used for authentication
279 creds = {"user": module.params["username"], "pswd": module.params["password"], "token": module.params["auth_token"]}
280
281 # timeout
282 timeout = module.params["timeout"]
283
284 # System, Manager or Chassis ID to modify
285 resource_id = module.params["resource_id"]
286
287 # Build root URI
288 root_uri = f"https://{module.params['baseuri']}"
289 rf_utils = IdracRedfishUtils(creds, root_uri, timeout, module, resource_id=resource_id, data_modification=True)
290
291 # Check that Category is valid
292 if category not in CATEGORY_COMMANDS_ALL:
293 module.fail_json(msg=f"Invalid Category '{category}'. Valid Categories = {list(CATEGORY_COMMANDS_ALL.keys())}")
294
295 # Check that all commands are valid
296 for cmd in command_list:
297 # Fail if even one command given is invalid
298 if cmd not in CATEGORY_COMMANDS_ALL[category]:
299 module.fail_json(msg=f"Invalid Command '{cmd}'. Valid Commands = {CATEGORY_COMMANDS_ALL[category]}")
300
301 # check for mutually exclusive commands
302 try:
303 # check_mutually_exclusive accepts a single list or list of lists that
304 # are groups of terms that should be mutually exclusive with one another
305 # and checks that against a dictionary
306 check_mutually_exclusive(CATEGORY_COMMANDS_MUTUALLY_EXCLUSIVE[category], dict.fromkeys(command_list, True))
307
308 except TypeError as e:
309 module.fail_json(msg=f"{e}")
310
311 # Organize by Categories / Commands
312
313 if category == "Manager":
314 # execute only if we find a Manager resource
315 result = rf_utils._find_managers_resource()
316 if result["ret"] is False:
317 module.fail_json(msg=result["msg"])
318
319 for command in command_list:
320 if command in ["SetManagerAttributes", "SetLifecycleControllerAttributes", "SetSystemAttributes"]:
321 result = rf_utils.set_manager_attributes(command)
322
323 # Return data back or fail with proper message
324 if result["ret"] is True:
325 if result.get("warning"):
326 module.warn(result["warning"])
327
328 module.exit_json(changed=result["changed"], msg=result["msg"])
329 else:
330 module.fail_json(msg=result["msg"])
331
332
333 if __name__ == "__main__":
334 main()