Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/idrac_server_config_profile.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) 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_server_config_profile
19 short_description: Export or Import iDRAC Server Configuration Profile (SCP)
20 version_added: "2.1.0"
21 description:
22 - Export the Server Configuration Profile (SCP) from the iDRAC or import from a
23 network share (CIFS, NFS, HTTP, HTTPS) or a local path.
24 extends_documentation_fragment:
25 - dellemc.openmanage.idrac_x_auth_options
26 options:
27 command:
28 description:
29 - If C(import), the module performs SCP import operation.
30 - If C(export), the module performs SCP export operation.
31 - If C(preview), the module performs SCP preview operation.
32 - C(import_custom_defaults) allows you to import custom default iDRAC settings.
33 - C(export_custom_defaults) allows you to export custom default iDRAC settings.
34 - C(import_custom_defaults) and C(export_custom_defaults) is supported only on iDRAC9 with firmware 7.00.00.00 and above.
35 type: str
36 choices: ['import', 'export', 'preview', 'import_custom_defaults', 'export_custom_defaults']
37 default: 'export'
38 job_wait:
39 description: Whether to wait for job completion or not.
40 type: bool
41 required: true
42 job_wait_timeout:
43 description:
44 - The maximum wait time of I(job_wait) in seconds.
45 - The job is tracked only for this duration.
46 - This option is applicable when I(job_wait) is C(true).
47 type: int
48 default: 900
49 share_name:
50 description:
51 - Network share or local path.
52 - CIFS, NFS, HTTP, and HTTPS network share types are supported.
53 - I(share_name) is mutually exclusive with I(import_buffer).
54 - Only "local" is supported when the I(command) is C(import_custom_defaults) or C(export_custom_defaults).
55 type: str
56 share_user:
57 description: Network share user in the format 'user@domain' or 'domain\\user' if user is
58 part of a domain else 'user'. This option is mandatory for CIFS Network Share.
59 type: str
60 share_password:
61 description: Network share user password. This option is mandatory for CIFS Network Share.
62 type: str
63 aliases: ['share_pwd']
64 scp_file:
65 description:
66 - Name of the server configuration profile (SCP) file.
67 - Only XML file format is supported when I(command) is C(import) or C(import_custom_defaults) or C(export_custom_defaults).
68 - The default format <idrac_ip>_YYmmdd_HHMMSS_scp is used if this option is not specified for C(export) or C(export_custom_defaults).
69 - I(export_format) is used if the valid extension file is not provided for C(export).
70 type: str
71 scp_components:
72 description:
73 - If C(ALL), this option exports or imports all components configurations from the SCP file.
74 - If C(IDRAC), this option exports or imports iDRAC configuration from the SCP file.
75 - If C(BIOS), this option exports or imports BIOS configuration from the SCP file.
76 - If C(NIC), this option exports or imports NIC configuration from the SCP file.
77 - If C(RAID), this option exports or imports RAID configuration from the SCP file.
78 - If C(FC), this option exports or imports FiberChannel configurations from the SCP file.
79 - If C(InfiniBand), this option exports or imports InfiniBand configuration from the SCP file.
80 - If C(SupportAssist), this option exports or imports SupportAssist configuration from the SCP file.
81 - If C(EventFilters), this option exports or imports EventFilters configuration from the SCP file.
82 - If C(System), this option exports or imports System configuration from the SCP file.
83 - If C(LifecycleController), this option exports or imports SupportAssist configuration from the SCP file.
84 - If C(AHCI), this option exports or imports EventFilters configuration from the SCP file.
85 - If C(PCIeSSD), this option exports or imports PCIeSSD configuration from the SCP file.
86 - When I(command) is C(export) or C(import) I(target) with multiple components is supported only
87 on iDRAC9 with firmware 6.10.00.00 and above.
88 type: list
89 choices: ['ALL', 'IDRAC', 'BIOS', 'NIC', 'RAID', 'FC', 'InfiniBand', 'SupportAssist',
90 'EventFilters', 'System', 'LifecycleController', 'AHCI', 'PCIeSSD']
91 default: 'ALL'
92 elements: str
93 aliases: ['target']
94 shutdown_type:
95 description:
96 - This option is applicable for C(import) command.
97 - If C(Graceful), the job gracefully shuts down the operating system and turns off the server.
98 - If C(Forced), it forcefully shuts down the server.
99 - If C(NoReboot), the job that applies the SCP will pause until you manually reboot the server.
100 type: str
101 choices: ['Graceful', 'Forced', 'NoReboot']
102 default: 'Graceful'
103 end_host_power_state:
104 description:
105 - This option is applicable for C(import) command.
106 - If C(On), End host power state is on.
107 - If C(Off), End host power state is off.
108 type: str
109 choices: ['On' ,'Off']
110 default: 'On'
111 export_format:
112 description:
113 - Specify the output file format. This option is applicable for C(export) or C(export_custom_defaults) command.
114 - The default export file format is always XML when the I(command) is C(export_custom_defaults).
115 type: str
116 choices: ['JSON', 'XML']
117 default: 'XML'
118 export_use:
119 description:
120 - Specify the type of Server Configuration Profile (SCP) to be exported.
121 - This option is applicable when I(command) is C(export).
122 - C(Default) Creates a non-destructive snapshot of the configuration.
123 - C(Replace) Replaces a server with another or restores the servers settings to a known baseline.
124 - C(Clone) Clones settings from one server to another server with the identical hardware setup.
125 All settings except I/O identity are updated (e.g. will reset RAID). The settings in this export
126 will be destructive when uploaded to another system.
127 type: str
128 choices: ['Default', 'Clone', 'Replace']
129 default: 'Default'
130 version_added: 7.3.0
131 ignore_certificate_warning:
132 description:
133 - If C(ignore), it ignores the certificate warnings.
134 - If C(showerror), it shows the certificate warnings.
135 - I(ignore_certificate_warning) is considered only when I(share_name) is of type HTTPS and is
136 supported only on iDRAC9.
137 type: str
138 choices: [ignore, showerror]
139 default: ignore
140 version_added: 7.3.0
141 include_in_export:
142 description:
143 - This option is applicable when I(command) is C(export).
144 - If C(default), it exports the default Server Configuration Profile.
145 - If C(readonly), it exports the SCP with readonly attributes.
146 - If C(passwordhashvalues), it exports the SCP with password hash values.
147 - If C(customtelemetry), exports the SCP with custom telemetry attributes supported only in the iDRAC9.
148 type: str
149 choices: [default, readonly, passwordhashvalues, customtelemetry]
150 default: default
151 version_added: 7.3.0
152 import_buffer:
153 description:
154 - Used to import the buffer input of xml or json into the iDRAC.
155 - When the I(command) is C(import_custom_defaults), only XML file format is supported.
156 - This option is applicable when I(command) is C(import) or C(preview) or C(import_custom_defaults).
157 - I(import_buffer) is mutually exclusive with I(share_name).
158 type: str
159 version_added: 7.3.0
160 proxy_support:
161 description:
162 - Proxy to be enabled or disabled.
163 - I(proxy_support) is considered only when I(share_name) is of type HTTP or HTTPS and is supported only on iDRAC9.
164 type: bool
165 default: false
166 version_added: 7.3.0
167 proxy_type:
168 description:
169 - C(http) to select HTTP type proxy.
170 - C(socks4) to select SOCKS4 type proxy.
171 - I(proxy_type) is considered only when I(share_name) is of type HTTP or HTTPS and is supported only on iDRAC9.
172 type: str
173 choices: [http, socks4]
174 default: http
175 version_added: 7.3.0
176 proxy_server:
177 description:
178 - I(proxy_server) is required when I(share_name) is of type HTTPS or HTTP and I(proxy_support) is C(true).
179 - I(proxy_server) is considered only when I(share_name) is of type HTTP or HTTPS and is supported only on iDRAC9.
180 type: str
181 version_added: 7.3.0
182 proxy_port:
183 description:
184 - Proxy port to authenticate.
185 - I(proxy_port) is required when I(share_name) is of type HTTPS or HTTP and I(proxy_support) is C(true).
186 - I(proxy_port) is considered only when I(share_name) is of type HTTP or HTTPS and is supported only on iDRAC9.
187 type: str
188 default: "80"
189 version_added: 7.3.0
190 proxy_username:
191 description:
192 - Proxy username to authenticate.
193 - I(proxy_username) is considered only when I(share_name) is of type HTTP or HTTPS
194 and is supported only on iDRAC9.
195 type: str
196 version_added: 7.3.0
197 proxy_password:
198 description:
199 - Proxy password to authenticate.
200 - I(proxy_password) is considered only when I(share_name) is of type HTTP or HTTPS
201 and is supported only on iDRAC9.
202 type: str
203 version_added: 7.3.0
204 requirements:
205 - "python >= 3.9.14"
206 author:
207 - "Jagadeesh N V(@jagadeeshnv)"
208 - "Felix Stephen (@felixs88)"
209 - "Jennifer John (@Jennifer-John)"
210 - "Shivam Sharma (@ShivamSh3)"
211 - "Lovepreet Singh (@singh-lovepreet1)"
212 notes:
213 - This module requires 'Administrator' privilege for I(idrac_user).
214 - Run this module from a system that has direct access to Dell iDRAC.
215 - This module supports C(check_mode).
216 - To import Server Configuration Profile (SCP) on the iDRAC8-based servers,
217 the servers must have iDRAC Enterprise license or later.
218 - For C(import) operation, C(check_mode) is supported only when I(target) is C(ALL).
219 - This module supports IPv4 and IPv6 addresses.
220 '''
221
222 EXAMPLES = r'''
223 ---
224 - name: Export SCP with IDRAC components in JSON format to a local path
225 dellemc.openmanage.idrac_server_config_profile:
226 idrac_ip: "192.168.0.1"
227 idrac_user: "user_name"
228 idrac_password: "user_password"
229 ca_path: "/path/to/ca_cert.pem"
230 share_name: "/scp_folder"
231 scp_components:
232 - IDRAC
233 scp_file: example_file
234 export_format: JSON
235 export_use: Clone
236 job_wait: true
237
238 - name: Import SCP with IDRAC components in JSON format from a local path
239 dellemc.openmanage.idrac_server_config_profile:
240 idrac_ip: "192.168.0.1"
241 idrac_user: "user_name"
242 idrac_password: "user_password"
243 ca_path: "/path/to/ca_cert.pem"
244 share_name: "/scp_folder"
245 command: import
246 scp_components:
247 - IDRAC
248 scp_file: example_file.json
249 shutdown_type: Graceful
250 end_host_power_state: "On"
251 job_wait: false
252
253 - name: Export SCP with BIOS components in XML format to a NFS share path with auto-generated file name
254 dellemc.openmanage.idrac_server_config_profile:
255 idrac_ip: "192.168.0.1"
256 idrac_user: "user_name"
257 idrac_password: "user_password"
258 ca_path: "/path/to/ca_cert.pem"
259 share_name: "192.168.0.2:/share"
260 scp_components:
261 - BIOS
262 export_format: XML
263 export_use: Default
264 job_wait: true
265
266 - name: Import SCP with BIOS components in XML format from a NFS share path
267 dellemc.openmanage.idrac_server_config_profile:
268 idrac_ip: "192.168.0.1"
269 idrac_user: "user_name"
270 idrac_password: "user_password"
271 ca_path: "/path/to/ca_cert.pem"
272 share_name: "192.168.0.2:/share"
273 command: import
274 scp_components:
275 - BIOS
276 scp_file: 192.168.0.1_20210618_162856.xml
277 shutdown_type: NoReboot
278 end_host_power_state: "Off"
279 job_wait: false
280
281 - name: Export SCP with RAID components in XML format to a CIFS share path with share user domain name
282 dellemc.openmanage.idrac_server_config_profile:
283 idrac_ip: "192.168.0.1"
284 idrac_user: "user_name"
285 idrac_password: "user_password"
286 ca_path: "/path/to/ca_cert.pem"
287 share_name: "\\\\192.168.0.2\\share"
288 share_user: share_username@domain
289 share_password: share_password
290 scp_file: example_file.xml
291 scp_components:
292 - RAID
293 export_format: XML
294 export_use: Default
295 job_wait: true
296
297 - name: Import SCP with RAID components in XML format from a CIFS share path
298 dellemc.openmanage.idrac_server_config_profile:
299 idrac_ip: "192.168.0.1"
300 idrac_user: "user_name"
301 idrac_password: "user_password"
302 ca_path: "/path/to/ca_cert.pem"
303 share_name: "\\\\192.168.0.2\\share"
304 share_user: share_username
305 share_password: share_password
306 command: import
307 scp_components:
308 - RAID
309 scp_file: example_file.xml
310 shutdown_type: Forced
311 end_host_power_state: "On"
312 job_wait: true
313
314 - name: Export SCP with ALL components in JSON format to a HTTP share path
315 dellemc.openmanage.idrac_server_config_profile:
316 idrac_ip: "192.168.0.1"
317 idrac_user: "user_name"
318 idrac_password: "user_password"
319 ca_path: "/path/to/ca_cert.pem"
320 share_name: "http://192.168.0.3/share"
321 share_user: share_username
322 share_password: share_password
323 scp_file: example_file.json
324 scp_components:
325 - ALL
326 export_format: JSON
327 job_wait: false
328
329 - name: Import SCP with ALL components in JSON format from a HTTP share path
330 dellemc.openmanage.idrac_server_config_profile:
331 idrac_ip: "192.168.0.1"
332 idrac_user: "user_name"
333 idrac_password: "user_password"
334 ca_path: "/path/to/ca_cert.pem"
335 command: import
336 share_name: "http://192.168.0.3/share"
337 share_user: share_username
338 share_password: share_password
339 scp_file: example_file.json
340 shutdown_type: Graceful
341 end_host_power_state: "On"
342 job_wait: true
343
344 - name: Export SCP with ALL components in XML format to a HTTPS share path without SCP file name
345 dellemc.openmanage.idrac_server_config_profile:
346 idrac_ip: "192.168.0.1"
347 idrac_user: "user_name"
348 idrac_password: "user_password"
349 ca_path: "/path/to/ca_cert.pem"
350 share_name: "https://192.168.0.4/share"
351 share_user: share_username
352 share_password: share_password
353 scp_components:
354 - ALL
355 export_format: XML
356 export_use: Replace
357 job_wait: true
358
359 - name: Import SCP with ALL components in XML format from a HTTPS share path
360 dellemc.openmanage.idrac_server_config_profile:
361 idrac_ip: "192.168.0.1"
362 idrac_user: "user_name"
363 idrac_password: "user_password"
364 ca_path: "/path/to/ca_cert.pem"
365 command: import
366 share_name: "https://192.168.0.4/share"
367 share_user: share_username
368 share_password: share_password
369 scp_file: 192.168.0.1_20160618_164647.xml
370 shutdown_type: Graceful
371 end_host_power_state: "On"
372 job_wait: false
373
374 - name: Preview SCP with IDRAC components in XML format from a CIFS share path
375 dellemc.openmanage.idrac_server_config_profile:
376 idrac_ip: "{{ idrac_ip }}"
377 idrac_user: "{{ idrac_user }}"
378 idrac_password: "{{ idrac_password }}"
379 ca_path: "/path/to/ca_cert.pem"
380 share_name: "\\\\192.168.0.2\\share"
381 share_user: share_username
382 share_password: share_password
383 command: preview
384 scp_components:
385 - ALL
386 scp_file: example_file.xml
387 job_wait: true
388
389 - name: Preview SCP with IDRAC components in JSON format from a NFS share path
390 dellemc.openmanage.idrac_server_config_profile:
391 idrac_ip: "{{ idrac_ip }}"
392 idrac_user: "{{ idrac_user }}"
393 idrac_password: "{{ idrac_password }}"
394 ca_path: "/path/to/ca_cert.pem"
395 share_name: "192.168.0.2:/share"
396 command: preview
397 scp_components:
398 - IDRAC
399 scp_file: example_file.xml
400 job_wait: true
401
402 - name: Preview SCP with IDRAC components in XML format from a HTTP share path
403 dellemc.openmanage.idrac_server_config_profile:
404 idrac_ip: "{{ idrac_ip }}"
405 idrac_user: "{{ idrac_user }}"
406 idrac_password: "{{ idrac_password }}"
407 ca_path: "/path/to/ca_cert.pem"
408 share_name: "http://192.168.0.1/http-share"
409 share_user: share_username
410 share_password: share_password
411 command: preview
412 scp_components:
413 - ALL
414 scp_file: example_file.xml
415 job_wait: true
416
417 - name: Preview SCP with IDRAC components in XML format from a local path
418 dellemc.openmanage.idrac_server_config_profile:
419 idrac_ip: "{{ idrac_ip }}"
420 idrac_user: "{{ idrac_user }}"
421 idrac_password: "{{ idrac_password }}"
422 ca_path: "/path/to/ca_cert.pem"
423 share_name: "/scp_folder"
424 command: preview
425 scp_components:
426 - IDRAC
427 scp_file: example_file.json
428 job_wait: false
429
430 - name: Import SCP with IDRAC components in XML format from the XML content.
431 dellemc.openmanage.idrac_server_config_profile:
432 idrac_ip: "{{ idrac_ip }}"
433 idrac_user: "{{ idrac_user }}"
434 idrac_password: "{{ idrac_password }}"
435 ca_path: "/path/to/ca_cert.pem"
436 command: import
437 scp_components:
438 - IDRAC
439 job_wait: true
440 import_buffer: "<SystemConfiguration><Component FQDD='iDRAC.Embedded.1'><Attribute Name='IPMILan.1#Enable'>
441 Disabled</Attribute></Component></SystemConfiguration>"
442
443 - name: Export SCP with ALL components in XML format using HTTP proxy.
444 dellemc.openmanage.idrac_server_config_profile:
445 idrac_ip: "{{ idrac_ip }}"
446 idrac_user: "{{ idrac_user }}"
447 idrac_password: "{{ idrac_password }}"
448 ca_path: "/path/to/ca_cert.pem"
449 scp_components:
450 - ALL
451 share_name: "http://192.168.0.1/http-share"
452 proxy_support: true
453 proxy_server: 192.168.0.5
454 proxy_port: 8080
455 proxy_username: proxy_username
456 proxy_password: proxy_password
457 proxy_type: http
458 include_in_export: passwordhashvalues
459 job_wait: true
460
461 - name: Import SCP with IDRAC and BIOS components in XML format using SOCKS4 proxy
462 dellemc.openmanage.idrac_server_config_profile:
463 idrac_ip: "{{ idrac_ip }}"
464 idrac_user: "{{ idrac_user }}"
465 idrac_password: "{{ idrac_password }}"
466 ca_path: "/path/to/ca_cert.pem"
467 command: import
468 scp_components:
469 - IDRAC
470 - BIOS
471 share_name: "https://192.168.0.1/http-share"
472 proxy_support: true
473 proxy_server: 192.168.0.6
474 proxy_port: 8080
475 proxy_type: socks4
476 scp_file: filename.xml
477 job_wait: true
478
479 - name: Import SCP with IDRAC components in JSON format from the JSON content.
480 dellemc.openmanage.idrac_server_config_profile:
481 idrac_ip: "{{ idrac_ip }}"
482 idrac_user: "{{ idrac_user }}"
483 idrac_password: "{{ idrac_password }}"
484 ca_path: "/path/to/ca_cert.pem"
485 command: import
486 scp_components:
487 - IDRAC
488 job_wait: true
489 import_buffer: "{\"SystemConfiguration\": {\"Components\": [{\"FQDD\": \"iDRAC.Embedded.1\",\"Attributes\":
490 [{\"Name\": \"SNMP.1#AgentCommunity\",\"Value\": \"public1\"}]}]}}"
491
492 - name: Export custom default
493 dellemc.openmanage.idrac_server_config_profile:
494 idrac_ip: "192.168.0.1"
495 idrac_user: "user_name"
496 idrac_password: "user_password"
497 ca_path: "/path/to/ca_cert.pem"
498 job_wait: true
499 share_name: "/scp_folder"
500 command: export_custom_defaults
501 scp_file: example_file
502
503 - name: Import custom default
504 dellemc.openmanage.idrac_server_config_profile:
505 idrac_ip: "192.168.0.1"
506 idrac_user: "user_name"
507 idrac_password: "user_password"
508 ca_path: "/path/to/ca_cert.pem"
509 job_wait: true
510 share_name: "/scp_folder"
511 command: import_custom_defaults
512 scp_file: example_file.xml
513
514 - name: Import custom default using buffer
515 dellemc.openmanage.idrac_server_config_profile:
516 idrac_ip: "192.168.0.1"
517 idrac_user: "user_name"
518 idrac_password: "user_password"
519 ca_path: "/path/to/ca_cert.pem"
520 job_wait: true
521 command: import_custom_defaults
522 import_buffer: "<SystemConfiguration><Component FQDD='iDRAC.Embedded.1'><Attribute Name='IPMILan.1#Enable'>Disabled</Attribute>
523 </Component></SystemConfiguration>"
524 '''
525
526 RETURN = r'''
527 ---
528 msg:
529 type: str
530 description: Status of the import or export SCP job.
531 returned: always
532 sample: "Successfully imported the Server Configuration Profile"
533 scp_status:
534 type: dict
535 description: SCP operation job and progress details from the iDRAC.
536 returned: success
537 sample:
538 {
539 "Id": "JID_XXXXXXXXX",
540 "JobState": "Completed",
541 "JobType": "ImportConfiguration",
542 "Message": "Successfully imported and applied Server Configuration Profile.",
543 "MessageArgs": [],
544 "MessageId": "XXX123",
545 "Name": "Import Configuration",
546 "PercentComplete": 100,
547 "StartTime": "TIME_NOW",
548 "Status": "Success",
549 "TargetSettingsURI": null,
550 "retval": true
551 }
552 error_info:
553 description: Details of the HTTP Error.
554 returned: on HTTP error
555 type: dict
556 sample: {
557 "error": {
558 "code": "Base.1.0.GeneralError",
559 "message": "A general error has occurred. See ExtendedInfo for more information.",
560 "@Message.ExtendedInfo": [
561 {
562 "MessageId": "GEN1234",
563 "RelatedProperties": [],
564 "Message": "Unable to process the request because an error occurred.",
565 "MessageArgs": [],
566 "Severity": "Critical",
567 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
568 }
569 ]
570 }
571 }
572 '''
573
574 import os
575 import re
576 import json
577 from datetime import datetime
578 from os.path import exists
579 import xml.etree.ElementTree as ET
580 from ansible.module_utils.compat.version import LooseVersion
581 from ansible_collections.dellemc.openmanage.plugins.module_utils.idrac_redfish import iDRACRedfishAPI, IdracAnsibleModule
582 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import idrac_redfish_job_tracking, \
583 strip_substr_dict, get_idrac_firmware_version, get_dynamic_uri, validate_job_wait
584 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
585 from ansible.module_utils.urls import ConnectionError, SSLValidationError
586 from ansible.module_utils.six.moves.urllib.parse import urlparse
587 from typing import Tuple
588
589
590 REDFISH_SCP_BASE_URI = "/redfish/v1/Managers/iDRAC.Embedded.1"
591 MANAGER_ID = 'iDRAC.Embedded.1'
592 CHANGES_FOUND = "Changes found to be applied."
593 INVALID_SHARE_NAME = "Unable to perform the {command} operation because an invalid Share name is entered. \
594 Only 'local' share name is supported. Enter the valid Share name and retry the operation."
595 ERR_STATUS_CODE = [400, 404]
596 CUSTOM_DEFAULTS_NOT_FOUND = "Custom defaults is not available on the iDRAC."
597 SHARE_NAME_REQUIRED = "Share name is required. Enter the valid Share name and retry the operation."
598 NO_CHANGES_FOUND = "No changes found to be applied."
599 INVALID_FILE = "Invalid file path provided."
600 INVALID_FILE_FORMAT = "An invalid export format is selected. File format '.xml' is supported. Select a valid file format and retry the operation."
601 INVALID_XML_CONTENT = "An invalid XML content is provided. Provide custom default content in a valid XML format."
602 CUSTOM_ERROR = "{command} is not supported on this firmware version of iDRAC. \
603 Enter the valid values and retry the operation."
604 JOB_URI = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs/{job_id}"
605 IGNORE_WARNING = {"ignore": "Enabled", "showerror": "Disabled"}
606 IN_EXPORTS = {"default": "Default", "readonly": "IncludeReadOnly", "passwordhashvalues": "IncludePasswordHashValues",
607 "customtelemetry": "IncludeCustomTelemetry"}
608 SCP_ALL_ERR_MSG = "The option ALL cannot be used with options IDRAC, BIOS, NIC, or RAID."
609 MINIMUM_SUPPORTED_FIRMWARE_VERSION = "7.00.00"
610 MUTUALLY_EXCLUSIVE = "import_buffer is mutually exclusive with {0}."
611 PROXY_ERR_MSG = "proxy_support is enabled but all of the following are missing: proxy_server"
612 iDRAC_JOB_URI = "/redfish/v1/Managers/iDRAC.Embedded.1/Jobs/{job_id}"
613 FAIL_MSG = "Failed to {0} scp."
614 NEGATIVE_TIMEOUT_MESSAGE = "The parameter job_wait_timeout value cannot be negative or zero."
615 TIMEOUT_MESSAGE = "The job wait timeout of {0} seconds has been exceeded. The SCP job may still be running on the server. " \
616 "Increase the job_wait_timeout value and retry."
617 TARGET_INVALID_MSG = "Unable to {command} the {invalid_targets} from the SCP file\
618 because the values {invalid_targets} are invalid.\
619 The valid values are {valid_targets}. Enter the valid values and retry the operation."
620 DOMAIN_LIST = ["\\", "@"]
621 ERROR_CODES = ["SYS041", "SYS044", "SYS045", "SYS046", "SYS047", "SYS048", "SYS050", "SYS051", "SYS062",
622 "SYS063", "SYS064", "SYS065", "SYS067", "SYS068", "SYS070", "SYS071", "SYS072",
623 "SYS073", "SYS075", "SYS076", "SYS077", "SYS078", "SYS079", "SYS080"]
624 REDFISH_EXTENDED_INFO_KEY = "@Message.ExtendedInfo"
625
626
627 def get_scp_file_format(module):
628 scp_file = module.params['scp_file']
629 if scp_file:
630 scp_file_name_format = scp_file
631 if not str(scp_file.lower()).endswith(('.xml', '.json')):
632 scp_file_name_format = "{0}.{1}".format(scp_file, module.params['export_format'].lower())
633 else:
634 d = datetime.now()
635 scp_file_name_format = "{0}_{1}{2}{3}_{4}{5}{6}_scp.{7}".format(
636 module.params["idrac_ip"], d.date().year, d.date().month, d.date().day,
637 d.time().hour, d.time().minute, d.time().second,
638 module.params['export_format'].lower())
639 return scp_file_name_format
640
641
642 def response_format_change(response, params, file_name):
643 resp = {}
644 if params["job_wait"]:
645 if hasattr(response, "json_data"):
646 response = response.json_data
647 response.pop("Description", None)
648 response.pop("Name", None)
649 response.pop("EndTime", None)
650 response.pop("StartTime", None)
651 response.pop("TaskState", None)
652 response.pop("Messages", None)
653 if response.get("Oem") is not None:
654 response.update(response["Oem"]["Dell"])
655 response.pop("Oem", None)
656 response = get_file(params, response, file_name)
657 response["retval"] = True
658 else:
659 location = response.headers.get("Location")
660 job_id = location.split("/")[-1]
661 job_uri = JOB_URI.format(job_id=job_id)
662 resp["Data"] = {"StatusCode": response.status_code, "jobid": job_id, "next_uri": job_uri}
663 resp["Job"] = {"JobId": job_id, "ResourceURI": job_uri}
664 resp["Return"] = "JobCreated"
665 resp["Status"] = "Success"
666 resp["Message"] = "none"
667 resp["StatusCode"] = response.status_code
668 resp = get_file(params, resp, file_name)
669 resp["retval"] = True
670 response = resp
671 return response
672
673
674 def get_file(params, response, file_name):
675 if params.get("share_name") is not None:
676 sep = "/" if "/" in params.get("share_name") else "\\"
677 response["file"] = "{0}{1}{2}".format(params.get("share_name"), sep, file_name)
678 return response
679
680
681 def get_proxy_share(module):
682 proxy_share = {}
683 proxy_support = module.params.get("proxy_support")
684 proxy_type = module.params["proxy_type"]
685 proxy_server = module.params.get("proxy_server")
686 proxy_port = module.params["proxy_port"]
687 proxy_username = module.params.get("proxy_username")
688 proxy_password = module.params.get("proxy_password")
689 if proxy_support is True and proxy_server is None:
690 module.fail_json(msg=PROXY_ERR_MSG)
691 if proxy_support is True:
692 proxy_share["proxy_server"] = proxy_server
693 proxy_share["proxy_username"] = proxy_username
694 proxy_share["proxy_password"] = proxy_password
695 proxy_share["proxy_port"] = proxy_port
696 proxy_share["proxy_type"] = proxy_type.upper()
697 proxy_share["proxy_support"] = "Enabled"
698 else:
699 proxy_share["proxy_support"] = "Disabled"
700 return proxy_share
701
702
703 def run_export_import_scp_http(idrac, module):
704 share_url = urlparse(module.params["share_name"])
705 share = {}
706 scp_file = module.params.get("scp_file")
707 share["share_ip"] = share_url.netloc
708 share["share_name"] = share_url.path.strip('/')
709 share["share_type"] = share_url.scheme.upper()
710 share["file_name"] = scp_file
711 scp_file_name_format = scp_file
712 share["username"] = module.params.get("share_user")
713 share["password"] = module.params.get("share_password")
714 scp_target = ",".join(module.params["scp_components"])
715 command = module.params["command"]
716 if share["share_type"] == "HTTPS":
717 share["ignore_certificate_warning"] = IGNORE_WARNING[module.params["ignore_certificate_warning"]]
718 if command == "import":
719 perform_check_mode(module, idrac)
720 if share["share_type"] in ["HTTP", "HTTPS"]:
721 proxy_share = get_proxy_share(module)
722 share.update(proxy_share)
723 idrac_import_scp_params = {
724 "target": scp_target, "share": share, "job_wait": module.params["job_wait"],
725 "host_powerstate": module.params["end_host_power_state"], "shutdown_type": module.params["shutdown_type"]
726 }
727 scp_response = idrac.import_scp_share(**idrac_import_scp_params)
728 scp_response = wait_for_job_tracking_redfish(module, idrac, scp_response)
729 elif command == "export":
730 scp_file_name_format = get_scp_file_format(module)
731 share["file_name"] = scp_file_name_format
732 include_in_export = IN_EXPORTS[module.params["include_in_export"]]
733 if share["share_type"] in ["HTTP", "HTTPS"]:
734 proxy_share = get_proxy_share(module)
735 share.update(proxy_share)
736 scp_response = idrac.export_scp(export_format=module.params["export_format"],
737 export_use=module.params["export_use"],
738 target=scp_target,
739 job_wait=False, share=share, # Hardcoding it as false because job tracking is done in idrac_redfish.py as well.
740 include_in_export=include_in_export)
741 scp_response = wait_for_job_tracking_redfish(
742 module, idrac, scp_response
743 )
744 scp_response = response_format_change(scp_response, module.params, scp_file_name_format)
745 exit_on_failure(module, scp_response, command)
746 return scp_response
747
748
749 def perform_check_mode(module, idrac, http_share=True):
750 if module.check_mode:
751 module.params["job_wait"] = True
752 scp_resp = preview_scp_redfish(module, idrac, http_share, import_job_wait=True)
753 if REDFISH_EXTENDED_INFO_KEY in scp_resp:
754 scp_resp = scp_resp[REDFISH_EXTENDED_INFO_KEY][0]
755 if "SYS081" in scp_resp["MessageId"] or "SYS082" in scp_resp["MessageId"]:
756 module.exit_json(msg=CHANGES_FOUND, changed=True)
757 elif "SYS069" in scp_resp["MessageId"]:
758 module.exit_json(msg=NO_CHANGES_FOUND)
759 else:
760 module.fail_json(msg=scp_resp)
761
762
763 def get_scp_share_details(module):
764 share_name = module.params.get("share_name")
765 command = module.params["command"]
766 scp_file_name_format = get_scp_file_format(module)
767 share = {}
768 if share_name:
769 share = parse_share_name(module, share_name)
770 if command in ["export", "export_custom_defaults"]:
771 share["file_name"] = scp_file_name_format
772 return share, scp_file_name_format
773
774
775 def parse_share_name(module, share_name):
776 if ":/" in share_name:
777 nfs_split = share_name.split(":/", 1)
778 return {"share_ip": nfs_split[0], "share_name": "/{0}".format(nfs_split[1]), "share_type": "NFS"}
779 elif "\\" in share_name:
780 cifs_share = share_name.split("\\", 3)
781 share_ip = cifs_share[2]
782 share_path_name = cifs_share[-1]
783 if not any(domain in module.params.get("share_user") for domain in DOMAIN_LIST):
784 module.params["share_user"] = ".\\{0}".format(module.params.get("share_user"))
785 return {"share_ip": share_ip, "share_name": share_path_name, "share_type": "CIFS",
786 "username": module.params.get("share_user"), "password": module.params.get("share_password")}
787 else:
788 return {"share_type": "LOCAL", "share_name": share_name}
789
790
791 def export_scp_redfish(module, idrac):
792 command = module.params["command"]
793 share, scp_file_name_format = get_scp_share_details(module)
794 scp_components = ",".join(module.params["scp_components"])
795 include_in_export = IN_EXPORTS[module.params["include_in_export"]]
796 scp_response = idrac.export_scp(export_format=module.params["export_format"],
797 export_use=module.params["export_use"],
798 target=scp_components, include_in_export=include_in_export,
799 job_wait=False, share=share, ) # Assigning it as false because job tracking is done in idrac_redfish.py as well.
800 if share["share_type"] == "LOCAL":
801 scp_response = wait_for_response(scp_response, module, share, idrac)
802 scp_response = wait_for_job_tracking_redfish(
803 module, idrac, scp_response
804 )
805 scp_response = response_format_change(scp_response, module.params, scp_file_name_format)
806 exit_on_failure(module, scp_response, command)
807 return scp_response
808
809
810 def wait_for_response(scp_resp, module, share, idrac):
811 task_uri = scp_resp.headers["Location"]
812 wait_resp = idrac.wait_for_job_complete(task_uri, job_wait=True)
813 with open("{0}/{1}".format(share["share_name"], share["file_name"]), "w") as file_obj:
814 if module.params["export_format"] == "JSON":
815 json.dump(wait_resp.json_data, file_obj, indent=4)
816 else:
817 wait_resp_value = wait_resp.decode("utf-8")
818 file_obj.write(wait_resp_value)
819 return scp_resp
820
821
822 def preview_scp_redfish(module, idrac, http_share, import_job_wait=False):
823 import_buffer = module.params.get("import_buffer")
824 command = module.params["command"]
825 scp_targets = 'ALL' # Assigning it as ALL because it is the only target for preview.
826 job_wait_option = module.params["job_wait"]
827 if command == "import":
828 job_wait_option = import_job_wait
829 share = {}
830 if not import_buffer:
831 if http_share:
832 share_url = urlparse(module.params["share_name"])
833 share = {"share_ip": share_url.netloc, "share_name": share_url.path.strip('/'),
834 "share_type": share_url.scheme.upper(), "file_name": module.params.get("scp_file"),
835 "username": module.params.get("share_user"), "password": module.params.get("share_password")}
836 if http_share == "HTTPS":
837 share["ignore_certificate_warning"] = IGNORE_WARNING[module.params["ignore_certificate_warning"]]
838 else:
839 share, _scp_file_name_format = get_scp_share_details(module)
840 share["file_name"] = module.params.get("scp_file")
841 buffer_text = get_buffer_text(module, share)
842 scp_response = idrac.import_preview(import_buffer=buffer_text, target=scp_targets,
843 share=share, job_wait=False) # Assigning it as false because job tracking is done in idrac_redfish.py as well
844 scp_response = wait_for_job_tracking_redfish(
845 module, idrac, scp_response)
846 else:
847 scp_response = idrac.import_preview(import_buffer=import_buffer, target=scp_targets, job_wait=job_wait_option)
848 scp_response = response_format_change(scp_response, module.params, share.get("file_name"))
849 exit_on_failure(module, scp_response, command)
850 return scp_response
851
852
853 def exit_on_failure(module, scp_response, command):
854 if isinstance(scp_response, dict) and (scp_response.get("TaskStatus") == "Critical" or
855 scp_response.get("JobState") in ("Failed", "CompletedWithErrors")):
856 module.exit_json(msg=FAIL_MSG.format(command), scp_status=scp_response, failed=True)
857
858
859 def get_buffer_text(module, share):
860 buffer_text = None
861 if share["share_type"] == "LOCAL":
862 file_path = "{0}{1}{2}".format(share["share_name"], os.sep, share["file_name"])
863 if not exists(file_path):
864 module.fail_json(msg=INVALID_FILE)
865 with open(file_path, "r") as file_obj:
866 buffer_text = file_obj.read()
867 return buffer_text
868
869
870 def get_xml_content(module, xml_content):
871 idrac_content = None
872 try:
873 root = ET.fromstring(xml_content)
874 component = next((c for c in root.iter('Component') if c.get('FQDD') == MANAGER_ID), None)
875 if component:
876 idrac_content = ET.tostring(component).decode('utf-8')
877 return idrac_content
878 except ET.ParseError:
879 module.exit_json(msg=INVALID_XML_CONTENT, failed=True)
880
881
882 def clean_buffer_text(buffer_text):
883 buffer_text = re.sub(r'\s+', ' ', buffer_text)
884 buffer_text = re.sub(r'>\s+<', '><', buffer_text)
885 return buffer_text
886
887
888 def compare_custom_default_configs(module, idrac):
889 diff = True
890 scp_file = module.params.get("scp_file")
891 buffer_text = module.params.get("import_buffer")
892 idrac_cds = idrac_custom_option(idrac)
893 if idrac_cds is None:
894 return diff
895 idrac_cds = idrac_cds.body
896 if scp_file is not None:
897 share, _scp_file_name_format = get_scp_share_details(module)
898 share["file_name"] = module.params.get("scp_file")
899 buffer_text = get_buffer_text(module, share)
900 buffer_text = clean_buffer_text(buffer_text)
901 if isinstance(idrac_cds, bytes):
902 idrac_cds = idrac_cds.decode('utf-8')
903 idrac_cds = clean_buffer_text(idrac_cds)
904 imported_cds = get_xml_content(module, buffer_text)
905 idrac_cds_data = get_xml_content(module, idrac_cds)
906 if imported_cds == idrac_cds_data:
907 diff = False
908 return diff
909
910
911 def idrac_custom_option(idrac):
912 url = None
913 result = None
914 resp = get_dynamic_uri(idrac, REDFISH_SCP_BASE_URI, "Oem")
915 if resp:
916 url = resp.get("Dell", {}).get('CustomDefaultsDownloadURI', {})
917 try:
918 if url:
919 result = idrac.invoke_request(url, "GET")
920 return result
921 except HTTPError as err:
922 if err.code in ERR_STATUS_CODE:
923 return result
924
925
926 def check_mode_custom_defaults(module, content_diff):
927 if module.check_mode:
928 if content_diff:
929 module.exit_json(msg=CHANGES_FOUND, changed=True)
930 return module.exit_json(msg=NO_CHANGES_FOUND, changed=False)
931
932
933 def import_scp_redfish(module, idrac, http_share):
934 import_buffer = module.params.get("import_buffer")
935 command = module.params["command"]
936 scp_targets = ",".join(module.params["scp_components"])
937 perform_check_mode(module, idrac, http_share)
938 share = {}
939 if not import_buffer:
940 share, _scp_file_name_format = get_scp_share_details(module)
941 share["file_name"] = module.params.get("scp_file")
942 buffer_text = get_buffer_text(module, share)
943 share_dict = share
944 if share["share_type"] == "LOCAL":
945 share_dict = {}
946 idrac_import_scp_params = {
947 "import_buffer": buffer_text, "target": scp_targets, "share": share_dict, "job_wait": module.params["job_wait"],
948 "host_powerstate": module.params["end_host_power_state"], "shutdown_type": module.params["shutdown_type"]
949 }
950 scp_response = idrac.import_scp_share(**idrac_import_scp_params)
951 scp_response = wait_for_job_tracking_redfish(module, idrac, scp_response)
952 else:
953 scp_response = idrac.import_scp(import_buffer=import_buffer, target=scp_targets, job_wait=module.params["job_wait"])
954 scp_response = response_format_change(scp_response, module.params, share.get("file_name"))
955 exit_on_failure(module, scp_response, command)
956 return scp_response
957
958
959 def _handle_job_tracking_failure(module, _msg, job_dict, job_id, job_wait_timeout):
960 if _msg == "Job tracking started.":
961 module.exit_json(failed=True, status_msg=job_dict, job_id=job_id,
962 msg=TIMEOUT_MESSAGE.format(job_wait_timeout))
963 module.exit_json(failed=True, status_msg=job_dict, job_id=job_id,
964 msg=FAIL_MSG.format(module.params["command"]))
965
966
967 def wait_for_job_tracking_redfish(module, idrac, scp_response):
968 job_id = scp_response.headers["Location"].split("/")[-1]
969 job_wait_timeout = module.params.get("job_wait_timeout", 900)
970 if module.params["job_wait"]:
971 job_uri = JOB_URI.format(job_id=job_id) if generation >= 17 else iDRAC_JOB_URI.format(job_id=job_id)
972 job_failed, _msg, job_dict, _wait_time = idrac_redfish_job_tracking(
973 idrac, job_uri, max_job_wait_sec=job_wait_timeout)
974 if job_failed:
975 _handle_job_tracking_failure(module, _msg, job_dict, job_id, job_wait_timeout)
976 scp_response = job_dict
977 return scp_response
978
979
980 def validate_share_name(module):
981 share_name = module.params.get("share_name")
982 command = module.params.get("command")
983 import_buffer = module.params.get("import_buffer")
984 if share_name is None and not import_buffer:
985 module.exit_json(msg=SHARE_NAME_REQUIRED, skipped=True)
986 elif share_name and (":/" in share_name or "\\" in share_name):
987 module.exit_json(msg=INVALID_SHARE_NAME.format(share_name=share_name, command=command), skipped=True)
988
989
990 def validate_input(module, scp_components):
991 if len(scp_components) != 1 and "ALL" in scp_components:
992 module.fail_json(msg=SCP_ALL_ERR_MSG)
993 if module.params["command"] in ["import", "preview"]:
994 if module.params.get("import_buffer") is not None:
995 if module.params.get("scp_file") is not None:
996 module.fail_json(msg=MUTUALLY_EXCLUSIVE.format("scp_file"))
997 if module.params.get("share_name") is not None:
998 module.fail_json(msg=MUTUALLY_EXCLUSIVE.format("share_name"))
999
1000
1001 def validate_customdefault_input(module, command):
1002 export_format = module.params.get("export_format")
1003 validate_share_name(module)
1004 if command == "export_custom_defaults" and export_format:
1005 if export_format.lower() != 'xml':
1006 module.exit_json(msg=INVALID_FILE_FORMAT.format(export_format=export_format), failed=True)
1007 if command == "import_custom_defaults":
1008 if module.params.get("import_buffer") is not None:
1009 if module.params.get("scp_file") is not None:
1010 module.exit_json(msg=MUTUALLY_EXCLUSIVE.format("scp_file"), failed=True)
1011 if module.params.get("share_name") is not None:
1012 module.exit_json(msg=MUTUALLY_EXCLUSIVE.format("share_name"), failed=True)
1013
1014
1015 def validate_scp_components(module, idrac):
1016 components = idrac.invoke_request(REDFISH_SCP_BASE_URI, "GET")
1017 all_components = strip_substr_dict(components.json_data)
1018 scp_components = module.params.get("scp_components")
1019 command = module.params.get("command")
1020 oem = all_components['Actions']['Oem']
1021 operation_dict = {
1022 "export": "ExportSystemConfiguration",
1023 "import": "ImportSystemConfiguration",
1024 "preview": "ImportSystemConfigurationPreview"
1025 }
1026 for each in oem:
1027 if each.endswith(operation_dict.get(command.lower())):
1028 allowable = ["ALL", "BIOS", "IDRAC", "NIC", "RAID", "FC", "InfiniBand", "SupportAssist",
1029 "EventFilters", "System", "LifecycleController", "AHCI", "PCIeSSD"]
1030 invalid_comp = list(set(scp_components) - set(allowable))
1031 if invalid_comp:
1032 msg = TARGET_INVALID_MSG.format(command=command, invalid_targets=invalid_comp, valid_targets=allowable)
1033 module.exit_json(msg=msg, failed=True)
1034
1035
1036 def is_check_idrac_latest(firmware_version, generation):
1037 if generation >= 17:
1038 return True
1039 else:
1040 if LooseVersion(firmware_version) >= MINIMUM_SUPPORTED_FIRMWARE_VERSION:
1041 return True
1042 return False
1043
1044
1045 def import_custom_defaults(module, idrac):
1046 import_buffer = module.params.get("import_buffer")
1047 command = module.params["command"]
1048 cds_diff = compare_custom_default_configs(module, idrac)
1049 check_mode_custom_defaults(module, cds_diff)
1050 if not cds_diff:
1051 module.exit_json(msg=NO_CHANGES_FOUND, changed=False)
1052 share = {}
1053 if import_buffer:
1054 buffer_text = import_buffer
1055 else:
1056 share, _scp_file_name_format = get_scp_share_details(module)
1057 share["file_name"] = module.params.get("scp_file")
1058 buffer_text = get_buffer_text(module, share)
1059 payload = {"CustomDefaults": buffer_text}
1060 url = None
1061 resp = get_dynamic_uri(idrac, REDFISH_SCP_BASE_URI, "Actions")
1062 if resp:
1063 url = resp.get("Oem", {}).get('#DellManager.SetCustomDefaults', {}).get('target', {})
1064 job_resp = idrac.invoke_request(url, "POST", data=payload)
1065 scp_response = wait_for_job_tracking_redfish(module, idrac, job_resp)
1066 scp_response = response_format_change(scp_response, module.params, share.get("file_name"))
1067 exit_on_failure(module, scp_response, command)
1068 return scp_response
1069
1070
1071 def export_custom_defaults(module, idrac):
1072 share, _scp_file_name_format = get_scp_share_details(module)
1073 idrac_resp_cds = idrac_custom_option(idrac)
1074 if idrac_resp_cds is None:
1075 module.exit_json(msg=CUSTOM_DEFAULTS_NOT_FOUND, changed=False)
1076 idrac_resp_cds = idrac_resp_cds.body
1077 res = {}
1078 if share["share_type"] == "LOCAL":
1079 if isinstance(idrac_resp_cds, bytes):
1080 idrac_resp_cds = idrac_resp_cds.decode('utf-8')
1081 with open("{0}/{1}".format(share["share_name"], share["file_name"]), "w") as file_obj:
1082 file_obj.write(idrac_resp_cds)
1083 res = get_file(module.params, res, _scp_file_name_format)
1084 return res
1085
1086
1087 class ImportCustomDefaultCommand():
1088 def __init__(self, idrac, module, generation):
1089 self.idrac = idrac
1090 self.module = module
1091 self.idrac_firmware_version = get_idrac_firmware_version(self.idrac)
1092 self.generation = generation
1093
1094 def execute(self):
1095 changed = True
1096 command = self.module.params["command"]
1097 if not is_check_idrac_latest(self.idrac_firmware_version, self.generation):
1098 self.module.exit_json(msg=CUSTOM_ERROR.format(command=command),
1099 skipped=True)
1100 validate_customdefault_input(self.module, command)
1101 scp_status = import_custom_defaults(self.module, self.idrac)
1102 return scp_status, changed
1103
1104
1105 class ImportCommand():
1106 def __init__(self, idrac, http_share, module):
1107 self.idrac = idrac
1108 self.http_share = http_share
1109 self.module = module
1110
1111 def execute(self):
1112 changed = False
1113 if self.http_share:
1114 scp_status = run_export_import_scp_http(self.idrac, self.module)
1115 if "SYS069" in scp_status.get("MessageId", ""):
1116 changed = False
1117 elif "SYS053" in scp_status.get("MessageId", ""):
1118 changed = True
1119 else:
1120 scp_status = import_scp_redfish(self.module, self.idrac, self.http_share)
1121 if REDFISH_EXTENDED_INFO_KEY in scp_status:
1122 scp_status = scp_status[REDFISH_EXTENDED_INFO_KEY][0]
1123 if "No changes were applied" not in scp_status.get('Message', ""):
1124 changed = True
1125 elif "SYS043" in scp_status.get('MessageId', ""):
1126 changed = True
1127 elif "SYS069" in scp_status.get('MessageId', ""):
1128 changed = False
1129 return scp_status, changed
1130
1131
1132 class ExportCustomDefaultCommand():
1133 def __init__(self, idrac, module, generation):
1134 self.idrac = idrac
1135 self.module = module
1136 self.idrac_firmware_version = get_idrac_firmware_version(self.idrac)
1137 self.generation = generation
1138
1139 def execute(self):
1140 command = self.module.params["command"]
1141 if not is_check_idrac_latest(self.idrac_firmware_version, self.generation):
1142 self.module.exit_json(msg=CUSTOM_ERROR.format(command=command),
1143 skipped=True)
1144 validate_customdefault_input(self.module, command)
1145 scp_status = export_custom_defaults(self.module, self.idrac)
1146 return scp_status, False
1147
1148
1149 class ExportCommand():
1150 def __init__(self, idrac, http_share, module):
1151 self.idrac = idrac
1152 self.http_share = http_share
1153 self.module = module
1154
1155 def execute(self):
1156 if self.http_share:
1157 scp_status = run_export_import_scp_http(self.idrac, self.module)
1158 else:
1159 scp_status = export_scp_redfish(self.module, self.idrac)
1160 return scp_status, False
1161
1162
1163 class PreviewCommand():
1164 def __init__(self, idrac, http_share, module):
1165 self.idrac = idrac
1166 self.http_share = http_share
1167 self.module = module
1168
1169 def execute(self):
1170 scp_status = preview_scp_redfish(self.module, self.idrac, self.http_share, import_job_wait=False)
1171 return scp_status, False
1172
1173
1174 def _get_server_version(idrac: iDRACRedfishAPI) -> Tuple[int]:
1175 """
1176 Function wrapping idrac.get_server_generation. Helps with mocked testing and linting.
1177
1178 Args:
1179 idrac (iDRACRedfishAPI): iDRACRedfishAPI object.
1180
1181 Returns:
1182 Tuple[int, str]: A tuple containing the server generation and firmware version.
1183 """
1184 t = idrac.get_server_generation
1185 return t[0]
1186
1187
1188 def _exit_with_result(module, command, scp_status, changed):
1189 if module.params.get('job_wait'):
1190 scp_status = strip_substr_dict(scp_status)
1191 if command in ["import", "export", "preview"]:
1192 msg = "Successfully {0}ed the Server Configuration Profile."
1193 else:
1194 command = command.split("_")[0]
1195 msg = "Successfully {0}ed the custom defaults Server Configuration Profile."
1196 module.exit_json(changed=changed, msg=msg.format(command), scp_status=scp_status)
1197 else:
1198 if command in ["import", "export", "preview"]:
1199 msg = "Successfully triggered the job to {0} the Server Configuration Profile."
1200 else:
1201 command = command.split("_")[0]
1202 msg = "Successfully triggered the job to {0} the custom defaults Server Configuration Profile."
1203 module.exit_json(msg=msg.format(command), scp_status=scp_status)
1204
1205
1206 def main():
1207 specs = get_argument_spec()
1208
1209 module = IdracAnsibleModule(
1210 argument_spec=specs,
1211 required_one_of=[("share_name", "import_buffer")],
1212 required_if=[
1213 ["command", "export", ["share_name"]],
1214 ["command", "export_custom_defaults", ["share_name"]],
1215 ["proxy_support", True, ["proxy_server"]]
1216 ],
1217 supports_check_mode=True)
1218
1219 validate_input(module, module.params.get("scp_components"))
1220 if validate_job_wait(module):
1221 module.fail_json(msg=NEGATIVE_TIMEOUT_MESSAGE)
1222 try:
1223 http_share = False
1224 msg = None
1225 command = module.params.get("command")
1226 if module.params.get("share_name") is not None:
1227 http_share = module.params["share_name"].lower().startswith(('http://', 'https://'))
1228 with iDRACRedfishAPI(module.params) as idrac:
1229 gen_details = _get_server_version(idrac)
1230 global generation
1231 generation = gen_details
1232 if command in ["import", "export", "preview"]:
1233 validate_scp_components(module, idrac)
1234 command_map = {
1235 "import": (ImportCommand, True),
1236 "export": (ExportCommand, True),
1237 "import_custom_defaults": (ImportCustomDefaultCommand, False),
1238 "export_custom_defaults": (ExportCustomDefaultCommand, False),
1239 "preview": (PreviewCommand, True)
1240 }
1241 command_obj_class, http_share_req = command_map.get(command)
1242 if http_share_req:
1243 command_obj = command_obj_class(idrac, http_share, module)
1244 else:
1245 command_obj = command_obj_class(idrac, module, generation)
1246 scp_status, changed = command_obj.execute()
1247
1248 _exit_with_result(module, command, scp_status, changed)
1249 except HTTPError as err:
1250 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
1251 except URLError as err:
1252 module.exit_json(msg=str(err), unreachable=True)
1253 except (ImportError, ValueError, RuntimeError, SSLValidationError,
1254 ConnectionError, KeyError, TypeError, IndexError, FileNotFoundError) as e:
1255 module.exit_json(msg=str(e), failed=True)
1256
1257
1258 def get_argument_spec():
1259 return {
1260 "command": {"required": False, "type": 'str',
1261 "choices": ['export', 'import', 'preview', 'import_custom_defaults', 'export_custom_defaults'], "default": 'export'},
1262 "job_wait": {"required": True, "type": 'bool'},
1263 "job_wait_timeout": {"type": 'int', "default": 900},
1264 "share_name": {"required": False, "type": 'str'},
1265 "share_user": {"required": False, "type": 'str'},
1266 "share_password": {"required": False, "type": 'str',
1267 "aliases": ['share_pwd'], "no_log": True},
1268 "scp_components": {"type": "list", "required": False, "elements": "str",
1269 "choices": ['ALL', 'IDRAC', 'BIOS', 'NIC', 'RAID', 'FC', 'InfiniBand', 'SupportAssist',
1270 'EventFilters', 'System', 'LifecycleController', 'AHCI', 'PCIeSSD'],
1271 "default": ['ALL'], "aliases": ["target"]},
1272 "scp_file": {"required": False, "type": 'str'},
1273 "shutdown_type": {"required": False,
1274 "choices": ['Graceful', 'Forced', 'NoReboot'],
1275 "default": 'Graceful'},
1276 "end_host_power_state": {"required": False,
1277 "choices": ['On', 'Off'],
1278 "default": 'On'},
1279 "export_format": {"required": False, "type": 'str',
1280 "choices": ['JSON', 'XML'], "default": 'XML'},
1281 "export_use": {"required": False, "type": 'str',
1282 "choices": ['Default', 'Clone', 'Replace'], "default": 'Default'},
1283 "ignore_certificate_warning": {"required": False, "choices": ["ignore", "showerror"], "default": "ignore"},
1284 "include_in_export": {"required": False, "type": "str", "default": "default",
1285 "choices": ["default", "readonly", "passwordhashvalues", "customtelemetry"]},
1286 "import_buffer": {"type": "str", "required": False},
1287 "proxy_support": {"type": "bool", "required": False, "default": False},
1288 "proxy_type": {"type": "str", "required": False, "choices": ["http", "socks4"], "default": "http"},
1289 "proxy_server": {"type": "str", "required": False},
1290 "proxy_port": {"type": "str", "required": False, "default": "80"},
1291 "proxy_username": {"type": "str", "required": False},
1292 "proxy_password": {"type": "str", "required": False, "no_log": True},
1293 }
1294
1295
1296 if __name__ == '__main__':
1297 main()