| 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: ome_session |
| 20 |
short_description: Manage OpenManage Enterprise and OpenManage Enterprise modular sessions |
| 21 |
version_added: "9.3.0" |
| 22 |
description: |
| 23 |
- This module allows you to create and delete sessions on OpenManage Enterprise and OpenManage Enterprise Modular. |
| 24 |
options: |
| 25 |
hostname: |
| 26 |
description: |
| 27 |
- IP address or hostname of the OpenManage Enterprise. |
| 28 |
type: str |
| 29 |
username: |
| 30 |
description: |
| 31 |
- Username of the OpenManage Enterprise. If the username is not provided, then |
| 32 |
the environment variable E(OME_USERNAME) is used. |
| 33 |
- I(username) is required when I(state) is C(present). |
| 34 |
type: str |
| 35 |
password: |
| 36 |
description: |
| 37 |
- Password of the OpenManage Enterprise. If the password is not provided, then |
| 38 |
the environment variable E(OME_PASSWORD) is used. |
| 39 |
- I(password) is required when I(state) is C(present). |
| 40 |
type: str |
| 41 |
port: |
| 42 |
description: |
| 43 |
- Port of the OpenManage Enterprise. |
| 44 |
type: int |
| 45 |
default: 443 |
| 46 |
validate_certs: |
| 47 |
description: |
| 48 |
- If C(false), the SSL certificates will not be validated. |
| 49 |
- Configure C(false) only on personally controlled sites where self-signed certificates are used. |
| 50 |
type: bool |
| 51 |
default: true |
| 52 |
ca_path: |
| 53 |
description: |
| 54 |
- The Privacy Enhanced Mail (PEM) file that contains a CA certificate to be used for the validation. |
| 55 |
type: path |
| 56 |
timeout: |
| 57 |
description: |
| 58 |
- The HTTPS socket level timeout in seconds. |
| 59 |
type: int |
| 60 |
default: 30 |
| 61 |
state: |
| 62 |
description: |
| 63 |
- The state of the session in OpenManage Enterprise. |
| 64 |
- C(present) creates a session. |
| 65 |
- C(absent) deletes a session. |
| 66 |
- Module will always report changes found to be applied when I(state) is C(present). |
| 67 |
choices: [present, absent] |
| 68 |
type: str |
| 69 |
default: present |
| 70 |
x_auth_token: |
| 71 |
description: |
| 72 |
- Authentication token. |
| 73 |
- I(x_auth_token) is required when I(state) is C(absent). |
| 74 |
type: str |
| 75 |
aliases: ['auth_token'] |
| 76 |
session_id: |
| 77 |
description: |
| 78 |
- Session ID of the OpenManage Enterprise. |
| 79 |
- I(session_id) is required when I(state) is C(absent). |
| 80 |
type: str |
| 81 |
requirements: |
| 82 |
- "python >= 3.9.6" |
| 83 |
author: |
| 84 |
- "Kritika Bhateja (@Kritika-Bhateja-03)" |
| 85 |
notes: |
| 86 |
- Run this module from a system that has direct access to Dell OpenManage Enterprise. |
| 87 |
- This module supports IPv4 and IPv6 addresses. |
| 88 |
- This module supports C(check_mode). |
| 89 |
- This module will always report changes found to be applied when I(state) is C(present). |
| 90 |
""" |
| 91 |
|
| 92 |
EXAMPLES = r""" |
| 93 |
--- |
| 94 |
- name: Create a session |
| 95 |
dellemc.openmanage.ome_session: |
| 96 |
hostname: 198.162.0.1 |
| 97 |
username: username |
| 98 |
password: password |
| 99 |
ca_path: "/path/to/ca_cert.pem" |
| 100 |
state: present |
| 101 |
|
| 102 |
- name: Delete a session |
| 103 |
dellemc.openmanage.ome_session: |
| 104 |
hostname: 198.162.0.1 |
| 105 |
ca_path: "/path/to/ca_cert.pem" |
| 106 |
state: absent |
| 107 |
x_auth_token: aed4aa802b748d2f3b31deec00a6b28a |
| 108 |
session_id: 4b48e9ab-809e-4087-b7c4-201a16e0143d |
| 109 |
|
| 110 |
- name: Create a session and execute other modules |
| 111 |
block: |
| 112 |
- name: Create a session |
| 113 |
dellemc.openmanage.ome_session: |
| 114 |
hostname: 198.162.0.1 |
| 115 |
username: username |
| 116 |
password: password |
| 117 |
ca_path: "/path/to/ca_cert.pem" |
| 118 |
state: present |
| 119 |
register: authData |
| 120 |
|
| 121 |
- name: Call ome_user_info module |
| 122 |
dellemc.openmanage.ome_user_info: |
| 123 |
hostname: 198.162.0.1 |
| 124 |
ca_path: "/path/to/ca_cert.pem" |
| 125 |
x_auth_token: "{{ authData.x_auth_token }}" |
| 126 |
|
| 127 |
- name: Call ome_network_vlan_info module |
| 128 |
dellemc.openmanage.ome_network_vlan_info: |
| 129 |
hostname: 198.162.0.1 |
| 130 |
ca_path: "/path/to/ca_cert.pem" |
| 131 |
x_auth_token: "{{ authData.x_auth_token }}" |
| 132 |
always: |
| 133 |
- name: Destroy a session |
| 134 |
dellemc.openmanage.ome_session: |
| 135 |
hostname: 198.162.0.1 |
| 136 |
ca_path: "/path/to/ca_cert.pem" |
| 137 |
state: absent |
| 138 |
x_auth_token: "{{ authData.x_auth_token }}" |
| 139 |
session_id: "{{ authData.session_data.Id }}" |
| 140 |
""" |
| 141 |
|
| 142 |
RETURN = r''' |
| 143 |
--- |
| 144 |
msg: |
| 145 |
description: Status of the session operation. |
| 146 |
returned: always |
| 147 |
type: str |
| 148 |
sample: "The session has been created successfully." |
| 149 |
session_data: |
| 150 |
description: The session details. |
| 151 |
returned: For session creation operation |
| 152 |
type: dict |
| 153 |
sample: { |
| 154 |
"Id": "d5c28d8e-1084-4055-9c01-e1051cfee2dd", |
| 155 |
"Description": "admin", |
| 156 |
"Name": "API", |
| 157 |
"UserName": "admin", |
| 158 |
"UserId": 10078, |
| 159 |
"Password": null, |
| 160 |
"Roles": [ |
| 161 |
"BACKUP_ADMINISTRATOR" |
| 162 |
], |
| 163 |
"IpAddress": "100.198.162.0", |
| 164 |
"StartTimeStamp": "2023-07-03 07:22:43.683", |
| 165 |
"LastAccessedTimeStamp": "2023-07-03 07:22:43.683", |
| 166 |
"DirectoryGroup": [] |
| 167 |
} |
| 168 |
x_auth_token: |
| 169 |
description: Authentication token. |
| 170 |
returned: For session creation operation |
| 171 |
type: str |
| 172 |
sample: "d15f17f01cd627c30173b1582642497d" |
| 173 |
error_info: |
| 174 |
description: Details of the HTTP Error. |
| 175 |
returned: On HTTP error |
| 176 |
type: dict |
| 177 |
sample: { |
| 178 |
"error": { |
| 179 |
"@Message.ExtendedInfo": [ |
| 180 |
{ |
| 181 |
"Message": "Unable to complete the operation because an invalid username and/or password is entered, and therefore authentication failed.", |
| 182 |
"MessageArgs": [], |
| 183 |
"[email protected]": 0, |
| 184 |
"MessageId": "IDRAC.2.7.SYS415", |
| 185 |
"RelatedProperties": [], |
| 186 |
"[email protected]": 0, |
| 187 |
"Resolution": "Enter valid user name and password and retry the operation.", |
| 188 |
"Severity": "Warning" |
| 189 |
} |
| 190 |
], |
| 191 |
"code": "Base.1.12.GeneralError", |
| 192 |
"message": "A general error has occurred. See ExtendedInfo for more information" |
| 193 |
} |
| 194 |
} |
| 195 |
''' |
| 196 |
|
| 197 |
|
| 198 |
import json |
| 199 |
from urllib.error import HTTPError, URLError |
| 200 |
from ansible_collections.dellemc.openmanage.plugins.module_utils.session_utils import Session |
| 201 |
from ansible.module_utils.basic import AnsibleModule |
| 202 |
from ansible.module_utils.urls import ConnectionError, SSLValidationError |
| 203 |
from ansible.module_utils.common.parameters import env_fallback |
| 204 |
from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import remove_key |
| 205 |
|
| 206 |
SESSION_URL = "/api/SessionService/Sessions" |
| 207 |
ODATA = "@odata.id" |
| 208 |
ODATA_REGEX = "(.*?)@odata" |
| 209 |
|
| 210 |
CREATE_SUCCESS_MSG = "The session has been created successfully." |
| 211 |
DELETE_SUCCESS_MSG = "The session has been deleted successfully." |
| 212 |
FAILURE_MSG = "Unable to '{operation}' a session." |
| 213 |
CHANGES_FOUND_MSG = "Changes found to be applied." |
| 214 |
NO_CHANGES_FOUND_MSG = "No changes found to be applied." |
| 215 |
|
| 216 |
|
| 217 |
class OMESession(Session): |
| 218 |
def __init__(self, module): |
| 219 |
super().__init__(module) |
| 220 |
self.url_kwrags = {"force_basic_auth": True, |
| 221 |
"url_username": self.module.params.get("username"), |
| 222 |
"url_password": self.module.params.get("password")} |
| 223 |
|
| 224 |
def get_session_status(self, session_url, session_id): |
| 225 |
""" |
| 226 |
Retrieves the status of a session given its URL and ID. |
| 227 |
|
| 228 |
Args: |
| 229 |
session_url (str): The URL of the session. |
| 230 |
session_id (str): The ID of the session. |
| 231 |
|
| 232 |
Returns: |
| 233 |
int: The status code of the session status response. If an HTTPError occurs, the status |
| 234 |
code of the error is returned. |
| 235 |
""" |
| 236 |
session_status_response = self.instance.invoke_request(SESSION_URL, "GET") |
| 237 |
sessions_data = session_status_response.json_data |
| 238 |
session_ids = [session_id["@odata.id"].split("'")[1] for session_id in sessions_data["value"]] |
| 239 |
session_status = session_id in session_ids |
| 240 |
return session_status |
| 241 |
|
| 242 |
def create_session(self): |
| 243 |
""" |
| 244 |
Executes the session creation process. |
| 245 |
|
| 246 |
This function creates a session by sending a POST request to the session URL with the |
| 247 |
provided username and password. |
| 248 |
If the request is successful (status code 201), it retrieves the session details, removes |
| 249 |
any OData keys from the response, |
| 250 |
and extracts the X-Auth-Token from the response headers. It then exits the module with a |
| 251 |
success message, indicating that |
| 252 |
the session was created successfully, and provides the session data and X-Auth-Token as |
| 253 |
output variables. |
| 254 |
|
| 255 |
If the request fails (status code other than 201), it exits the module with a failure |
| 256 |
message, indicating that the session creation failed. |
| 257 |
|
| 258 |
Parameters: |
| 259 |
None |
| 260 |
|
| 261 |
Returns: |
| 262 |
None |
| 263 |
""" |
| 264 |
payload = {"UserName": self.module.params.get("username"), |
| 265 |
"Password": self.module.params.get("password")} |
| 266 |
if self.module.check_mode: |
| 267 |
self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True) |
| 268 |
session_response = self.instance.invoke_request(SESSION_URL, "POST", data=payload, url_kwargs=self.url_kwrags) |
| 269 |
status = session_response.status_code |
| 270 |
if status == 201: |
| 271 |
session_details = session_response.json_data |
| 272 |
session_data = remove_key(session_details, regex_pattern=ODATA_REGEX) |
| 273 |
x_auth_token = session_response.headers.get('X-Auth-Token') |
| 274 |
self.module.exit_json(msg=CREATE_SUCCESS_MSG, |
| 275 |
changed=True, |
| 276 |
session_data=session_data, |
| 277 |
x_auth_token=x_auth_token) |
| 278 |
else: |
| 279 |
self.module.exit_json(msg=FAILURE_MSG.format(operation="create"), failed=True) |
| 280 |
|
| 281 |
def delete_session(self): |
| 282 |
""" |
| 283 |
Executes the deletion of a session. |
| 284 |
This function retrieves the session ID from the module parameters.It then invokes a |
| 285 |
DELETE request to the session URL with the session ID appended. The response from |
| 286 |
the request is stored in the `session_response` variable. |
| 287 |
|
| 288 |
If the response status code is 200, indicating a successful deletion, the function exits |
| 289 |
the module with a success message and sets the `changed` parameter to True. Otherwise, it |
| 290 |
exits the module with a failure message and sets the `failed` parameter to True. |
| 291 |
|
| 292 |
Parameters: |
| 293 |
None |
| 294 |
|
| 295 |
Returns: |
| 296 |
None |
| 297 |
""" |
| 298 |
session_id = self.module.params.get("session_id") |
| 299 |
session_status = self.get_session_status(SESSION_URL, session_id) |
| 300 |
if self.module.check_mode: |
| 301 |
if session_status: |
| 302 |
self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True) |
| 303 |
else: |
| 304 |
self.module.exit_json(msg=NO_CHANGES_FOUND_MSG) |
| 305 |
else: |
| 306 |
if session_status: |
| 307 |
try: |
| 308 |
delete_session_url = SESSION_URL + "('" + session_id + "')" |
| 309 |
session_response = self.instance.invoke_request(delete_session_url, "DELETE") |
| 310 |
status = session_response.status_code |
| 311 |
if status == 204: |
| 312 |
self.module.exit_json(msg=DELETE_SUCCESS_MSG, changed=True) |
| 313 |
except HTTPError as err: |
| 314 |
filter_err = remove_key(json.load(err), regex_pattern=ODATA_REGEX) |
| 315 |
self.module.exit_json(msg=FAILURE_MSG.format(operation="delete"), |
| 316 |
error_info=filter_err, |
| 317 |
failed=True) |
| 318 |
else: |
| 319 |
self.module.exit_json(msg=NO_CHANGES_FOUND_MSG) |
| 320 |
|
| 321 |
|
| 322 |
def main(): |
| 323 |
""" |
| 324 |
Main function that initializes the Ansible module with the argument specs and required if |
| 325 |
conditions. |
| 326 |
It then creates a SessionAPI object with the module parameters and performs a session operation |
| 327 |
based on the state parameter. |
| 328 |
If the state is "present", it creates a CreateSession object and executes it. If the state is |
| 329 |
"absent", it creates a DeleteSession object and executes it. |
| 330 |
The session status is returned. |
| 331 |
|
| 332 |
Raises: |
| 333 |
HTTPError: If an HTTP error occurs, the error message and filtered error information are |
| 334 |
returned in the module's exit_json. |
| 335 |
URLError: If a URL error occurs, the error message is returned in the module's exit_json. |
| 336 |
SSLValidationError, ConnectionError, TypeError, ValueError, OSError: If any other error |
| 337 |
occurs, the error message is returned in the module's exit_json. |
| 338 |
|
| 339 |
Returns: |
| 340 |
None |
| 341 |
""" |
| 342 |
specs = get_argument_spec() |
| 343 |
module = AnsibleModule( |
| 344 |
argument_spec=specs, |
| 345 |
required_if=[ |
| 346 |
["state", "present", ("username", "password",)], |
| 347 |
["state", "absent", ("x_auth_token", "session_id",)] |
| 348 |
], |
| 349 |
supports_check_mode=True |
| 350 |
) |
| 351 |
try: |
| 352 |
ome = OMESession(module) |
| 353 |
session_operation = module.params.get("state") |
| 354 |
if session_operation == "present": |
| 355 |
ome.create_session() |
| 356 |
else: |
| 357 |
ome.delete_session() |
| 358 |
except HTTPError as err: |
| 359 |
filter_err = {} |
| 360 |
if isinstance(err, dict): |
| 361 |
filter_err = remove_key(json.load(err), regex_pattern=ODATA_REGEX) |
| 362 |
module.exit_json(msg=str(err), error_info=filter_err, failed=True) |
| 363 |
except URLError as err: |
| 364 |
module.exit_json(msg=str(err), unreachable=True) |
| 365 |
except (SSLValidationError, ConnectionError, TypeError, ValueError, OSError) as err: |
| 366 |
module.exit_json(msg=str(err), failed=True) |
| 367 |
|
| 368 |
|
| 369 |
def get_argument_spec(): |
| 370 |
""" |
| 371 |
Returns a dictionary representing the argument specification for a module. |
| 372 |
|
| 373 |
The dictionary contains the following keys and their corresponding values: |
| 374 |
- "hostname": A string representing the hostname. |
| 375 |
- "username": A string representing the username. It has a fallback option to retrieve the |
| 376 |
value from the environment variable 'IDRAC_USERNAME'. |
| 377 |
- "password": A string representing the password. It is marked as not to be logged and has a |
| 378 |
fallback option to retrieve the value from the environment variable 'IDRAC_PASSWORD'. |
| 379 |
- "port": An integer representing the port number. The default value is 443. |
| 380 |
- "validate_certs": A boolean representing whether to validate certificates. The default value |
| 381 |
is True. |
| 382 |
- "ca_path": A path representing the certificate authority path. The default value is None. |
| 383 |
- "timeout": An integer representing the timeout value. The default value is 30. |
| 384 |
- "state": A string representing the state. The default value is "present". The choices are |
| 385 |
["present", "absent"]. |
| 386 |
- "x_auth_token": A string representing the authentication token. It is marked as not to be |
| 387 |
logged. |
| 388 |
- "session_id": A string representing the session ID. |
| 389 |
|
| 390 |
Returns: |
| 391 |
A dictionary representing the argument specification. |
| 392 |
""" |
| 393 |
return { |
| 394 |
"hostname": {"type": "str"}, |
| 395 |
"username": {"type": "str", "fallback": (env_fallback, ['OME_USERNAME'])}, |
| 396 |
"password": {"type": "str", "no_log": True, "fallback": (env_fallback, ['OME_PASSWORD'])}, |
| 397 |
"port": {"type": "int", "default": 443}, |
| 398 |
"validate_certs": {"type": "bool", "default": True}, |
| 399 |
"ca_path": {"type": "path", "default": None}, |
| 400 |
"timeout": {"type": "int", "default": 30}, |
| 401 |
"state": {"type": 'str', "default": "present", "choices": ["present", "absent"]}, |
| 402 |
"x_auth_token": {"type": "str", "no_log": True, "aliases": ['auth_token']}, |
| 403 |
"session_id": {"type": "str"} |
| 404 |
} |
| 405 |
|
| 406 |
|
| 407 |
if __name__ == '__main__': |
| 408 |
main() |