| 1 |
#!/usr/bin/python |
| 2 |
# Copyright (c) 2017, Dag Wieers <[email protected]> |
| 3 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
DOCUMENTATION = r""" |
| 9 |
module: imc_rest |
| 10 |
short_description: Manage Cisco IMC hardware through its REST API |
| 11 |
description: |
| 12 |
- Provides direct access to the Cisco IMC REST API. |
| 13 |
- Perform any configuration changes and actions that the Cisco IMC supports. |
| 14 |
- More information about the IMC REST API is available from |
| 15 |
U(http://www.cisco.com/c/en/us/td/docs/unified_computing/ucs/c/sw/api/3_0/b_Cisco_IMC_api_301.html). |
| 16 |
author: |
| 17 |
- Dag Wieers (@dagwieers) |
| 18 |
requirements: |
| 19 |
- lxml |
| 20 |
- xmljson >= 0.1.8 |
| 21 |
extends_documentation_fragment: |
| 22 |
- community.general._attributes |
| 23 |
attributes: |
| 24 |
check_mode: |
| 25 |
support: full |
| 26 |
diff_mode: |
| 27 |
support: none |
| 28 |
options: |
| 29 |
hostname: |
| 30 |
description: |
| 31 |
- IP Address or hostname of Cisco IMC, resolvable by Ansible control host. |
| 32 |
required: true |
| 33 |
aliases: [host, ip] |
| 34 |
type: str |
| 35 |
username: |
| 36 |
description: |
| 37 |
- Username used to login to the switch. |
| 38 |
default: admin |
| 39 |
aliases: [user] |
| 40 |
type: str |
| 41 |
password: |
| 42 |
description: |
| 43 |
- The password to use for authentication. |
| 44 |
default: password |
| 45 |
type: str |
| 46 |
path: |
| 47 |
description: |
| 48 |
- Name of the absolute path of the filename that includes the body of the http request being sent to the Cisco IMC REST |
| 49 |
API. |
| 50 |
- Parameter O(path) is mutual exclusive with parameter O(content). |
| 51 |
aliases: ['src', 'config_file'] |
| 52 |
type: path |
| 53 |
content: |
| 54 |
description: |
| 55 |
- When used instead of O(path), sets the content of the API requests directly. |
| 56 |
- This may be convenient to template simple requests, for anything complex use the M(ansible.builtin.template) module. |
| 57 |
- You can collate multiple IMC XML fragments and they are processed sequentially in a single stream, the Cisco IMC output |
| 58 |
is subsequently merged. |
| 59 |
- Parameter O(content) is mutual exclusive with parameter O(path). |
| 60 |
type: str |
| 61 |
protocol: |
| 62 |
description: |
| 63 |
- Connection protocol to use. |
| 64 |
default: https |
| 65 |
choices: [http, https] |
| 66 |
type: str |
| 67 |
timeout: |
| 68 |
description: |
| 69 |
- The socket level timeout in seconds. |
| 70 |
- This is the time that every single connection (every fragment) can spend. If this O(timeout) is reached, the module |
| 71 |
fails with a C(Connection failure) indicating that C(The read operation timed out). |
| 72 |
default: 60 |
| 73 |
type: int |
| 74 |
validate_certs: |
| 75 |
description: |
| 76 |
- If V(false), SSL certificates are not validated. |
| 77 |
- This should only set to V(false) used on personally controlled sites using self-signed certificates. |
| 78 |
type: bool |
| 79 |
default: true |
| 80 |
notes: |
| 81 |
- The XML fragments do not need an authentication cookie, this is injected by the module automatically. |
| 82 |
- The Cisco IMC XML output is being translated to JSON using the Cobra convention. |
| 83 |
- Any configConfMo change requested has a return status of C(modified), even if there was no actual change from the previous |
| 84 |
configuration. As a result, this module always reports a change on subsequent runs. In case this behaviour is fixed in |
| 85 |
a future update to Cisco IMC, this module is meant to automatically adapt. |
| 86 |
- If you get a C(Connection failure) related to C(The read operation timed out) increase the O(timeout) parameter. Some |
| 87 |
XML fragments can take longer than the default timeout. |
| 88 |
- More information about the IMC REST API is available from |
| 89 |
U(http://www.cisco.com/c/en/us/td/docs/unified_computing/ucs/c/sw/api/3_0/b_Cisco_IMC_api_301.html). |
| 90 |
""" |
| 91 |
|
| 92 |
EXAMPLES = r""" |
| 93 |
- name: Power down server |
| 94 |
community.general.imc_rest: |
| 95 |
hostname: '{{ imc_hostname }}' |
| 96 |
username: '{{ imc_username }}' |
| 97 |
password: '{{ imc_password }}' |
| 98 |
validate_certs: false # only do this when you trust the network! |
| 99 |
content: | |
| 100 |
<configConfMo><inConfig> |
| 101 |
<computeRackUnit dn="sys/rack-unit-1" adminPower="down"/> |
| 102 |
</inConfig></configConfMo> |
| 103 |
delegate_to: localhost |
| 104 |
|
| 105 |
- name: Configure IMC using multiple XML fragments |
| 106 |
community.general.imc_rest: |
| 107 |
hostname: '{{ imc_hostname }}' |
| 108 |
username: '{{ imc_username }}' |
| 109 |
password: '{{ imc_password }}' |
| 110 |
validate_certs: false # only do this when you trust the network! |
| 111 |
timeout: 120 |
| 112 |
content: | |
| 113 |
<!-- Configure Serial-on-LAN --> |
| 114 |
<configConfMo><inConfig> |
| 115 |
<solIf dn="sys/rack-unit-1/sol-if" adminState="enable" speed=="115200" comport="com0"/> |
| 116 |
</inConfig></configConfMo> |
| 117 |
|
| 118 |
<!-- Configure Console Redirection --> |
| 119 |
<configConfMo><inConfig> |
| 120 |
<biosVfConsoleRedirection dn="sys/rack-unit-1/bios/bios-settings/Console-redirection" |
| 121 |
vpBaudRate="115200" |
| 122 |
vpConsoleRedirection="com-0" |
| 123 |
vpFlowControl="none" |
| 124 |
vpTerminalType="vt100" |
| 125 |
vpPuttyKeyPad="LINUX" |
| 126 |
vpRedirectionAfterPOST="Always Enable"/> |
| 127 |
</inConfig></configConfMo> |
| 128 |
delegate_to: localhost |
| 129 |
|
| 130 |
- name: Enable PXE boot and power-cycle server |
| 131 |
community.general.imc_rest: |
| 132 |
hostname: '{{ imc_hostname }}' |
| 133 |
username: '{{ imc_username }}' |
| 134 |
password: '{{ imc_password }}' |
| 135 |
validate_certs: false # only do this when you trust the network! |
| 136 |
content: | |
| 137 |
<!-- Configure PXE boot --> |
| 138 |
<configConfMo><inConfig> |
| 139 |
<lsbootLan dn="sys/rack-unit-1/boot-policy/lan-read-only" access="read-only" order="1" prot="pxe" type="lan"/> |
| 140 |
</inConfig></configConfMo> |
| 141 |
|
| 142 |
<!-- Power cycle server --> |
| 143 |
<configConfMo><inConfig> |
| 144 |
<computeRackUnit dn="sys/rack-unit-1" adminPower="cycle-immediate"/> |
| 145 |
</inConfig></configConfMo> |
| 146 |
delegate_to: localhost |
| 147 |
|
| 148 |
- name: Reconfigure IMC to boot from storage |
| 149 |
community.general.imc_rest: |
| 150 |
hostname: '{{ imc_host }}' |
| 151 |
username: '{{ imc_username }}' |
| 152 |
password: '{{ imc_password }}' |
| 153 |
validate_certs: false # only do this when you trust the network! |
| 154 |
content: | |
| 155 |
<configConfMo><inConfig> |
| 156 |
<lsbootStorage dn="sys/rack-unit-1/boot-policy/storage-read-write" access="read-write" order="1" type="storage"/> |
| 157 |
</inConfig></configConfMo> |
| 158 |
delegate_to: localhost |
| 159 |
|
| 160 |
- name: Add customer description to server |
| 161 |
community.general.imc_rest: |
| 162 |
hostname: '{{ imc_host }}' |
| 163 |
username: '{{ imc_username }}' |
| 164 |
password: '{{ imc_password }}' |
| 165 |
validate_certs: false # only do this when you trust the network! |
| 166 |
content: | |
| 167 |
<configConfMo><inConfig> |
| 168 |
<computeRackUnit dn="sys/rack-unit-1" usrLbl="Customer Lab - POD{{ pod_id }} - {{ inventory_hostname_short }}"/> |
| 169 |
</inConfig></configConfMo> |
| 170 |
delegate_to: localhost |
| 171 |
|
| 172 |
- name: Disable HTTP and increase session timeout to max value 10800 secs |
| 173 |
community.general.imc_rest: |
| 174 |
hostname: '{{ imc_host }}' |
| 175 |
username: '{{ imc_username }}' |
| 176 |
password: '{{ imc_password }}' |
| 177 |
validate_certs: false # only do this when you trust the network! |
| 178 |
timeout: 120 |
| 179 |
content: | |
| 180 |
<configConfMo><inConfig> |
| 181 |
<commHttp dn="sys/svc-ext/http-svc" adminState="disabled"/> |
| 182 |
</inConfig></configConfMo> |
| 183 |
|
| 184 |
<configConfMo><inConfig> |
| 185 |
<commHttps dn="sys/svc-ext/https-svc" adminState="enabled" sessionTimeout="10800"/> |
| 186 |
</inConfig></configConfMo> |
| 187 |
delegate_to: localhost |
| 188 |
""" |
| 189 |
|
| 190 |
RETURN = r""" |
| 191 |
aaLogin: |
| 192 |
description: Cisco IMC XML output for the login, translated to JSON using Cobra convention. |
| 193 |
returned: success |
| 194 |
type: dict |
| 195 |
sample: | |
| 196 |
"attributes": { |
| 197 |
"cookie": "", |
| 198 |
"outCookie": "1498902428/9de6dc36-417c-157c-106c-139efe2dc02a", |
| 199 |
"outPriv": "admin", |
| 200 |
"outRefreshPeriod": "600", |
| 201 |
"outSessionId": "114", |
| 202 |
"outVersion": "2.0(13e)", |
| 203 |
"response": "yes" |
| 204 |
} |
| 205 |
configConfMo: |
| 206 |
description: Cisco IMC XML output for any configConfMo XML fragments, translated to JSON using Cobra convention. |
| 207 |
returned: success |
| 208 |
type: dict |
| 209 |
sample: | |
| 210 |
elapsed: |
| 211 |
description: Elapsed time in seconds. |
| 212 |
returned: always |
| 213 |
type: int |
| 214 |
sample: 31 |
| 215 |
response: |
| 216 |
description: HTTP response message, including content length. |
| 217 |
returned: always |
| 218 |
type: str |
| 219 |
sample: OK (729 bytes) |
| 220 |
status: |
| 221 |
description: The HTTP response status code. |
| 222 |
returned: always |
| 223 |
type: dict |
| 224 |
sample: 200 |
| 225 |
error: |
| 226 |
description: Cisco IMC XML error output for last request, translated to JSON using Cobra convention. |
| 227 |
returned: failed |
| 228 |
type: dict |
| 229 |
sample: | |
| 230 |
"attributes": { |
| 231 |
"cookie": "", |
| 232 |
"errorCode": "ERR-xml-parse-error", |
| 233 |
"errorDescr": "XML PARSING ERROR: Element 'computeRackUnit', attribute 'admin_Power': The attribute 'admin_Power' is not allowed. ", |
| 234 |
"invocationResult": "594", |
| 235 |
"response": "yes" |
| 236 |
} |
| 237 |
error_code: |
| 238 |
description: Cisco IMC error code. |
| 239 |
returned: failed |
| 240 |
type: str |
| 241 |
sample: ERR-xml-parse-error |
| 242 |
error_text: |
| 243 |
description: Cisco IMC error message. |
| 244 |
returned: failed |
| 245 |
type: str |
| 246 |
sample: | |
| 247 |
XML PARSING ERROR: Element 'computeRackUnit', attribute 'admin_Power': The attribute 'admin_Power' is not allowed. |
| 248 |
input: |
| 249 |
description: RAW XML input sent to the Cisco IMC, causing the error. |
| 250 |
returned: failed |
| 251 |
type: str |
| 252 |
sample: | |
| 253 |
<configConfMo><inConfig><computeRackUnit dn="sys/rack-unit-1" admin_Power="down"/></inConfig></configConfMo> |
| 254 |
output: |
| 255 |
description: RAW XML output received from the Cisco IMC, with error details. |
| 256 |
returned: failed |
| 257 |
type: str |
| 258 |
sample: > |
| 259 |
<error cookie="" |
| 260 |
response="yes" |
| 261 |
errorCode="ERR-xml-parse-error" |
| 262 |
invocationResult="594" |
| 263 |
errorDescr="XML PARSING ERROR: Element 'computeRackUnit', attribute 'admin_Power': The attribute 'admin_Power' is not allowed.\n" /> |
| 264 |
""" |
| 265 |
|
| 266 |
import os |
| 267 |
import traceback |
| 268 |
from itertools import zip_longest |
| 269 |
|
| 270 |
LXML_ETREE_IMP_ERR = None |
| 271 |
try: |
| 272 |
import lxml.etree |
| 273 |
|
| 274 |
HAS_LXML_ETREE = True |
| 275 |
except ImportError: |
| 276 |
LXML_ETREE_IMP_ERR = traceback.format_exc() |
| 277 |
HAS_LXML_ETREE = False |
| 278 |
|
| 279 |
XMLJSON_COBRA_IMP_ERR = None |
| 280 |
try: |
| 281 |
from xmljson import cobra |
| 282 |
|
| 283 |
HAS_XMLJSON_COBRA = True |
| 284 |
except ImportError: |
| 285 |
XMLJSON_COBRA_IMP_ERR = traceback.format_exc() |
| 286 |
HAS_XMLJSON_COBRA = False |
| 287 |
|
| 288 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 289 |
from ansible.module_utils.urls import fetch_url |
| 290 |
|
| 291 |
from ansible_collections.community.general.plugins.module_utils._datetime import ( |
| 292 |
now, |
| 293 |
) |
| 294 |
|
| 295 |
|
| 296 |
def imc_response(module, rawoutput, rawinput=""): |
| 297 |
"""Handle IMC returned data""" |
| 298 |
xmloutput = lxml.etree.fromstring(rawoutput) |
| 299 |
result = cobra.data(xmloutput) |
| 300 |
|
| 301 |
# Handle errors |
| 302 |
if xmloutput.get("errorCode") and xmloutput.get("errorDescr"): |
| 303 |
if rawinput: |
| 304 |
result["input"] = rawinput |
| 305 |
result["output"] = rawoutput |
| 306 |
result["error_code"] = xmloutput.get("errorCode") |
| 307 |
result["error_text"] = xmloutput.get("errorDescr") |
| 308 |
module.fail_json(msg=f"Request failed: {result['error_text']}", **result) |
| 309 |
|
| 310 |
return result |
| 311 |
|
| 312 |
|
| 313 |
def logout(module, url, cookie, timeout): |
| 314 |
"""Perform a logout, if needed""" |
| 315 |
data = f'<aaaLogout cookie="{cookie}" inCookie="{cookie}"/>' |
| 316 |
resp, auth = fetch_url(module, url, data=data, method="POST", timeout=timeout) |
| 317 |
|
| 318 |
|
| 319 |
def merge(one, two): |
| 320 |
"""Merge two complex nested datastructures into one""" |
| 321 |
if isinstance(one, dict) and isinstance(two, dict): |
| 322 |
copy = dict(one) |
| 323 |
copy.update({key: merge(one.get(key, None), two[key]) for key in two}) |
| 324 |
return copy |
| 325 |
|
| 326 |
elif isinstance(one, list) and isinstance(two, list): |
| 327 |
return [merge(alpha, beta) for (alpha, beta) in zip_longest(one, two)] |
| 328 |
|
| 329 |
return one if two is None else two |
| 330 |
|
| 331 |
|
| 332 |
def main(): |
| 333 |
module = AnsibleModule( |
| 334 |
argument_spec=dict( |
| 335 |
hostname=dict(type="str", required=True, aliases=["host", "ip"]), |
| 336 |
username=dict(type="str", default="admin", aliases=["user"]), |
| 337 |
password=dict(type="str", default="password", no_log=True), |
| 338 |
content=dict(type="str"), |
| 339 |
path=dict(type="path", aliases=["config_file", "src"]), |
| 340 |
protocol=dict(type="str", default="https", choices=["http", "https"]), |
| 341 |
timeout=dict(type="int", default=60), |
| 342 |
validate_certs=dict(type="bool", default=True), |
| 343 |
), |
| 344 |
supports_check_mode=True, |
| 345 |
mutually_exclusive=[["content", "path"]], |
| 346 |
) |
| 347 |
|
| 348 |
if not HAS_LXML_ETREE: |
| 349 |
module.fail_json(msg=missing_required_lib("lxml"), exception=LXML_ETREE_IMP_ERR) |
| 350 |
|
| 351 |
if not HAS_XMLJSON_COBRA: |
| 352 |
module.fail_json(msg=missing_required_lib("xmljson >= 0.1.8"), exception=XMLJSON_COBRA_IMP_ERR) |
| 353 |
|
| 354 |
hostname = module.params["hostname"] |
| 355 |
username = module.params["username"] |
| 356 |
password = module.params["password"] |
| 357 |
|
| 358 |
content = module.params["content"] |
| 359 |
path = module.params["path"] |
| 360 |
|
| 361 |
protocol = module.params["protocol"] |
| 362 |
timeout = module.params["timeout"] |
| 363 |
|
| 364 |
result = dict( |
| 365 |
failed=False, |
| 366 |
changed=False, |
| 367 |
) |
| 368 |
|
| 369 |
# Report missing file |
| 370 |
file_exists = False |
| 371 |
if path: |
| 372 |
if os.path.isfile(path): |
| 373 |
file_exists = True |
| 374 |
else: |
| 375 |
module.fail_json(msg=f"Cannot find/access path:\n{path}") |
| 376 |
|
| 377 |
start = now() |
| 378 |
|
| 379 |
# Perform login first |
| 380 |
url = f"{protocol}://{hostname}/nuova" |
| 381 |
data = f'<aaaLogin inName="{username}" inPassword="{password}"/>' |
| 382 |
resp, auth = fetch_url(module, url, data=data, method="POST", timeout=timeout) |
| 383 |
if resp is None or auth["status"] != 200: |
| 384 |
result["elapsed"] = (now() - start).seconds |
| 385 |
module.fail_json(msg=f"Task failed with error {auth['status']}: {auth['msg']}", **result) |
| 386 |
result.update(imc_response(module, resp.read())) |
| 387 |
|
| 388 |
# Store cookie for future requests |
| 389 |
cookie = "" |
| 390 |
try: |
| 391 |
cookie = result["aaaLogin"]["attributes"]["outCookie"] |
| 392 |
except Exception: |
| 393 |
module.fail_json(msg="Could not find cookie in output", **result) |
| 394 |
|
| 395 |
try: |
| 396 |
# Prepare request data |
| 397 |
if content: |
| 398 |
rawdata = content.replace("\n", "") |
| 399 |
elif file_exists: |
| 400 |
with open(path) as config_object: |
| 401 |
rawdata = config_object.read().replace("\n", "") |
| 402 |
|
| 403 |
# Wrap the XML documents in a <root> element |
| 404 |
xmldata = lxml.etree.fromstring(f"<root>{rawdata}</root>") |
| 405 |
|
| 406 |
# Handle each XML document separately in the same session |
| 407 |
for xmldoc in list(xmldata): |
| 408 |
if xmldoc.tag is lxml.etree.Comment: |
| 409 |
continue |
| 410 |
# Add cookie to XML |
| 411 |
xmldoc.set("cookie", cookie) |
| 412 |
data = lxml.etree.tostring(xmldoc) |
| 413 |
|
| 414 |
# Perform actual request |
| 415 |
resp, info = fetch_url(module, url, data=data, method="POST", timeout=timeout) |
| 416 |
if resp is None or info["status"] != 200: |
| 417 |
result["elapsed"] = (now() - start).seconds |
| 418 |
module.fail_json(msg=f"Task failed with error {info['status']}: {info['msg']}", **result) |
| 419 |
|
| 420 |
# Merge results with previous results |
| 421 |
rawoutput = resp.read() |
| 422 |
result = merge(result, imc_response(module, rawoutput, rawinput=data)) |
| 423 |
result["response"] = info["msg"] |
| 424 |
result["status"] = info["status"] |
| 425 |
|
| 426 |
# Check for any changes |
| 427 |
# NOTE: Unfortunately IMC API always report status as 'modified' |
| 428 |
xmloutput = lxml.etree.fromstring(rawoutput) |
| 429 |
results = xmloutput.xpath("/configConfMo/outConfig/*/@status") |
| 430 |
result["changed"] = "modified" in results |
| 431 |
|
| 432 |
# Report success |
| 433 |
result["elapsed"] = (now() - start).seconds |
| 434 |
module.exit_json(**result) |
| 435 |
finally: |
| 436 |
logout(module, url, cookie, timeout) |
| 437 |
|
| 438 |
|
| 439 |
if __name__ == "__main__": |
| 440 |
main() |