Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/idrac_redfish_storage_controller.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) 2019-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
13 from __future__ import (absolute_import, division, print_function)
14 __metaclass__ = type
15
16 DOCUMENTATION = r'''
17 ---
18 module: idrac_redfish_storage_controller
19 short_description: Configures the physical disk, virtual disk, and storage controller settings
20 version_added: "2.1.0"
21 description:
22 - This module allows the users to configure the settings of the physical disk, virtual disk,
23 and storage controller.
24 extends_documentation_fragment:
25 - dellemc.openmanage.redfish_auth_options
26 options:
27 command:
28 description:
29 - These actions may require a system reset, depending on the capabilities of the controller.
30 - C(ResetConfig) - Deletes all the virtual disks and unassigns all hot spares on physical disks.
31 I(controller_id) is required for this operation.
32 - C(AssignSpare) - Assigns a physical disk as a dedicated or global hot spare for a virtual disk.
33 I(target) is required for this operation.
34 - C(SetControllerKey) - Sets the key on controllers, which is used to encrypt the drives in Local
35 Key Management(LKM). I(controller_id), I(key), and I(key_id) are required for this operation.
36 - C(RemoveControllerKey) - Deletes the encryption key on the controller.
37 I(controller_id) is required for this operation.
38 - C(ReKey) - Resets the key on the controller and it always reports as changes found when check mode is enabled.
39 I(controller_id), I(old_key), I(key_id), and I(key) is required for this operation.
40 - C(UnassignSpare) - To unassign the Global or Dedicated hot spare. I(target) is required for this operation.
41 - C(EnableControllerEncryption) - To enable Local Key Management (LKM) or Secure Enterprise Key Manager (SEKM)
42 on controllers that support encryption of the drives. I(controller_id), I(key), and I(key_id) are required
43 for this operation.
44 - C(BlinkTarget) - Blinks the target virtual drive or physical disk and it always reports as changes found
45 when check mode is enabled. I(target) or I(volume_id) is required for this operation.
46 - C(UnBlinkTarget) - Unblink the target virtual drive or physical disk and and it always reports as changes
47 found when check mode is enabled. I(target) or I(volume_id) is required for this operation.
48 - C(ConvertToRAID) - Converts the disk form non-Raid to Raid. I(target) is required for this operation.
49 - C(ConvertToNonRAID) - Converts the disk form Raid to non-Raid. I(target) is required for this operation.
50 - C(ChangePDStateToOnline) - To set the disk status to online. I(target) is required for this operation.
51 - C(ChangePDStateToOffline) - To set the disk status to offline. I(target) is required for this operation.
52 - C(LockVirtualDisk) - To encrypt the virtual disk. I(volume_id) is required for this operation.
53 - C(OnlineCapacityExpansion) - To expand the size of virtual disk. I(volume_id), and I(target) or I(size) is required for this operation.
54 - C(SecureErase) - To delete all the data on the physical disk securely. This option is available for
55 Self-Encrypting Drives (SED), Instant Scramble Erase (ISE) drives, and PCIe SSD devices (drives and cards).
56 The drives must be in a ready state. I(controller_id) and I(target) are required for this operation,
57 I(target) must be a single physical disk ID. If a secure erase needs a reboot,
58 the job will get scheduled and waits for no of seconds specfied in I(job_wait_time),
59 to reduce the wait time either give I(job_wait_time) minimum or make I(job_wait)
60 as false.
61 - C(EnableSecurity) - To enable security on a storage controller. Only Applicable for 17G and above.
62 - C(DisableSecurity) - To disable security on a storage controller. Only Applicable for 17G and above.
63 - C(SetControllerKey), C(RemoveControllerKey), C(ReKey) and C(EnableControllerEncryption) are only supported for 16G and below.
64 - Blinking of virtual disk is not supported for 17G and above.
65 choices: [ResetConfig, AssignSpare, SetControllerKey, RemoveControllerKey, ReKey, UnassignSpare,
66 EnableControllerEncryption, BlinkTarget, UnBlinkTarget, ConvertToRAID, ConvertToNonRAID,
67 ChangePDStateToOnline, ChangePDStateToOffline, LockVirtualDisk, OnlineCapacityExpansion, SecureErase,
68 EnableSecurity, DisableSecurity]
69 type: str
70 target:
71 description:
72 - Fully Qualified Device Descriptor (FQDD) of the target physical drive.
73 - This is mandatory when I(command) is C(AssignSpare), C(UnassisgnSpare),
74 C(ChangePDStateToOnline), C(ChangePDStateToOffline), C(ConvertToRAID), or C(ConvertToNonRAID).
75 - If I(volume_id) is not specified or empty, this physical drive will be
76 assigned as a global hot spare when I(command) is C(AssignSpare).
77 - When I(command) is C(OnlineCapacityExpansion), then I(target) is mutually exclusive with I(size).
78 - "Notes: Global or Dedicated hot spare can be assigned only once for a physical disk,
79 Re-assign cannot be done when I(command) is C(AssignSpare)."
80 type: list
81 elements: str
82 aliases: [drive_id]
83 volume_id:
84 description:
85 - Fully Qualified Device Descriptor (FQDD) of the volume.
86 - Applicable if I(command) is C(AssignSpare), C(BlinkTarget), C(UnBlinkTarget) or C(LockVirtualDisk).
87 - I(volume_id) or I(target) is required when the I(command) is C(BlinkTarget) or C(UnBlinkTarget),
88 if both are specified I(target) is considered.
89 - To know the number of volumes to which a hot spare can be assigned, refer iDRAC Redfish API documentation.
90 type: list
91 elements: str
92 controller_id:
93 description:
94 - Fully Qualified Device Descriptor (FQDD) of the storage controller. For example-'RAID.Slot.1-1'.
95 - This option is mandatory when I(command) is C(ResetConfig), C(SetControllerKey),
96 C(RemoveControllerKey), C(ReKey), or C(EnableControllerEncryption).
97 - This option is mandatory for I(attributes).
98 type: str
99 key:
100 description:
101 - A new security key passphrase that the encryption-capable controller uses to create the
102 encryption key. The controller uses the encryption key to lock or unlock access to the
103 Self-Encrypting Drive (SED). Only one encryption key can be created for each controller.
104 - This is mandatory when I(command) is C(SetControllerKey), C(ReKey), or C(EnableControllerEncryption)
105 and when I(mode) is C(LKM).
106 - The length of the key can be a maximum of 32 characters in length, where the expanded form of
107 the special character is counted as a single character.
108 - "The key must contain at least one character from each of the character classes: uppercase,
109 lowercase, number, and special character."
110 type: str
111 key_id:
112 description:
113 - This is a user supplied text label associated with the passphrase.
114 - This is mandatory when I(command) is C(SetControllerKey), C(ReKey), or C(EnableControllerEncryption)
115 and when I(mode) is C(LKM).
116 - The length of I(key_id) can be a maximum of 32 characters in length and should not have any spaces.
117 type: str
118 old_key:
119 description:
120 - Security key passphrase used by the encryption-capable controller.
121 - This option is mandatory when I(command) is C(ReKey) and I(mode) is C(LKM).
122 type: str
123 mode:
124 description:
125 - Encryption mode of the encryption capable controller.
126 - This option is applicable only when I(command) is C(ReKey) or C(EnableControllerEncryption).
127 - C(SEKM) requires secure enterprise key manager license on the iDRAC.
128 - C(LKM) to choose mode as local key mode.
129 choices: [LKM, SEKM]
130 default: LKM
131 type: str
132 size:
133 description:
134 - Capacity of the virtual disk to be expanded in MB.
135 - Check mode and Idempotency is not supported for I(size).
136 - Minimum Online Capacity Expansion size must be greater than 100 MB of the current size.
137 - When I(command) is C(OnlineCapacityExpansion), then I(size) is mutually exclusive with I(target).
138 type: int
139 attributes:
140 type: dict
141 description:
142 - Dictionary of controller attributes and value pair.
143 - This feature is only supported for iDRAC9 with firmware version 6.00.00.00 and above
144 - I(controller_id) is required for this operation.
145 - I(apply_time) and I(maintenance_window) is applicable for I(attributes).
146 - I(attributes) is mutually exclusive with I(command).
147 - Use U(https://I(idrac_ip)/redfish/v1/Schemas/DellOemStorageController.json) to view the attributes.
148 - C(BackgroundInitializationRatePercent) and C(ReconstructRatePercent) are supported parameters for iDRAC 10.
149 apply_time:
150 type: str
151 description:
152 - Apply time of the I(attributes).
153 - This is applicable only to I(attributes).
154 - "C(Immediate) Allows the user to immediately reboot the host and apply the changes. I(job_wait)
155 is applicable."
156 - C(OnReset) Allows the user to apply the changes on the next reboot of the host server.
157 - "C(AtMaintenanceWindowStart) Allows the user to apply at the start of a maintenance window as specified
158 in I(maintenance_window)."
159 - "C(InMaintenanceWindowOnReset) Allows to apply after a manual reset but within the maintenance window as
160 specified in I(maintenance_window)."
161 - Only C(Immediate) and C(OnReset) are supported for 17G.
162 choices: [Immediate, OnReset, AtMaintenanceWindowStart, InMaintenanceWindowOnReset]
163 default: Immediate
164 maintenance_window:
165 type: dict
166 description:
167 - Option to schedule the maintenance window.
168 - This is required when I(apply_time) is C(AtMaintenanceWindowStart) or C(InMaintenanceWindowOnReset).
169 suboptions:
170 start_time:
171 type: str
172 description:
173 - The start time for the maintenance window to be scheduled.
174 - "The format is YYYY-MM-DDThh:mm:ss<offset>"
175 - "<offset> is the time offset from UTC that the current timezone set in
176 iDRAC in the format: +05:30 for IST."
177 required: true
178 duration:
179 type: int
180 description:
181 - The duration in seconds for the maintenance window.
182 default: 900
183 job_wait:
184 description:
185 - Provides the option if the module has to wait for the job to be completed.
186 - This is applicable for I(attributes) when I(apply_time) is C(Immediate)
187 and when I(command) is C(SecureErase).
188 type: bool
189 default: false
190 job_wait_timeout:
191 description:
192 - The maximum wait time of job completion in seconds before the job tracking is stopped.
193 - This option is applicable when I(job_wait) is C(true).
194 - "Note: When I(command) is C(SecureErase), If a secure erase needs a reboot,
195 the job will get scheduled and waits for no of seconds specfied in I(job_wait_time),
196 to reduce the wait time either give I(job_wait_time) a lesser value or make I(job_wait)
197 as false."
198 type: int
199 default: 120
200 requirements:
201 - "python >= 3.9.6"
202 author:
203 - "Jagadeesh N V (@jagadeeshnv)"
204 - "Felix Stephen (@felixs88)"
205 - "Husniya Hameed (@husniya_hameed)"
206 - "Abhishek Sinha (@ABHISHEK-SINHA10)"
207 - "Shivam Sharma (@ShivamSh3)"
208 - "Trisha Datta (@trisha-dell)"
209 notes:
210 - Run this module from a system that has direct access to Dell iDRAC.
211 - This module is supported on iDRAC9 and iDRAC 10.
212 - This module supports IPv4 and IPv6 addresses.
213 - This module always reports as changes found when I(command) is C(ReKey), C(BlinkTarget), and C(UnBlinkTarget).
214 - This module supports C(check_mode).
215
216 '''
217
218 EXAMPLES = r'''
219 ---
220 - name: Assign dedicated hot spare
221 dellemc.openmanage.idrac_redfish_storage_controller:
222 baseuri: "192.168.0.1:443"
223 username: "user_name"
224 password: "user_password"
225 ca_path: "/path/to/ca_cert.pem"
226 volume_id:
227 - "Disk.Virtual.0:RAID.Slot.1-1"
228 target: "Disk.Bay.0:Enclosure.Internal.0-1:RAID.Slot.1-1"
229 tags:
230 - assign_dedicated_hot_spare
231
232 - name: Assign global hot spare
233 dellemc.openmanage.idrac_redfish_storage_controller:
234 baseuri: "192.168.0.1:443"
235 username: "user_name"
236 password: "user_password"
237 ca_path: "/path/to/ca_cert.pem"
238 target: "Disk.Bay.0:Enclosure.Internal.0-1:RAID.Slot.1-1"
239 tags:
240 - assign_global_hot_spare
241
242 - name: Unassign hot spare
243 dellemc.openmanage.idrac_redfish_storage_controller:
244 baseuri: "192.168.0.1:443"
245 username: "user_name"
246 password: "user_password"
247 ca_path: "/path/to/ca_cert.pem"
248 target: "Disk.Bay.0:Enclosure.Internal.0-1:RAID.Slot.1-1"
249 command: UnassignSpare
250 tags:
251 - un-assign-hot-spare
252
253 - name: Set controller encryption key
254 dellemc.openmanage.idrac_redfish_storage_controller:
255 baseuri: "192.168.0.1:443"
256 username: "user_name"
257 password: "user_password"
258 ca_path: "/path/to/ca_cert.pem"
259 command: "SetControllerKey"
260 controller_id: "RAID.Slot.1-1"
261 key: "PassPhrase@123"
262 key_id: "mykeyid123"
263 tags:
264 - set_controller_key
265
266 - name: Rekey in LKM mode
267 dellemc.openmanage.idrac_redfish_storage_controller:
268 baseuri: "192.168.0.1:443"
269 username: "user_name"
270 password: "user_password"
271 ca_path: "/path/to/ca_cert.pem"
272 command: "ReKey"
273 controller_id: "RAID.Slot.1-1"
274 key: "NewPassPhrase@123"
275 key_id: "newkeyid123"
276 old_key: "OldPassPhrase@123"
277 tags:
278 - rekey_lkm
279
280 - name: Rekey in SEKM mode
281 dellemc.openmanage.idrac_redfish_storage_controller:
282 baseuri: "192.168.0.1:443"
283 username: "user_name"
284 password: "user_password"
285 ca_path: "/path/to/ca_cert.pem"
286 command: "ReKey"
287 controller_id: "RAID.Slot.1-1"
288 mode: "SEKM"
289 tags:
290 - rekey_sekm
291
292 - name: Remove controller key
293 dellemc.openmanage.idrac_redfish_storage_controller:
294 baseuri: "192.168.0.1:443"
295 username: "user_name"
296 password: "user_password"
297 ca_path: "/path/to/ca_cert.pem"
298 command: "RemoveControllerKey"
299 controller_id: "RAID.Slot.1-1"
300 tags:
301 - remove_controller_key
302
303 - name: Reset controller configuration
304 dellemc.openmanage.idrac_redfish_storage_controller:
305 baseuri: "192.168.0.1:443"
306 username: "user_name"
307 password: "user_password"
308 ca_path: "/path/to/ca_cert.pem"
309 command: "ResetConfig"
310 controller_id: "RAID.Slot.1-1"
311 tags:
312 - reset_config
313
314 - name: Enable controller encryption
315 idrac_redfish_storage_controller:
316 baseuri: "{{ baseuri }}"
317 username: "{{ username }}"
318 password: "{{ password }}"
319 ca_path: "/path/to/ca_cert.pem"
320 command: "EnableControllerEncryption"
321 controller_id: "RAID.Slot.1-1"
322 mode: "LKM"
323 key: "your_Key@123"
324 key_id: "your_Keyid@123"
325 tags:
326 - enable-encrypt
327
328 - name: Blink physical disk.
329 dellemc.openmanage.idrac_redfish_storage_controller:
330 baseuri: "192.168.0.1:443"
331 username: "user_name"
332 password: "user_password"
333 ca_path: "/path/to/ca_cert.pem"
334 command: BlinkTarget
335 target: "Disk.Bay.0:Enclosure.Internal.0-1:RAID.Slot.1-1"
336 tags:
337 - blink-target
338
339 - name: Blink virtual drive.
340 dellemc.openmanage.idrac_redfish_storage_controller:
341 baseuri: "192.168.0.1:443"
342 username: "user_name"
343 password: "user_password"
344 ca_path: "/path/to/ca_cert.pem"
345 command: BlinkTarget
346 volume_id: "Disk.Virtual.0:RAID.Slot.1-1"
347 tags:
348 - blink-volume
349
350 - name: Unblink physical disk.
351 dellemc.openmanage.idrac_redfish_storage_controller:
352 baseuri: "192.168.0.1:443"
353 username: "user_name"
354 password: "user_password"
355 ca_path: "/path/to/ca_cert.pem"
356 command: UnBlinkTarget
357 target: "Disk.Bay.0:Enclosure.Internal.0-1:RAID.Slot.1-1"
358 tags:
359 - unblink-target
360
361 - name: Unblink virtual drive.
362 dellemc.openmanage.idrac_redfish_storage_controller:
363 baseuri: "192.168.0.1:443"
364 username: "user_name"
365 password: "user_password"
366 ca_path: "/path/to/ca_cert.pem"
367 command: UnBlinkTarget
368 volume_id: "Disk.Virtual.0:RAID.Slot.1-1"
369 tags:
370 - unblink-drive
371
372 - name: Convert physical disk to RAID
373 dellemc.openmanage.idrac_redfish_storage_controller:
374 baseuri: "192.168.0.1:443"
375 username: "user_name"
376 password: "user_password"
377 ca_path: "/path/to/ca_cert.pem"
378 command: "ConvertToRAID"
379 target: "Disk.Bay.0:Enclosure.Internal.0-1:RAID.Slot.1-1"
380 tags:
381 - convert-raid
382
383 - name: Convert physical disk to non-RAID
384 dellemc.openmanage.idrac_redfish_storage_controller:
385 baseuri: "192.168.0.1:443"
386 username: "user_name"
387 password: "user_password"
388 ca_path: "/path/to/ca_cert.pem"
389 command: "ConvertToNonRAID"
390 target: "Disk.Bay.0:Enclosure.Internal.0-1:RAID.Slot.1-1"
391 tags:
392 - convert-non-raid
393
394 - name: Change physical disk state to online.
395 dellemc.openmanage.idrac_redfish_storage_controller:
396 baseuri: "192.168.0.1:443"
397 username: "user_name"
398 password: "user_password"
399 ca_path: "/path/to/ca_cert.pem"
400 command: "ChangePDStateToOnline"
401 target: "Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-1"
402 tags:
403 - pd-state-online
404
405 - name: Change physical disk state to offline.
406 dellemc.openmanage.idrac_redfish_storage_controller:
407 baseuri: "192.168.0.1:443"
408 username: "user_name"
409 password: "user_password"
410 ca_path: "/path/to/ca_cert.pem"
411 command: "ChangePDStateToOnline"
412 target: "Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-1"
413 tags:
414 - pd-state-offline
415
416 - name: Lock virtual drive
417 dellemc.openmanage.idrac_redfish_storage_controller:
418 baseuri: "192.168.0.1:443"
419 username: "user_name"
420 password: "user_password"
421 ca_path: "/path/to/ca_cert.pem"
422 command: "LockVirtualDisk"
423 volume_id: "Disk.Virtual.0:RAID.SL.3-1"
424 tags:
425 - lock
426
427 - name: Online Capacity Expansion of a volume using target
428 dellemc.openmanage.idrac_redfish_storage_controller:
429 baseuri: "{{ baseuri }}"
430 username: "{{ username }}"
431 password: "{{ password }}"
432 ca_path: "/path/to/ca_cert.pem"
433 command: "OnlineCapacityExpansion"
434 volume_id: "Disk.Virtual.0:RAID.Integrated.1-1"
435 target:
436 - "Disk.Bay.2:Enclosure.Internal.0-0:RAID.Integrated.1-1"
437 tags:
438 - oce_target
439
440 - name: Online Capacity Expansion of a volume using size
441 dellemc.openmanage.idrac_redfish_storage_controller:
442 baseuri: "{{ baseuri }}"
443 username: "{{ username }}"
444 password: "{{ password }}"
445 ca_path: "/path/to/ca_cert.pem"
446 command: "OnlineCapacityExpansion"
447 volume_id: "Disk.Virtual.0:RAID.Integrated.1-1"
448 size: 362785
449 tags:
450 - oce_size
451
452 - name: Set controller attributes.
453 dellemc.openmanage.idrac_redfish_storage_controller:
454 baseuri: "192.168.0.1:443"
455 username: "user_name"
456 password: "user_password"
457 ca_path: "/path/to/ca_cert.pem"
458 controller_id: "RAID.Slot.1-1"
459 attributes:
460 ControllerMode: "HBA"
461 apply_time: "OnReset"
462 tags:
463 - controller-attribute
464
465 - name: Configure controller attributes at Maintenance window
466 dellemc.openmanage.idrac_redfish_storage_controller:
467 baseuri: "192.168.0.1:443"
468 username: "user_name"
469 password: "user_password"
470 ca_path: "/path/to/ca_cert.pem"
471 controller_id: "RAID.Slot.1-1"
472 attributes:
473 CheckConsistencyMode: Normal
474 CopybackMode: "Off"
475 LoadBalanceMode: Disabled
476 apply_time: AtMaintenanceWindowStart
477 maintenance_window:
478 start_time: "2022-09-30T05:15:40-05:00"
479 duration: 1200
480
481 - name: Perform Secure Erase operation on SED drive
482 dellemc.openmanage.idrac_redfish_storage_controller:
483 baseuri: "192.168.0.1:443"
484 username: "user_name"
485 password: "user_password"
486 ca_path: "/path/to/ca_cert.pem"
487 controller_id: "RAID.Slot.1-1"
488 command: "SecureErase"
489 target: "Disk.Bay.1:Enclosure.Internal.0-1:RAID.Slot.1-1"
490 '''
491
492 RETURN = r'''
493 ---
494 msg:
495 type: str
496 description: Overall status of the storage controller configuration operation.
497 returned: always
498 sample: "Successfully submitted the job that performs the AssignSpare operation"
499 task:
500 type: dict
501 description: ID and URI resource of the job created.
502 returned: success
503 sample: {
504 "id": "JID_XXXXXXXXXXXXX",
505 "uri": "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs/JID_XXXXXXXXXXXXX"
506 }
507 status:
508 type: dict
509 description: status of the submitted job.
510 returned: always
511 sample: {
512 "ActualRunningStartTime": "2022-02-09T04:42:41",
513 "ActualRunningStopTime": "2022-02-09T04:44:00",
514 "CompletionTime": "2022-02-09T04:44:00",
515 "Description": "Job Instance",
516 "EndTime": "TIME_NA",
517 "Id": "JID_444033604418",
518 "JobState": "Completed",
519 "JobType": "RealTimeNoRebootConfiguration",
520 "Message": "Job completed successfully.",
521 "MessageArgs":[],
522 "MessageId": "PR19",
523 "Name": "Configure: RAID.Integrated.1-1",
524 "PercentComplete": 100,
525 "StartTime": "2022-02-09T04:42:40",
526 "TargetSettingsURI": null
527 }
528 error_info:
529 type: dict
530 description: Details of a http error.
531 returned: on http error
532 sample: {
533 "error": {
534 "@Message.ExtendedInfo": [
535 {
536 "Message": "Unable to run the method because the requested HTTP method is not allowed.",
537 "MessageArgs": [],
538 "[email protected]": 0,
539 "MessageId": "iDRAC.1.6.SYS402",
540 "RelatedProperties": [],
541 "[email protected]": 0,
542 "Resolution": "Enter a valid HTTP method and retry the operation. For information about
543 valid methods, see the Redfish Users Guide available on the support site.",
544 "Severity": "Informational"
545 }
546 ],
547 "code": "Base.1.0.GeneralError",
548 "message": "A general error has occurred. See ExtendedInfo for more information"
549 }
550 }
551 '''
552
553
554 import re
555 import json
556 from ansible.module_utils.compat.version import LooseVersion
557 from ansible_collections.dellemc.openmanage.plugins.module_utils.redfish import Redfish, RedfishAnsibleModule
558 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import wait_for_job_completion, strip_substr_dict, \
559 get_dynamic_uri, validate_and_get_first_resource_id_uri, get_idrac_firmware_version, get_scheduled_job_resp
560 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
561 from ansible.module_utils.urls import ConnectionError, SSLValidationError
562
563
564 SYSTEMS_URI = "/redfish/v1/Systems/"
565 SYSTEM_ID = "System.Embedded.1"
566 MANAGER_ID = "iDRAC.Embedded.1"
567 RAID_ACTION_URI = "/redfish/v1/Systems/{system_id}/Oem/Dell/DellRaidService/Actions/DellRaidService.{action}"
568 CONTROLLER_URI = "/redfish/v1/Systems/{system_id}/Storage/{controller_id}"
569 VOLUME_URI = "/redfish/v1/Systems/{system_id}/Storage/{controller_id}/Volumes"
570 PD_URI = "/redfish/v1/Systems/System.Embedded.1/Storage/{controller_id}/Drives/{drive_id}"
571 JOB_URI_OEM = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs/{job_id}"
572 CONTROLLERS_URI = "/redfish/v1/Systems/{system_id}/Storage/{controller_id}/Controllers/{controller_id}"
573 MANAGER_URI = "/redfish/v1/Managers/iDRAC.Embedded.1"
574 SETTINGS_URI = "/redfish/v1/Systems/{system_id}/Storage/{controller_id}/Controllers/{controller_id}/Settings"
575 OCE_MIN_PD_RAID_MAPPING = {'RAID0': 1, 'RAID5': 1, 'RAID6': 1, 'RAID10': 2}
576 ODATA_ID = "@odata.id"
577
578 JOB_SUBMISSION = "Successfully submitted the job that performs the '{0}' operation."
579 JOB_COMPLETION = "Successfully performed the '{0}' operation."
580 JOB_EXISTS = "Unable to complete the operation because another job already " \
581 "exists. Wait for the pending job to complete and retry the operation."
582 CHANGES_FOUND = "Changes found to be applied."
583 NO_CHANGES_FOUND = "No changes found to be applied."
584 TARGET_ERR_MSG = "The Fully Qualified Device Descriptor (FQDD) of the target {0} must be only one."
585 CNTRL_ERROR_MSG = "Unable to locate the storage controller with the ID: {0}"
586 PD_ERROR_MSG = "Unable to locate the physical disk with the ID: {0}"
587 VD_ERROR_MSG = "Unable to locate the virtual disk with the ID: {0}"
588 ENCRYPT_ERR_MSG = "The storage controller '{0}' does not support encryption."
589 PHYSICAL_DISK_ERR = "Volume is not encryption capable."
590 DRIVE_NOT_SECURE_ERASE = "Drive {0} does not support secure erase operation."
591 DRIVE_NOT_READY = "Drive {0} is not in ready state."
592 OCE_RAID_TYPE_ERR = "Online Capacity Expansion is not supported for {0} virtual disks."
593 OCE_SIZE_100MB = "Minimum Online Capacity Expansion size must be greater than 100 MB of the current size {0}."
594 OCE_TARGET_EMPTY = "Provided list of targets is empty."
595 OCE_TARGET_RAID1_ERR = "Cannot add more than two disks to RAID1 virtual disk."
596 UNSUPPORTED_APPLY_TIME = "Apply time {0} is not supported."
597 MAINTENANCE_OFFSET = "The maintenance time must be post-fixed with local offset to {0}."
598 MAINTENANCE_TIME = "The specified maintenance time window occurs in the past, " \
599 "provide a future time to schedule the maintenance window."
600 HBA_MODE = "Other attributes cannot be updated when ControllerMode is provided as input."
601 INVALID_ATTRIBUTES = "The following attributes are invalid: {0}"
602 CONTROLLER_ID_REQUIRED = "controller_id is required to perform this operation."
603 JOB_COMPLETION_ATTRIBUTES = "Successfully applied the controller attributes."
604 JOB_SUBMISSION_ATTRIBUTES = "Successfully submitted the job that configures the controller attributes."
605 ERR_MSG = "Unable to configure the controller attribute(s) settings."
606 INVALID_KEY_ID = "The keyid should be of maximum length 32 and only alphanumeric characters are allowed without spaces."
607 INVALID_KEY = ("The key should be of maximum length 32 and must contain at least one "
608 "character from each of the character classes: uppercase, lowercase, "
609 "number, and special character.")
610 INVALID_START_TIME = "The start time should be in the format YYYY-MM-DDThh:mm:ss<offset>"
611 INVALID_COMMAND = "The command {0} is not applicable for {1}"
612
613
614 def check_id_exists(module, redfish_obj, key, item_id, uri):
615 msg = "{0} with id '{1}' not found in system".format(key, item_id)
616 try:
617 resp = redfish_obj.invoke_request("GET", uri.format(system_id=SYSTEM_ID, controller_id=item_id))
618 if not resp.success:
619 module.exit_json(msg=msg, failed=True)
620 except HTTPError as err:
621 module.exit_json(msg=msg, error_info=json.load(err), failed=True)
622
623
624 def handle_set_controller_key(module, controller_id, ctrl_key_id, key, key_id, payload):
625 if module.check_mode and ctrl_key_id is None:
626 module.exit_json(msg=CHANGES_FOUND, changed=True)
627 elif module.check_mode or ctrl_key_id is not None:
628 module.exit_json(msg=NO_CHANGES_FOUND)
629 payload.update({"TargetFQDD": controller_id, "Key": key, "Keyid": key_id})
630
631
632 def handle_rekey(module, controller_id, mode, key, key_id, payload):
633 if module.check_mode:
634 module.exit_json(msg=CHANGES_FOUND, changed=True)
635 if mode == "LKM":
636 payload.update({"TargetFQDD": controller_id, "Mode": mode, "NewKey": key,
637 "Keyid": key_id, "OldKey": module.params.get("old_key")})
638 else:
639 payload.update({"TargetFQDD": controller_id, "Mode": mode})
640
641
642 def handle_remove_controller_key(module, controller_id, ctrl_key_id, payload):
643 if module.check_mode and ctrl_key_id is not None:
644 module.exit_json(msg=CHANGES_FOUND, changed=True)
645 elif module.check_mode or ctrl_key_id is None:
646 module.exit_json(msg=NO_CHANGES_FOUND)
647 payload.update({"TargetFQDD": controller_id})
648
649
650 def handle_enable_controller_encryption(module, controller_id, security_status, mode, key, key_id, payload):
651 if module.check_mode and security_status != "SecurityKeyAssigned":
652 module.exit_json(msg=CHANGES_FOUND, changed=True)
653 elif (module.check_mode and security_status == "SecurityKeyAssigned") or (not module.check_mode and security_status == "SecurityKeyAssigned"):
654 module.exit_json(msg=NO_CHANGES_FOUND)
655 payload.update({"TargetFQDD": controller_id, "Mode": mode})
656 if mode == "LKM":
657 payload.update({"Key": key, "Keyid": key_id})
658
659
660 def ctrl_key(module, redfish_obj):
661 resp, job_uri, job_id, payload = None, None, None, {}
662 controller_id = module.params.get("controller_id")
663 command, mode = module.params["command"], module.params["mode"]
664 key, key_id = module.params.get("key"), module.params.get("key_id")
665
666 check_id_exists(module, redfish_obj, "controller_id",
667 controller_id, CONTROLLER_URI)
668 ctrl_resp = redfish_obj.invoke_request("GET", CONTROLLER_URI.format(
669 system_id=SYSTEM_ID, controller_id=controller_id))
670
671 security_status = ctrl_resp.json_data.get("Oem", {}).get("Dell", {}).get("DellController", {}).get("SecurityStatus")
672 if security_status == "EncryptionNotCapable":
673 module.fail_json(msg=ENCRYPT_ERR_MSG.format(controller_id))
674
675 ctrl_key_id = ctrl_resp.json_data.get("Oem", {}).get("Dell", {}).get("DellController", {}).get("KeyID")
676
677 if command == "SetControllerKey":
678 handle_set_controller_key(
679 module, controller_id, ctrl_key_id, key, key_id, payload)
680 elif command == "ReKey":
681 handle_rekey(module, controller_id, mode, key, key_id, payload)
682 elif command == "RemoveControllerKey":
683 handle_remove_controller_key(
684 module, controller_id, ctrl_key_id, payload)
685 elif command == "EnableControllerEncryption":
686 handle_enable_controller_encryption(
687 module, controller_id, security_status, mode, key, key_id, payload)
688
689 resp = redfish_obj.invoke_request("POST", RAID_ACTION_URI.format(
690 system_id=SYSTEM_ID, action=command), data=payload)
691 job_uri = resp.headers.get("Location")
692 job_id = job_uri.split("/")[-1]
693
694 return resp, job_uri, job_id
695
696
697 def ctrl_reset_config(module, redfish_obj):
698 resp, job_uri, job_id = None, None, None
699 controller_id = module.params.get("controller_id")
700 check_id_exists(module, redfish_obj, "controller_id", controller_id, CONTROLLER_URI)
701 member_resp = redfish_obj.invoke_request("GET", VOLUME_URI.format(system_id=SYSTEM_ID, controller_id=controller_id))
702 members = member_resp.json_data.get("Members")
703 if module.check_mode and members:
704 module.exit_json(msg=CHANGES_FOUND, changed=True)
705 elif (module.check_mode and not members) or (not module.check_mode and not members):
706 module.exit_json(msg=NO_CHANGES_FOUND)
707 else:
708 resp = redfish_obj.invoke_request("POST", RAID_ACTION_URI.format(system_id=SYSTEM_ID,
709 action=module.params["command"]),
710 data={"TargetFQDD": controller_id})
711 job_uri = resp.headers.get("Location")
712 job_id = job_uri.split("/")[-1]
713 return resp, job_uri, job_id
714
715
716 def enable_security(module, redfish_obj):
717 resp, job_uri, job_id = None, None, None
718 controller_id = module.params.get("controller_id")
719 check_id_exists(module, redfish_obj, "controller_id", controller_id, CONTROLLER_URI)
720 controller_resp = redfish_obj.invoke_request("GET", CONTROLLER_URI.format(system_id=SYSTEM_ID, controller_id=controller_id))
721 encryption_mode = controller_resp.json_data.get("Oem", {}).get("Dell", {}).get("DellController", {}).get("EncryptionMode")
722 if encryption_mode == "Enabled":
723 module.exit_json(msg=NO_CHANGES_FOUND)
724 elif module.check_mode and encryption_mode == "Disabled":
725 module.exit_json(msg=CHANGES_FOUND, changed=True)
726 else:
727 resp = redfish_obj.invoke_request("POST", RAID_ACTION_URI.format(system_id=SYSTEM_ID,
728 action=module.params["command"]),
729 data={"TargetFQDD": controller_id})
730 job_uri = resp.headers.get("Location")
731 job_id = job_uri.split("/")[-1]
732 return resp, job_uri, job_id
733
734
735 def disable_security(module, redfish_obj):
736 resp, job_uri, job_id = None, None, None
737 controller_id = module.params.get("controller_id")
738 check_id_exists(module, redfish_obj, "controller_id", controller_id, CONTROLLER_URI)
739 controller_resp = redfish_obj.invoke_request("GET", CONTROLLER_URI.format(system_id=SYSTEM_ID, controller_id=controller_id))
740 encryption_mode = controller_resp.json_data.get("Oem", {}).get("Dell", {}).get("DellController", {}).get("EncryptionMode")
741 if encryption_mode == "Disabled":
742 module.exit_json(msg=NO_CHANGES_FOUND)
743 elif module.check_mode and encryption_mode == "Enabled":
744 module.exit_json(msg=CHANGES_FOUND, changed=True)
745 else:
746 resp = redfish_obj.invoke_request("POST", RAID_ACTION_URI.format(system_id=SYSTEM_ID,
747 action=module.params["command"]),
748 data={"ControllerFQDD": controller_id})
749 job_uri = resp.headers.get("Location")
750 job_id = job_uri.split("/")[-1]
751 return resp, job_uri, job_id
752
753
754 def hot_spare_config(module, redfish_obj):
755 target, command = module.params.get("target"), module.params["command"]
756 resp, job_uri, job_id = None, None, None
757 volume = module.params.get("volume_id")
758 controller_id = target[0].split(":")[-1]
759 drive_id = target[0]
760 try:
761 pd_resp = redfish_obj.invoke_request("GET", PD_URI.format(
762 controller_id=controller_id, drive_id=drive_id))
763 except HTTPError:
764 module.fail_json(msg=PD_ERROR_MSG.format(drive_id))
765 else:
766 hot_spare = pd_resp.json_data.get("HotspareType")
767 resp, job_uri, job_id = hot_spare_config_refactored(
768 module, redfish_obj, command, volume, drive_id, hot_spare)
769 return resp, job_uri, job_id
770
771
772 def hot_spare_config_refactored(module, redfish_obj, command, volume, drive_id, hot_spare):
773 resp, job_uri, job_id = None, None, None
774 if module.check_mode and hot_spare == "None" and command == "AssignSpare" or \
775 (module.check_mode and hot_spare != "None" and command == "UnassignSpare"):
776 module.exit_json(msg=CHANGES_FOUND, changed=True)
777 elif (module.check_mode and hot_spare in ["Dedicated", "Global"] and command == "AssignSpare") or \
778 (not module.check_mode and hot_spare in ["Dedicated", "Global"] and command == "AssignSpare") or \
779 (module.check_mode and hot_spare == "None" and command == "UnassignSpare") or \
780 (not module.check_mode and hot_spare == "None" and command == "UnassignSpare"):
781 module.exit_json(msg=NO_CHANGES_FOUND)
782 else:
783 payload = {"TargetFQDD": drive_id}
784 if volume is not None and command == "AssignSpare":
785 payload["VirtualDiskArray"] = volume
786 resp = redfish_obj.invoke_request("POST", RAID_ACTION_URI.format(system_id=SYSTEM_ID,
787 action=command),
788 data=payload)
789 job_uri = resp.headers.get("Location")
790 job_id = job_uri.split("/")[-1]
791 return resp, job_uri, job_id
792
793
794 def change_pd_status(module, redfish_obj):
795 resp, job_uri, job_id = None, None, None
796 command, target = module.params["command"], module.params.get("target")
797 controller_id = target[0].split(":")[-1]
798 drive_id = target[0]
799 state = "Online" if command == "ChangePDStateToOnline" else "Offline"
800 try:
801 pd_resp = redfish_obj.invoke_request("GET", PD_URI.format(controller_id=controller_id, drive_id=drive_id))
802 raid_status = pd_resp.json_data["Oem"]["Dell"]["DellPhysicalDisk"]["RaidStatus"]
803 except HTTPError:
804 module.fail_json(msg=PD_ERROR_MSG.format(drive_id))
805 else:
806 if module.check_mode and state != raid_status:
807 module.exit_json(msg=CHANGES_FOUND, changed=True)
808 elif (module.check_mode and state == raid_status) or (not module.check_mode and state == raid_status):
809 module.exit_json(msg=NO_CHANGES_FOUND)
810 else:
811 resp = redfish_obj.invoke_request("POST", RAID_ACTION_URI.format(system_id=SYSTEM_ID,
812 action="ChangePDState"),
813 data={"TargetFQDD": drive_id, "State": state})
814 job_uri = resp.headers.get("Location")
815 job_id = job_uri.split("/")[-1]
816 return resp, job_uri, job_id
817
818
819 def convert_raid_status(module, redfish_obj):
820 resp, job_uri, job_id = None, None, None
821 command, target = module.params["command"], module.params.get("target")
822 ctrl, pd_ready_state = None, []
823 try:
824 for ctrl in target:
825 controller_id = ctrl.split(":")[-1]
826 pd_resp = redfish_obj.invoke_request("GET", PD_URI.format(controller_id=controller_id, drive_id=ctrl))
827 raid_status = pd_resp.json_data["Oem"]["Dell"]["DellPhysicalDisk"]["RaidStatus"]
828 pd_ready_state.append(raid_status)
829 except HTTPError:
830 module.fail_json(msg=PD_ERROR_MSG.format(ctrl))
831 else:
832 if (command == "ConvertToRAID" and module.check_mode and 0 < pd_ready_state.count("NonRAID")) or \
833 (command == "ConvertToNonRAID" and module.check_mode and 0 < pd_ready_state.count("Ready")):
834 module.exit_json(msg=CHANGES_FOUND, changed=True)
835 elif (command == "ConvertToRAID" and module.check_mode and
836 len(pd_ready_state) == pd_ready_state.count("Ready")) or \
837 (command == "ConvertToRAID" and not module.check_mode and
838 len(pd_ready_state) == pd_ready_state.count("Ready")) or \
839 (command == "ConvertToNonRAID" and module.check_mode and
840 len(pd_ready_state) == pd_ready_state.count("NonRAID")) or \
841 (command == "ConvertToNonRAID" and not module.check_mode and
842 len(pd_ready_state) == pd_ready_state.count("NonRAID")):
843 module.exit_json(msg=NO_CHANGES_FOUND)
844 else:
845 resp = redfish_obj.invoke_request("POST", RAID_ACTION_URI.format(system_id=SYSTEM_ID,
846 action=command),
847 data={"PDArray": target})
848 job_uri = resp.headers.get("Location")
849 job_id = job_uri.split("/")[-1]
850 return resp, job_uri, job_id
851
852
853 def target_identify_pattern(module, redfish_obj):
854 target, volume = module.params.get("target"), module.params.get("volume_id")
855 command = module.params.get("command")
856 payload = {"TargetFQDD": None}
857
858 if target is not None and volume is None:
859 payload = {"TargetFQDD": target[0]}
860 elif volume is not None and target is None:
861 payload = {"TargetFQDD": volume[0]}
862 elif target is not None and volume is not None:
863 payload = {"TargetFQDD": target[0]}
864
865 if module.check_mode:
866 module.exit_json(msg=CHANGES_FOUND, changed=True)
867 resp = redfish_obj.invoke_request("POST", RAID_ACTION_URI.format(system_id=SYSTEM_ID,
868 action=command),
869 data=payload)
870 return resp
871
872
873 def lock_virtual_disk(module, redfish_obj):
874 volume = module.params.get("volume_id")
875 resp, job_uri, job_id = None, None, None
876 controller_id = volume[0].split(":")[-1]
877 check_id_exists(module, redfish_obj, "controller_id", controller_id, CONTROLLER_URI)
878 volume_uri = VOLUME_URI + "/{volume_id}"
879 try:
880 volume_resp = redfish_obj.invoke_request("GET", volume_uri.format(system_id=SYSTEM_ID,
881 controller_id=controller_id,
882 volume_id=volume[0]))
883 links = volume_resp.json_data.get("Links")
884 if links:
885 for disk in volume_resp.json_data.get("Links").get("Drives"):
886 drive_link = disk[ODATA_ID]
887 drive_resp = redfish_obj.invoke_request("GET", drive_link)
888 encryption_ability = drive_resp.json_data.get("EncryptionAbility")
889 if encryption_ability != "SelfEncryptingDrive":
890 module.fail_json(msg=PHYSICAL_DISK_ERR)
891 lock_status = volume_resp.json_data.get("Oem").get("Dell").get("DellVolume").get("LockStatus")
892 except HTTPError:
893 module.fail_json(msg=PD_ERROR_MSG.format(controller_id))
894 else:
895 if lock_status == "Unlocked" and module.check_mode:
896 module.exit_json(msg=CHANGES_FOUND, changed=True)
897 elif lock_status == "Locked":
898 module.exit_json(msg=NO_CHANGES_FOUND)
899 else:
900 resp = redfish_obj.invoke_request("POST", RAID_ACTION_URI.format(system_id=SYSTEM_ID,
901 action="SecureVirtualDisk"),
902 data={"TargetFQDD": volume[0]})
903 job_uri = resp.headers.get("Location")
904 job_id = job_uri.split("/")[-1]
905 return resp, job_uri, job_id
906
907
908 def online_capacity_expansion(module, redfish_obj):
909 payload = None
910 volume_id = module.params.get("volume_id")
911 target = module.params.get("target")
912 size = module.params.get("size")
913 if not isinstance(volume_id, list):
914 volume_id = [volume_id]
915 if len(volume_id) != 1:
916 module.exit_json(msg=TARGET_ERR_MSG.format("virtual drive"), failed=True)
917
918 controller_id = volume_id[0].split(":")[-1]
919 volume_uri = VOLUME_URI + "/{volume_id}"
920 try:
921 volume_resp = redfish_obj.invoke_request("GET", volume_uri.format(system_id=SYSTEM_ID,
922 controller_id=controller_id,
923 volume_id=volume_id[0]))
924 except HTTPError:
925 module.exit_json(msg=VD_ERROR_MSG.format(volume_id[0]), failed=True)
926
927 try:
928 raid_type = volume_resp.json_data.get("RAIDType")
929 if raid_type in ['RAID50', 'RAID60']:
930 module.exit_json(msg=OCE_RAID_TYPE_ERR.format(raid_type), failed=True)
931
932 if target is not None:
933 drives_to_add = online_capacity_expansion_refactored(module, target, volume_resp, raid_type)
934 payload = {"TargetFQDD": volume_id[0], "PDArray": drives_to_add}
935
936 elif size:
937 vd_size = volume_resp.json_data.get("CapacityBytes")
938 vd_size_mb = vd_size // (1024 * 1024)
939 if (size - vd_size_mb) < 100:
940 module.exit_json(msg=OCE_SIZE_100MB.format(vd_size_mb), failed=True)
941 payload = {"TargetFQDD": volume_id[0], "Size": size}
942
943 resp = redfish_obj.invoke_request("POST", RAID_ACTION_URI.format(system_id=SYSTEM_ID,
944 action="OnlineCapacityExpansion"),
945 data=payload)
946 job_uri = resp.headers.get("Location")
947 job_id = job_uri.split("/")[-1]
948 return resp, job_uri, job_id
949 except HTTPError as err:
950 err = json.load(err).get("error").get("@Message.ExtendedInfo", [{}])[0].get("Message")
951 module.exit_json(msg=err, failed=True)
952
953
954 def online_capacity_expansion_refactored(module, target, volume_resp, raid_type):
955 if not target:
956 module.exit_json(msg=OCE_TARGET_EMPTY, failed=True)
957
958 if raid_type == 'RAID1':
959 module.fail_json(msg=OCE_TARGET_RAID1_ERR)
960
961 current_pd = []
962 links = volume_resp.json_data.get("Links")
963 if links:
964 for disk in volume_resp.json_data.get("Links").get("Drives"):
965 drive = disk[ODATA_ID].split('/')[-1]
966 current_pd.append(drive)
967 drives_to_add = [each_drive for each_drive in target if each_drive not in current_pd]
968 if module.check_mode and drives_to_add and len(drives_to_add) % OCE_MIN_PD_RAID_MAPPING[raid_type] == 0:
969 module.exit_json(msg=CHANGES_FOUND, changed=True)
970 elif len(drives_to_add) == 0 or len(drives_to_add) % OCE_MIN_PD_RAID_MAPPING[raid_type] != 0:
971 module.exit_json(msg=NO_CHANGES_FOUND)
972 return drives_to_add
973
974
975 def match_id_in_list(id, member_list):
976 for each_dict in member_list:
977 url = each_dict[ODATA_ID]
978 _id = url.split("/")[-1]
979 if id == _id:
980 return url
981
982
983 def validate_secure_erase(module, redfish_obj):
984 drive_uri = None
985 drive = module.params.get("target")
986 drive_id = drive[0]
987 controller_id = module.params.get("controller_id")
988 uri, err_msg = validate_and_get_first_resource_id_uri(module, redfish_obj,
989 SYSTEMS_URI)
990 if err_msg:
991 module.exit_json(msg=err_msg, failed=True)
992 storage_uri = get_dynamic_uri(redfish_obj, uri, "Storage")['@odata.id']
993 storage_member_list = get_dynamic_uri(redfish_obj, storage_uri, "Members")
994 controller_uri = match_id_in_list(controller_id, storage_member_list)
995 if controller_uri is None:
996 module.exit_json(msg=CNTRL_ERROR_MSG.format(controller_id), skipped=True)
997 drives_list = get_dynamic_uri(redfish_obj, controller_uri, 'Drives')
998 drive_uri = match_id_in_list(drive_id, drives_list)
999 if drive_uri is None:
1000 module.exit_json(msg=PD_ERROR_MSG.format(drive_id), skipped=True)
1001 drive_detail = get_dynamic_uri(redfish_obj, drive_uri)
1002 firm_ver = get_idrac_firmware_version(redfish_obj)
1003 if LooseVersion(firm_ver) >= '1.0':
1004 dell_oem = drive_detail.get("Oem", {}).get("Dell", {})
1005 try:
1006 dell_disk = dell_oem["DellPhysicalDisk"]
1007 except KeyError:
1008 dell_disk = dell_oem.get("DellPCIeSSD", {})
1009 drive_ready = dell_disk.get("RaidStatus", {})
1010 if drive_ready != "Ready":
1011 module.exit_json(msg=DRIVE_NOT_READY.format(drive_id),
1012 skipped=True)
1013 capable = dell_disk.get("SystemEraseCapability", {})
1014 if capable != "CryptographicErasePD":
1015 module.exit_json(msg=DRIVE_NOT_SECURE_ERASE.format(drive_id),
1016 skipped=True)
1017 return drive_uri
1018
1019
1020 def secure_erase(module, redfish_obj):
1021 drive_uri = validate_secure_erase(module, redfish_obj)
1022 job_type_list = ["RAIDConfiguration", "RealTimeNoRebootConfiguration"]
1023 scheduled_job = get_scheduled_job_resp(redfish_obj, job_type_list)
1024 if scheduled_job:
1025 job_id = scheduled_job.get("Id")
1026 job_uri = JOB_URI_OEM.format(job_id=job_id)
1027 module.exit_json(msg=JOB_EXISTS, status=scheduled_job, changed=False,
1028 task={"id": job_id, "uri": job_uri})
1029 action_uri = get_dynamic_uri(redfish_obj, drive_uri, "Actions")
1030 secure_erase_uri = action_uri.get("#Drive.SecureErase").get("target")
1031 if module.check_mode:
1032 module.exit_json(msg=CHANGES_FOUND, changed=True)
1033 resp = redfish_obj.invoke_request("POST", secure_erase_uri, data="{}",
1034 dump=False)
1035 job_uri = resp.headers.get("Location")
1036 job_id = job_uri.split("/")[-1]
1037 return resp, job_uri, job_id
1038
1039
1040 def validate_inputs(module):
1041 module_params = module.params
1042 command = module_params.get("command")
1043 mode = module_params.get("mode")
1044 key = module_params.get("key")
1045 key_id = module_params.get("key_id")
1046 old_key = module_params.get("old_key")
1047 target = module_params.get("target")
1048 volume = module_params.get("volume_id")
1049 command_need_target_validation = ["AssignSpare", "UnassignSpare", "BlinkTarget", "UnBlinkTarget",
1050 "LockVirtualDisk", "ChangePDStateToOnline", "ChangePDStateToOffline",
1051 "SecureErase"]
1052 command_need_volume_validation = ["AssignSpare", "UnassignSpare", "BlinkTarget", "UnBlinkTarget",
1053 "LockVirtualDisk"]
1054
1055 if command == "ReKey" and mode == "LKM":
1056 if not all([key, key_id, old_key]):
1057 module.fail_json(msg="All of the following: key, key_id and old_key are "
1058 "required for '{0}' operation.".format(command))
1059
1060 elif command == "EnableControllerEncryption" and mode == "LKM":
1061 if not all([key, key_id]):
1062 module.fail_json(msg="All of the following: key, key_id are "
1063 "required for '{0}' operation.".format(command))
1064
1065 elif command in command_need_target_validation and target is not None and len(target) != 1:
1066 module.fail_json(msg=TARGET_ERR_MSG.format("physical disk"))
1067 elif command in command_need_volume_validation and volume is not None and len(volume) != 1:
1068 module.fail_json(msg=TARGET_ERR_MSG.format("virtual drive"))
1069
1070
1071 def get_current_time(redfish_obj):
1072 try:
1073 resp = redfish_obj.invoke_request("GET", MANAGER_URI)
1074 curr_time = resp.json_data.get("DateTime")
1075 date_offset = resp.json_data.get("DateTimeLocalOffset")
1076 except Exception:
1077 return None, None
1078 return curr_time, date_offset
1079
1080
1081 def validate_time(module, redfish_obj, mtime):
1082 curr_time, date_offset = get_current_time(redfish_obj)
1083 if not mtime.endswith(date_offset):
1084 module.exit_json(failed=True, status_msg=MAINTENANCE_OFFSET.format(date_offset))
1085 if mtime < curr_time:
1086 module.exit_json(failed=True, status_msg=MAINTENANCE_TIME)
1087
1088
1089 def get_attributes(module, redfish_obj):
1090 resp_data = {}
1091 controller_id = module.params["controller_id"]
1092 try:
1093 resp = redfish_obj.invoke_request("GET", CONTROLLERS_URI.format(system_id=SYSTEM_ID,
1094 controller_id=controller_id))
1095 resp_data = resp.json_data
1096 except HTTPError:
1097 resp_data = {}
1098 return resp_data
1099
1100
1101 def check_attr_exists(module, curr_attr, inp_attr):
1102 invalid_attr = []
1103 pending_attr = {}
1104 diff = 0
1105 for each in inp_attr:
1106 if each not in curr_attr.keys():
1107 invalid_attr.append(each)
1108 elif curr_attr[each] != inp_attr[each]:
1109 diff = 1
1110 pending_attr[each] = inp_attr[each]
1111 if invalid_attr:
1112 module.exit_json(msg=INVALID_ATTRIBUTES.format(invalid_attr), failed=True)
1113 if diff and module.check_mode:
1114 module.exit_json(msg=CHANGES_FOUND, changed=True)
1115 elif not diff:
1116 module.exit_json(msg=NO_CHANGES_FOUND)
1117 return pending_attr
1118
1119
1120 def get_redfish_apply_time(module, redfish_obj, apply_time, time_settings):
1121 time_set = {}
1122 if time_settings:
1123 if 'Maintenance' in apply_time:
1124 if apply_time not in time_settings:
1125 module.exit_json(failed=True, status_msg=UNSUPPORTED_APPLY_TIME.format(apply_time))
1126 else:
1127 time_set['ApplyTime'] = apply_time
1128 m_win = module.params.get('maintenance_window')
1129 validate_time(module, redfish_obj, m_win.get('start_time'))
1130 time_set['MaintenanceWindowStartTime'] = m_win.get('start_time')
1131 time_set['MaintenanceWindowDurationInSeconds'] = m_win.get('duration')
1132 else:
1133 time_set['ApplyTime'] = apply_time
1134 return time_set
1135
1136
1137 def apply_attributes(module, redfish_obj, pending, time_settings):
1138 payload = {"Oem": {"Dell": {"DellStorageController": pending}}}
1139 apply_time = module.params.get('apply_time')
1140 time_set = get_redfish_apply_time(module, redfish_obj, apply_time, time_settings)
1141 if time_set:
1142 payload["@Redfish.SettingsApplyTime"] = time_set
1143 try:
1144 resp = redfish_obj.invoke_request("PATCH", SETTINGS_URI.format(system_id=SYSTEM_ID,
1145 controller_id=module.params["controller_id"]),
1146 data=payload)
1147 if resp.status_code == 202 and "error" in resp.json_data:
1148 msg_err_id = resp.json_data.get("error").get("@Message.ExtendedInfo", [{}])[0].get("MessageId")
1149 if "Created" not in msg_err_id:
1150 module.exit_json(msg=ERR_MSG, error_info=resp.json_data, failed=True)
1151 except HTTPError as err:
1152 err = json.load(err).get("error")
1153 module.exit_json(msg=ERR_MSG, error_info=err, failed=True)
1154 job_id = resp.headers["Location"].split("/")[-1]
1155 return job_id, time_set
1156
1157
1158 def set_attributes(module, redfish_obj):
1159 resp_data = get_attributes(module, redfish_obj)
1160 curr_attr = resp_data.get("Oem").get("Dell").get("DellStorageController")
1161 inp_attr = module.params.get("attributes")
1162 if inp_attr.get("ControllerMode") and len(inp_attr.keys()) > 1:
1163 module.exit_json(msg=HBA_MODE, failed=True)
1164 pending = check_attr_exists(module, curr_attr, inp_attr)
1165 time_settings = resp_data.get("@Redfish.Settings", {}).get("SupportedApplyTimes", [])
1166 job_id, time_set = apply_attributes(module, redfish_obj, pending, time_settings)
1167 return job_id, time_set
1168
1169
1170 def job_condition_check(module, redfish_obj, job_id, job_uri,
1171 job_completion_msg, job_submission_msg,
1172 condition=True):
1173 job_wait = module.params.get("job_wait")
1174 if condition and job_wait:
1175 resp, msg = wait_for_job_completion(redfish_obj, job_uri, job_wait=job_wait,
1176 wait_timeout=module.params["job_wait_timeout"])
1177 if not resp:
1178 job_completion_msg = msg
1179 resp = redfish_obj.invoke_request("GET", job_uri)
1180 job_data = strip_substr_dict(resp.json_data)
1181 if job_data["JobState"] == "Failed":
1182 changed, failed = False, True
1183 else:
1184 changed, failed = True, False
1185 module.exit_json(msg=job_completion_msg, changed=changed, failed=failed,
1186 task={"id": job_id, "uri": job_uri}, status=job_data)
1187 else:
1188 resp, msg = wait_for_job_completion(redfish_obj, job_uri, job_wait=job_wait,
1189 wait_timeout=module.params["job_wait_timeout"])
1190 if resp == {}:
1191 module.exit_json(msg=msg, task={"id": job_id, "uri": job_uri})
1192 job_data = strip_substr_dict(resp.json_data)
1193 module.exit_json(msg=job_submission_msg, task={"id": job_id, "uri": job_uri},
1194 status=job_data)
1195
1196
1197 def validate_operations(module, server_generation_op):
1198 generation = server_generation_op[0]
1199 command = module.params.get("command")
1200 idrac9_invalid_commands = ["EnableSecurity", "DisableSecurity"]
1201 idrac10_invalid_commands = ["SetControllerKey", "RemoveControllerKey",
1202 "ReKey", "EnableControllerEncryption"]
1203 if (generation < 17 and command in idrac9_invalid_commands) or \
1204 (generation >= 17 and command in idrac10_invalid_commands):
1205 module.exit_json(msg=INVALID_COMMAND.format(command, server_generation_op[2]), changed=False)
1206
1207
1208 def validate_params(module):
1209 start_time = None
1210 key_id = module.params.get("key_id")
1211 key = module.params.get("key")
1212 maintenance_window = module.params.get("maintenance_window")
1213 if maintenance_window:
1214 start_time = maintenance_window.get('start_time')
1215 if key:
1216 pattern_key = r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>]).{1,32}$'
1217 if not re.match(pattern_key, key):
1218 module.exit_json(failed=True, msg=INVALID_KEY)
1219 if key_id:
1220 pattern_key_id = r'^[^\s]{1,32}$'
1221 if not re.match(pattern_key_id, key_id):
1222 module.exit_json(failed=True, msg=INVALID_KEY_ID)
1223 if start_time:
1224 pattern_start_time = r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})$'
1225 if not re.match(pattern_start_time, start_time):
1226 module.exit_json(failed=True, msg=INVALID_START_TIME)
1227
1228
1229 def get_server_generation(redfish_obj: Redfish):
1230 """
1231 Function wrapping redfish_obj.get_server_generation. Helps with mocked testing.
1232
1233 Args:
1234 redfish_obj (Redfish): Redfish object.
1235
1236 Returns:
1237 Tuple[int, str, str]: A tuple containing the server generation, firmware version, and hardware model.
1238 """
1239 return redfish_obj.get_server_generation
1240
1241
1242 def main():
1243 specs = {
1244 "attributes": {"type": 'dict'},
1245 "command": {"required": False,
1246 "choices": ["ResetConfig", "AssignSpare", "SetControllerKey", "RemoveControllerKey",
1247 "ReKey", "UnassignSpare", "EnableControllerEncryption", "BlinkTarget",
1248 "UnBlinkTarget", "ConvertToRAID", "ConvertToNonRAID", "ChangePDStateToOnline",
1249 "ChangePDStateToOffline", "LockVirtualDisk", "OnlineCapacityExpansion", "SecureErase",
1250 "EnableSecurity", "DisableSecurity"]},
1251 "controller_id": {"required": False, "type": "str"},
1252 "volume_id": {"required": False, "type": "list", "elements": "str"},
1253 "target": {"required": False, "type": "list", "elements": "str", "aliases": ["drive_id"]},
1254 "key": {"required": False, "type": "str", "no_log": True},
1255 "key_id": {"required": False, "type": "str"},
1256 "old_key": {"required": False, "type": "str", "no_log": True},
1257 "mode": {"required": False, "choices": ["LKM", "SEKM"], "default": "LKM"},
1258 "apply_time": {"type": 'str', "default": 'Immediate',
1259 "choices": ['Immediate', 'OnReset', 'AtMaintenanceWindowStart', 'InMaintenanceWindowOnReset']},
1260 "maintenance_window": {"type": 'dict',
1261 "options": {"start_time": {"type": 'str', "required": True},
1262 "duration": {"type": 'int', "required": False, "default": 900}}},
1263 "job_wait": {"required": False, "type": "bool", "default": False},
1264 "job_wait_timeout": {"required": False, "type": "int", "default": 120},
1265 "size": {"required": False, "type": "int"}
1266 }
1267 module = RedfishAnsibleModule(
1268 argument_spec=specs,
1269 mutually_exclusive=[('attributes', 'command'), ("target", "size")],
1270 required_one_of=[('attributes', 'command')],
1271 required_if=[
1272 ["command", "SetControllerKey", ["controller_id", "key", "key_id"]],
1273 ["command", "ReKey", ["controller_id", "mode"]], ["command", "ResetConfig", ["controller_id"]],
1274 ["command", "RemoveControllerKey", ["controller_id"]], ["command", "AssignSpare", ["target"]],
1275 ["command", "UnassignSpare", ["target"]], ["command", "EnableControllerEncryption", ["controller_id"]],
1276 ["command", "BlinkTarget", ["target", "volume_id"], True],
1277 ["command", "UnBlinkTarget", ["target", "volume_id"], True], ["command", "ConvertToRAID", ["target"]],
1278 ["command", "ConvertToNonRAID", ["target"]], ["command", "ChangePDStateToOnline", ["target"]],
1279 ["command", "ChangePDStateToOffline", ["target"]],
1280 ["command", "LockVirtualDisk", ["volume_id"]], ["command", "OnlineCapacityExpansion", ["volume_id"]],
1281 ["command", "OnlineCapacityExpansion", ["target", "size"], True],
1282 ["command", "LockVirtualDisk", ["volume_id"]],
1283 ["command", "SecureErase", ["controller_id", "target"]],
1284 ["apply_time", "AtMaintenanceWindowStart", ("maintenance_window",)],
1285 ["apply_time", "InMaintenanceWindowOnReset", ("maintenance_window",)]
1286 ],
1287 supports_check_mode=True)
1288 try:
1289 command = module.params["command"]
1290 with Redfish(module.params, req_session=True) as redfish_obj:
1291 server_generation_op = get_server_generation(redfish_obj)
1292 validate_operations(module, server_generation_op)
1293 validate_params(module)
1294 if not bool(module.params["attributes"]):
1295 validate_inputs(module)
1296 command_function_mapping = {
1297 "ResetConfig": ctrl_reset_config,
1298 "SetControllerKey": ctrl_key,
1299 "ReKey": ctrl_key,
1300 "RemoveControllerKey": ctrl_key,
1301 "EnableControllerEncryption": ctrl_key,
1302 "AssignSpare": hot_spare_config,
1303 "UnassignSpare": hot_spare_config,
1304 "ConvertToRAID": convert_raid_status,
1305 "ConvertToNonRAID": convert_raid_status,
1306 "ChangePDStateToOnline": change_pd_status,
1307 "ChangePDStateToOffline": change_pd_status,
1308 "LockVirtualDisk": lock_virtual_disk,
1309 "OnlineCapacityExpansion": online_capacity_expansion,
1310 "SecureErase": secure_erase,
1311 "EnableSecurity": enable_security,
1312 "DisableSecurity": disable_security
1313 }
1314
1315 if command in ["BlinkTarget", "UnBlinkTarget"]:
1316 resp = target_identify_pattern(module, redfish_obj)
1317 if resp.success and resp.status_code == 200:
1318 module.exit_json(msg=JOB_COMPLETION.format(command), changed=True)
1319 elif command:
1320 func = command_function_mapping[command]
1321 resp, job_uri, job_id = func(module, redfish_obj)
1322
1323 if module.params["attributes"]:
1324 controller_id = module.params["controller_id"]
1325 if controller_id is None:
1326 module.exit_json(msg=CONTROLLER_ID_REQUIRED, failed=True)
1327 check_id_exists(module, redfish_obj, "controller_id", controller_id, CONTROLLER_URI)
1328 job_id, time_set = set_attributes(module, redfish_obj)
1329 job_uri = JOB_URI_OEM.format(job_id=job_id)
1330 job_condition_check(module, redfish_obj, job_id,
1331 job_uri, JOB_COMPLETION_ATTRIBUTES,
1332 JOB_SUBMISSION_ATTRIBUTES,
1333 time_set["ApplyTime"] == "Immediate")
1334 oem_job_url = JOB_URI_OEM.format(job_id=job_id)
1335 job_condition_check(module, redfish_obj, job_id, oem_job_url,
1336 JOB_COMPLETION.format(command),
1337 JOB_SUBMISSION.format(command))
1338 except HTTPError as err:
1339 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
1340 except URLError as err:
1341 module.exit_json(msg=str(err), unreachable=True)
1342 except (RuntimeError, SSLValidationError, ConnectionError, KeyError,
1343 ImportError, ValueError, TypeError, AttributeError) as e:
1344 module.exit_json(msg=str(e), failed=True)
1345
1346
1347 if __name__ == '__main__':
1348 main()