| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
from __future__ import (absolute_import, division, print_function) |
| 14 |
|
| 15 |
__metaclass__ = type |
| 16 |
|
| 17 |
DOCUMENTATION = r""" |
| 18 |
--- |
| 19 |
module: idrac_session |
| 20 |
short_description: Manage iDRAC sessions |
| 21 |
version_added: "9.2.0" |
| 22 |
description: |
| 23 |
- This module allows the creation and deletion of sessions on iDRAC. |
| 24 |
options: |
| 25 |
hostname: |
| 26 |
description: |
| 27 |
- IP address or hostname of the iDRAC. |
| 28 |
type: str |
| 29 |
aliases: [idrac_ip] |
| 30 |
username: |
| 31 |
description: |
| 32 |
- Username of the iDRAC. If the username is not provided, then |
| 33 |
the environment variable E(IDRAC_USERNAME) is used. |
| 34 |
- I(username) is required when I(state) is C(present). |
| 35 |
type: str |
| 36 |
aliases: [idrac_user] |
| 37 |
password: |
| 38 |
description: |
| 39 |
- Password of the iDRAC. If the password is not provided, then |
| 40 |
the environment variable E(IDRAC_PASSWORD) is used. |
| 41 |
- I(password) is required when I(state) is C(present). |
| 42 |
type: str |
| 43 |
aliases: [idrac_password] |
| 44 |
port: |
| 45 |
description: |
| 46 |
- Port of the iDRAC. |
| 47 |
type: int |
| 48 |
default: 443 |
| 49 |
validate_certs: |
| 50 |
description: |
| 51 |
- If C(false), the SSL certificates will not be validated. |
| 52 |
- Configure C(false) only on personally controlled sites where self-signed certificates are used. |
| 53 |
type: bool |
| 54 |
default: true |
| 55 |
ca_path: |
| 56 |
description: |
| 57 |
- The Privacy Enhanced Mail (PEM) file that contains a CA certificate to be used for the validation. |
| 58 |
type: path |
| 59 |
timeout: |
| 60 |
description: |
| 61 |
- The https socket level timeout in seconds. |
| 62 |
type: int |
| 63 |
default: 30 |
| 64 |
state: |
| 65 |
description: |
| 66 |
- The state of the session in an iDRAC. |
| 67 |
- C(present) creates a session. |
| 68 |
- C(absent) deletes a session. |
| 69 |
- Module will always report changes found to be applied when I(state) is C(present). |
| 70 |
choices: [present, absent] |
| 71 |
type: str |
| 72 |
default: present |
| 73 |
x_auth_token: |
| 74 |
description: |
| 75 |
- Authentication token. |
| 76 |
- I(x_auth_token) is required when I(state) is C(absent). |
| 77 |
type: str |
| 78 |
aliases: ['auth_token'] |
| 79 |
session_id: |
| 80 |
description: |
| 81 |
- Session ID of the iDRAC. |
| 82 |
- I(session_id) is required when I(state) is C(absent). |
| 83 |
type: str |
| 84 |
requirements: |
| 85 |
- "python >= 3.9.6" |
| 86 |
author: |
| 87 |
- "Rajshekar P(@rajshekarp87)" |
| 88 |
- "Kritika Bhateja (@Kritika-Bhateja-03)" |
| 89 |
- "Saksham Nautiyal (@Saksham-Nautiyal)" |
| 90 |
notes: |
| 91 |
- Run this module from a system that has direct access to Dell iDRAC. |
| 92 |
- This module supports IPv4 and IPv6 addresses. |
| 93 |
- This module supports C(check_mode). |
| 94 |
- This module will always report changes found to be applied when I(state) is C(present). |
| 95 |
""" |
| 96 |
|
| 97 |
EXAMPLES = r""" |
| 98 |
--- |
| 99 |
- name: Create a session |
| 100 |
dellemc.openmanage.idrac_session: |
| 101 |
hostname: 198.162.0.1 |
| 102 |
username: username |
| 103 |
password: password |
| 104 |
ca_path: "/path/to/ca_cert.pem" |
| 105 |
state: present |
| 106 |
|
| 107 |
- name: Delete a session |
| 108 |
dellemc.openmanage.idrac_session: |
| 109 |
hostname: 198.162.0.1 |
| 110 |
ca_path: "/path/to/ca_cert.pem" |
| 111 |
state: absent |
| 112 |
x_auth_token: aed4aa802b748d2f3b31deec00a6b28a |
| 113 |
session_id: 2 |
| 114 |
|
| 115 |
- name: Create a session and execute other modules |
| 116 |
block: |
| 117 |
- name: Create a session |
| 118 |
dellemc.openmanage.idrac_session: |
| 119 |
hostname: 198.162.0.1 |
| 120 |
username: username |
| 121 |
password: password |
| 122 |
ca_path: "/path/to/ca_cert.pem" |
| 123 |
state: present |
| 124 |
register: authData |
| 125 |
|
| 126 |
- name: Call idrac_firmware_info module |
| 127 |
dellemc.openmanage.idrac_firmware_info: |
| 128 |
idrac_ip: 198.162.0.1 |
| 129 |
ca_path: "/path/to/ca_cert.pem" |
| 130 |
x_auth_token: "{{ authData.x_auth_token }}" |
| 131 |
|
| 132 |
- name: Call idrac_user_info module |
| 133 |
dellemc.openmanage.idrac_user_info: |
| 134 |
idrac_ip: 198.162.0.1 |
| 135 |
ca_path: "/path/to/ca_cert.pem" |
| 136 |
x_auth_token: "{{ authData.x_auth_token }}" |
| 137 |
always: |
| 138 |
- name: Destroy a session |
| 139 |
dellemc.openmanage.idrac_session: |
| 140 |
hostname: 198.162.0.1 |
| 141 |
ca_path: "/path/to/ca_cert.pem" |
| 142 |
state: absent |
| 143 |
x_auth_token: "{{ authData.x_auth_token }}" |
| 144 |
session_id: "{{ authData.session_data.Id }}" |
| 145 |
""" |
| 146 |
|
| 147 |
RETURN = r''' |
| 148 |
--- |
| 149 |
msg: |
| 150 |
description: Status of the session operation. |
| 151 |
returned: always |
| 152 |
type: str |
| 153 |
sample: "The session has been created successfully." |
| 154 |
session_data: |
| 155 |
description: The session details. |
| 156 |
returned: For session creation operation |
| 157 |
type: dict |
| 158 |
sample: { |
| 159 |
"@Message.ExtendedInfo": [ |
| 160 |
{ |
| 161 |
"Message": "The resource has been created successfully.", |
| 162 |
"MessageArgs": [], |
| 163 |
"MessageId": "Base.1.12.Created", |
| 164 |
"RelatedProperties": [], |
| 165 |
"Resolution": "None.", |
| 166 |
"Severity": "OK" |
| 167 |
}, |
| 168 |
{ |
| 169 |
"Message": "A new resource is successfully created.", |
| 170 |
"MessageArgs": [], |
| 171 |
"MessageId": "IDRAC.2.9.SYS414", |
| 172 |
"RelatedProperties": [], |
| 173 |
"Resolution": "No response action is required.", |
| 174 |
"Severity": "Informational" |
| 175 |
} |
| 176 |
], |
| 177 |
"ClientOriginIPAddress": "100.96.37.58", |
| 178 |
"CreatedTime": "2024-04-05T01:14:01-05:00", |
| 179 |
"Description": "User Session", |
| 180 |
"Id": "74", |
| 181 |
"Name": "User Session", |
| 182 |
"Password": null, |
| 183 |
"SessionType": "Redfish", |
| 184 |
"UserName": "root" |
| 185 |
} |
| 186 |
x_auth_token: |
| 187 |
description: Authentication token. |
| 188 |
returned: For session creation operation |
| 189 |
type: str |
| 190 |
sample: "d15f17f01cd627c30173b1582642497d" |
| 191 |
error_info: |
| 192 |
description: Details of the HTTP Error. |
| 193 |
returned: On HTTP error |
| 194 |
type: dict |
| 195 |
sample: { |
| 196 |
"error": { |
| 197 |
"@Message.ExtendedInfo": [ |
| 198 |
{ |
| 199 |
"Message": "Unable to complete the operation because an invalid username |
| 200 |
and/or password is entered, and therefore authentication failed.", |
| 201 |
"MessageArgs": [], |
| 202 |
"MessageId": "IDRAC.2.9.SYS415", |
| 203 |
"RelatedProperties": [], |
| 204 |
"Resolution": "Enter valid user name and password and retry the operation.", |
| 205 |
"Severity": "Warning" |
| 206 |
} |
| 207 |
], |
| 208 |
"code": "Base.1.12.GeneralError", |
| 209 |
"message": "A general error has occurred. See ExtendedInfo for more information" |
| 210 |
} |
| 211 |
} |
| 212 |
''' |
| 213 |
|
| 214 |
|
| 215 |
import json |
| 216 |
from urllib.error import HTTPError, URLError |
| 217 |
from ansible_collections.dellemc.openmanage.plugins.module_utils.session_utils import SessionAPI |
| 218 |
from ansible.module_utils.basic import AnsibleModule |
| 219 |
from ansible.module_utils.urls import ConnectionError, SSLValidationError |
| 220 |
from ansible.module_utils.common.parameters import env_fallback |
| 221 |
from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import ( |
| 222 |
get_dynamic_uri, remove_key) |
| 223 |
|
| 224 |
REDFISH = "/redfish/v1" |
| 225 |
SESSIONS = "Sessions" |
| 226 |
ODATA = "@odata.id" |
| 227 |
ODATA_REGEX = "(.*?)@odata" |
| 228 |
|
| 229 |
CREATE_SUCCESS_MSG = "The session has been created successfully." |
| 230 |
DELETE_SUCCESS_MSG = "The session has been deleted successfully." |
| 231 |
FAILURE_MSG = "Unable to '{operation}' a session." |
| 232 |
CHANGES_FOUND_MSG = "Changes found to be applied." |
| 233 |
NO_CHANGES_FOUND_MSG = "No changes found to be applied." |
| 234 |
|
| 235 |
|
| 236 |
class Session(): |
| 237 |
""" |
| 238 |
Parent class for all session operations. |
| 239 |
""" |
| 240 |
def __init__(self, idrac, module): |
| 241 |
""" |
| 242 |
Initializes the object with the given idrac and module parameters. |
| 243 |
|
| 244 |
Args: |
| 245 |
idrac (object): The idrac object. |
| 246 |
module (object): The module object. |
| 247 |
|
| 248 |
Returns: |
| 249 |
None |
| 250 |
""" |
| 251 |
self.idrac = idrac |
| 252 |
self.module = module |
| 253 |
|
| 254 |
def get_session_url(self): |
| 255 |
""" |
| 256 |
Retrieves the URL for the sessions endpoint from the Redfish API. |
| 257 |
|
| 258 |
Returns: |
| 259 |
str: The URL for the sessions endpoint, or None if not found. |
| 260 |
""" |
| 261 |
v1_resp = get_dynamic_uri(self.idrac, REDFISH) |
| 262 |
sessions_url = v1_resp.get('Links', {}).get(SESSIONS, {}).get(ODATA, {}) |
| 263 |
return sessions_url |
| 264 |
|
| 265 |
|
| 266 |
class CreateSession(Session): |
| 267 |
""" |
| 268 |
Creates a session. |
| 269 |
""" |
| 270 |
def execute(self): |
| 271 |
""" |
| 272 |
Executes the session creation process. |
| 273 |
|
| 274 |
This function creates a session by sending a POST request to the session URL with the |
| 275 |
provided username and password. |
| 276 |
If the request is successful (status code 201), it retrieves the session details, removes |
| 277 |
any OData keys from the response, |
| 278 |
and extracts the X-Auth-Token from the response headers. It then exits the module with a |
| 279 |
success message, indicating that |
| 280 |
the session was created successfully, and provides the session data and X-Auth-Token as |
| 281 |
output variables. |
| 282 |
|
| 283 |
If the request fails (status code other than 201), it exits the module with a failure |
| 284 |
message, indicating that the session creation failed. |
| 285 |
|
| 286 |
Parameters: |
| 287 |
None |
| 288 |
|
| 289 |
Returns: |
| 290 |
None |
| 291 |
""" |
| 292 |
payload = {"UserName": self.module.params.get("username"), |
| 293 |
"Password": self.module.params.get("password")} |
| 294 |
session_url = self.get_session_url() |
| 295 |
if self.module.check_mode: |
| 296 |
self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True) |
| 297 |
session_response = self.idrac.invoke_request(session_url, "POST", data=payload) |
| 298 |
status = session_response.status_code |
| 299 |
if status == 201: |
| 300 |
session_details = session_response.json_data |
| 301 |
session_data = remove_key(session_details, regex_pattern=ODATA_REGEX) |
| 302 |
x_auth_token = session_response.headers.get('X-Auth-Token') |
| 303 |
self.module.exit_json(msg=CREATE_SUCCESS_MSG, |
| 304 |
changed=True, |
| 305 |
session_data=session_data, |
| 306 |
x_auth_token=x_auth_token) |
| 307 |
else: |
| 308 |
self.module.exit_json(msg=FAILURE_MSG.format(operation="create"), failed=True) |
| 309 |
|
| 310 |
|
| 311 |
class DeleteSession(Session): |
| 312 |
""" |
| 313 |
Deletes a session. |
| 314 |
""" |
| 315 |
def execute(self): |
| 316 |
""" |
| 317 |
Executes the deletion of a session. |
| 318 |
|
| 319 |
This function retrieves the session ID from the module parameters and constructs the |
| 320 |
session URL using the `get_session_url` method. It then invokes a DELETE request to the |
| 321 |
session URL with the session ID appended. The response from the request is stored in the |
| 322 |
`session_response` variable. |
| 323 |
|
| 324 |
If the response status code is 200, indicating a successful deletion, the function exits |
| 325 |
the module with a success message and sets the `changed` parameter to True. Otherwise, it |
| 326 |
exits the module with a failure message and sets the `failed` parameter to True. |
| 327 |
|
| 328 |
Parameters: |
| 329 |
None |
| 330 |
|
| 331 |
Returns: |
| 332 |
None |
| 333 |
""" |
| 334 |
session_id = self.module.params.get("session_id") |
| 335 |
session_url = self.get_session_url() |
| 336 |
session_status = self.get_session_status(session_url, session_id) |
| 337 |
if self.module.check_mode: |
| 338 |
if session_status == 200: |
| 339 |
self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True) |
| 340 |
else: |
| 341 |
self.module.exit_json(msg=NO_CHANGES_FOUND_MSG) |
| 342 |
else: |
| 343 |
if session_status == 200: |
| 344 |
try: |
| 345 |
session_response = self.idrac.invoke_request(session_url + f"/{session_id}", |
| 346 |
"DELETE") |
| 347 |
status = session_response.status_code |
| 348 |
if status in [200, 204]: |
| 349 |
self.module.exit_json(msg=DELETE_SUCCESS_MSG, changed=True) |
| 350 |
except HTTPError as err: |
| 351 |
filter_err = remove_key(json.load(err), regex_pattern=ODATA_REGEX) |
| 352 |
self.module.exit_json(msg=FAILURE_MSG.format(operation="delete"), |
| 353 |
error_info=filter_err, |
| 354 |
failed=True) |
| 355 |
else: |
| 356 |
self.module.exit_json(msg=NO_CHANGES_FOUND_MSG) |
| 357 |
|
| 358 |
def get_session_status(self, session_url, session_id): |
| 359 |
""" |
| 360 |
Retrieves the status of a session given its URL and ID. |
| 361 |
|
| 362 |
Args: |
| 363 |
session_url (str): The URL of the session. |
| 364 |
session_id (str): The ID of the session. |
| 365 |
|
| 366 |
|
| 367 |
Returns: |
| 368 |
int: The status code of the session status response. If an HTTPError occurs, the status |
| 369 |
code of the error is returned. |
| 370 |
""" |
| 371 |
try: |
| 372 |
session_status_response = self.idrac.invoke_request(session_url + f"/{session_id}", |
| 373 |
"GET") |
| 374 |
session_status = session_status_response.status_code |
| 375 |
except HTTPError as err: |
| 376 |
session_status = err.status |
| 377 |
return session_status |
| 378 |
|
| 379 |
|
| 380 |
def main(): |
| 381 |
""" |
| 382 |
Main function that initializes the Ansible module with the argument specs and required if |
| 383 |
conditions. |
| 384 |
It then creates a SessionAPI object with the module parameters and performs a session operation |
| 385 |
based on the state parameter. |
| 386 |
If the state is "present", it creates a CreateSession object and executes it. If the state is |
| 387 |
"absent", it creates a DeleteSession object and executes it. |
| 388 |
The session status is returned. |
| 389 |
|
| 390 |
Raises: |
| 391 |
HTTPError: If an HTTP error occurs, the error message and filtered error information are |
| 392 |
returned in the module's exit_json. |
| 393 |
URLError: If a URL error occurs, the error message is returned in the module's exit_json. |
| 394 |
SSLValidationError, ConnectionError, TypeError, ValueError, OSError: If any other error |
| 395 |
occurs, the error message is returned in the module's exit_json. |
| 396 |
|
| 397 |
Returns: |
| 398 |
None |
| 399 |
""" |
| 400 |
specs = get_argument_spec() |
| 401 |
module = AnsibleModule( |
| 402 |
argument_spec=specs, |
| 403 |
required_if=[ |
| 404 |
["state", "present", ("username", "password",)], |
| 405 |
["state", "absent", ("x_auth_token", "session_id",)] |
| 406 |
], |
| 407 |
supports_check_mode=True |
| 408 |
) |
| 409 |
|
| 410 |
try: |
| 411 |
idrac = SessionAPI(module.params) |
| 412 |
session_operation = module.params.get("state") |
| 413 |
if session_operation == "present": |
| 414 |
session_operation_obj = CreateSession(idrac, module) |
| 415 |
else: |
| 416 |
session_operation_obj = DeleteSession(idrac, module) |
| 417 |
session_operation_obj.execute() |
| 418 |
except HTTPError as err: |
| 419 |
filter_err = remove_key(json.load(err), regex_pattern=ODATA_REGEX) |
| 420 |
module.exit_json(msg=str(err), error_info=filter_err, failed=True) |
| 421 |
except URLError as err: |
| 422 |
module.exit_json(msg=str(err), unreachable=True) |
| 423 |
except (SSLValidationError, ConnectionError, TypeError, ValueError, OSError) as err: |
| 424 |
module.exit_json(msg=str(err), failed=True) |
| 425 |
|
| 426 |
|
| 427 |
def get_argument_spec(): |
| 428 |
""" |
| 429 |
Returns a dictionary representing the argument specification for a module. |
| 430 |
|
| 431 |
The dictionary contains the following keys and their corresponding values: |
| 432 |
- "hostname": A string representing the hostname. |
| 433 |
- "username": A string representing the username. It has a fallback option to retrieve the |
| 434 |
value from the environment variable 'IDRAC_USERNAME'. |
| 435 |
- "password": A string representing the password. It is marked as not to be logged and has a |
| 436 |
fallback option to retrieve the value from the environment variable 'IDRAC_PASSWORD'. |
| 437 |
- "port": An integer representing the port number. The default value is 443. |
| 438 |
- "validate_certs": A boolean representing whether to validate certificates. The default value |
| 439 |
is True. |
| 440 |
- "ca_path": A path representing the certificate authority path. The default value is None. |
| 441 |
- "timeout": An integer representing the timeout value. The default value is 30. |
| 442 |
- "state": A string representing the state. The default value is "present". The choices are |
| 443 |
["present", "absent"]. |
| 444 |
- "x_auth_token": A string representing the authentication token. It is marked as not to be |
| 445 |
logged. |
| 446 |
- "session_id": An integer representing the session ID. |
| 447 |
|
| 448 |
Returns: |
| 449 |
A dictionary representing the argument specification. |
| 450 |
""" |
| 451 |
return { |
| 452 |
"hostname": {"type": "str", "aliases": ["idrac_ip"]}, |
| 453 |
"username": {"type": "str", "aliases": ["idrac_user"], |
| 454 |
"fallback": (env_fallback, ['IDRAC_USERNAME'])}, |
| 455 |
"password": {"type": "str", "aliases": ["idrac_password"], "no_log": True, |
| 456 |
"fallback": (env_fallback, ['IDRAC_PASSWORD'])}, |
| 457 |
"port": {"type": "int", "default": 443}, |
| 458 |
"validate_certs": {"type": "bool", "default": True}, |
| 459 |
"ca_path": {"type": "path", "default": None}, |
| 460 |
"timeout": {"type": "int", "default": 30}, |
| 461 |
"session_id": {"type": "str"}, |
| 462 |
"state": {"type": 'str', "default": "present", "choices": ["present", "absent"]}, |
| 463 |
"x_auth_token": {"type": "str", "no_log": True, "aliases": ['auth_token']} |
| 464 |
} |
| 465 |
|
| 466 |
|
| 467 |
if __name__ == '__main__': |
| 468 |
main() |