Debian Codegraph @

ansible_collections/community/general/plugins/modules/idrac_redfish_info.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_info
11 short_description: Gather PowerEdge server information through iDRAC using Redfish APIs
12 description:
13 - Builds Redfish URIs locally and sends them to remote iDRAC controllers to get information back.
14 - For use with Dell EMC iDRAC operations that require Redfish OEM extensions.
15 extends_documentation_fragment:
16 - community.general._attributes
17 - community.general._attributes.info_module
18 - community.general._redfish
19 attributes:
20 check_mode:
21 version_added: 3.3.0
22 # This was backported to 2.5.4 and 1.3.11 as well, since this was a bugfix
23 options:
24 category:
25 required: true
26 description:
27 - Category to execute on iDRAC.
28 type: str
29 command:
30 required: true
31 description:
32 - List of commands to execute on iDRAC.
33 - V(GetManagerAttributes) returns the list of dicts containing iDRAC, LifecycleController and System attributes.
34 type: list
35 elements: str
36 baseuri:
37 required: true
38 description:
39 - Base URI of iDRAC.
40 type: str
41 username:
42 description:
43 - Username for authenticating to iDRAC.
44 type: str
45 password:
46 description:
47 - Password for authenticating to iDRAC.
48 type: str
49 auth_token:
50 description:
51 - Security token for authenticating to iDRAC.
52 type: str
53 version_added: 2.3.0
54 timeout:
55 description:
56 - Timeout in seconds for HTTP requests to iDRAC.
57 default: 10
58 type: int
59 validate_certs:
60 version_added: 10.6.0
61 ca_path:
62 version_added: 10.6.0
63 ciphers:
64 version_added: 10.6.0
65
66 author: "Jose Delarosa (@jose-delarosa)"
67 """
68
69 EXAMPLES = r"""
70 - name: Get Manager attributes with a default of 20 seconds
71 community.general.idrac_redfish_info:
72 category: Manager
73 command: GetManagerAttributes
74 baseuri: "{{ baseuri }}"
75 username: "{{ username }}"
76 password: "{{ password }}"
77 timeout: 20
78 register: result
79
80 # Examples to display the value of all or a single iDRAC attribute
81 - name: Store iDRAC attributes as a fact variable
82 ansible.builtin.set_fact:
83 idrac_attributes: "{{ result.redfish_facts.entries | selectattr('Id', 'defined') | selectattr('Id', 'equalto', 'iDRACAttributes')
84 | list | first }}"
85
86 - name: Display all iDRAC attributes
87 ansible.builtin.debug:
88 var: idrac_attributes
89
90 - name: Display the value of 'Syslog.1.SysLogEnable' iDRAC attribute
91 ansible.builtin.debug:
92 var: idrac_attributes['Syslog.1.SysLogEnable']
93
94 # Examples to display the value of all or a single LifecycleController attribute
95 - name: Store LifecycleController attributes as a fact variable
96 ansible.builtin.set_fact:
97 lc_attributes: "{{ result.redfish_facts.entries | selectattr('Id', 'defined') | selectattr('Id', 'equalto', 'LCAttributes')
98 | list | first }}"
99
100 - name: Display LifecycleController attributes
101 ansible.builtin.debug:
102 var: lc_attributes
103
104 - name: Display the value of 'CollectSystemInventoryOnRestart' attribute
105 ansible.builtin.debug:
106 var: lc_attributes['LCAttributes.1.CollectSystemInventoryOnRestart']
107
108 # Examples to display the value of all or a single System attribute
109 - name: Store System attributes as a fact variable
110 ansible.builtin.set_fact:
111 system_attributes: "{{ result.redfish_facts.entries | selectattr('Id', 'defined') | selectattr('Id', 'equalto', 'SystemAttributes')
112 | list | first }}"
113
114 - name: Display System attributes
115 ansible.builtin.debug:
116 var: system_attributes
117
118 - name: Display the value of 'PSRedPolicy'
119 ansible.builtin.debug:
120 var: system_attributes['ServerPwr.1.PSRedPolicy']
121 """
122
123 RETURN = r"""
124 msg:
125 description: Different results depending on task.
126 returned: always
127 type: dict
128 sample: List of Manager attributes
129 """
130
131 from ansible.module_utils.basic import AnsibleModule
132
133 from ansible_collections.community.general.plugins.module_utils._redfish_utils import (
134 REDFISH_COMMON_ARGUMENT_SPEC,
135 RedfishUtils,
136 )
137
138
139 class IdracRedfishUtils(RedfishUtils):
140 def get_manager_attributes(self):
141 result = {}
142 response = {}
143 manager_attributes = []
144 properties = ["Attributes", "Id"]
145
146 if len(self.manager_uris) == 1:
147 response = self.get_request(f"{self.root_uri}{self.manager_uri}")
148 elif len(self.manager_uris) > 1:
149 response = self.get_request(f"{self.root_uri}/redfish/v1/Managers/iDRAC.Embedded.1", override_headers=None)
150
151 if response["ret"] is False:
152 return response
153 data = response["data"]
154
155 # Manager attributes are supported as part of iDRAC OEM extension
156 # Attributes are supported only on iDRAC9
157 try:
158 for members in data["Links"]["Oem"]["Dell"]["DellAttributes"]:
159 attributes_uri = members["@odata.id"]
160
161 response = self.get_request(self.root_uri + attributes_uri)
162 if response["ret"] is False:
163 return response
164 data = response["data"]
165
166 attributes = {}
167 for prop in properties:
168 if prop in data:
169 attributes[prop] = data.get(prop)
170
171 if attributes:
172 manager_attributes.append(attributes)
173
174 result["ret"] = True
175
176 except (AttributeError, KeyError) as e:
177 result["ret"] = False
178 result["msg"] = f"Failed to find attribute/key: {e}"
179
180 result["entries"] = manager_attributes
181 return result
182
183
184 CATEGORY_COMMANDS_ALL = {"Manager": ["GetManagerAttributes"]}
185
186
187 def main():
188 result = {}
189 argument_spec = dict(
190 category=dict(required=True),
191 command=dict(required=True, type="list", elements="str"),
192 baseuri=dict(required=True),
193 username=dict(),
194 password=dict(no_log=True),
195 auth_token=dict(no_log=True),
196 timeout=dict(type="int", default=10),
197 )
198 argument_spec.update(REDFISH_COMMON_ARGUMENT_SPEC)
199 module = AnsibleModule(
200 argument_spec,
201 required_together=[
202 ("username", "password"),
203 ],
204 required_one_of=[
205 ("username", "auth_token"),
206 ],
207 mutually_exclusive=[
208 ("username", "auth_token"),
209 ],
210 supports_check_mode=True,
211 )
212
213 category = module.params["category"]
214 command_list = module.params["command"]
215
216 # admin credentials used for authentication
217 creds = {"user": module.params["username"], "pswd": module.params["password"], "token": module.params["auth_token"]}
218
219 # timeout
220 timeout = module.params["timeout"]
221
222 # Build root URI
223 root_uri = f"https://{module.params['baseuri']}"
224 rf_utils = IdracRedfishUtils(creds, root_uri, timeout, module)
225
226 # Check that Category is valid
227 if category not in CATEGORY_COMMANDS_ALL:
228 module.fail_json(msg=f"Invalid Category '{category}'. Valid Categories = {list(CATEGORY_COMMANDS_ALL.keys())}")
229
230 # Check that all commands are valid
231 for cmd in command_list:
232 # Fail if even one command given is invalid
233 if cmd not in CATEGORY_COMMANDS_ALL[category]:
234 module.fail_json(msg=f"Invalid Command '{cmd}'. Valid Commands = {CATEGORY_COMMANDS_ALL[category]}")
235
236 # Organize by Categories / Commands
237
238 if category == "Manager":
239 # execute only if we find a Manager resource
240 result = rf_utils._find_managers_resource()
241 if result["ret"] is False:
242 module.fail_json(msg=result["msg"])
243
244 for command in command_list:
245 if command == "GetManagerAttributes":
246 result = rf_utils.get_manager_attributes()
247
248 # Return data back or fail with proper message
249 if result["ret"] is True:
250 del result["ret"]
251 module.exit_json(redfish_facts=result)
252 else:
253 module.fail_json(msg=result["msg"])
254
255
256 if __name__ == "__main__":
257 main()