| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2017, Dag Wieers (@dagwieers) <[email protected]> |
| 5 |
# Copyright: (c) 2020, Cindy Zhao (@cizhao) <[email protected]> |
| 6 |
# Copyright: (c) 2023, Samita Bhattacharjee (@samitab) <[email protected]> |
| 7 |
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 8 |
|
| 9 |
from __future__ import absolute_import, division, print_function |
| 10 |
|
| 11 |
__metaclass__ = type |
| 12 |
|
| 13 |
ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "certified"} |
| 14 |
|
| 15 |
DOCUMENTATION = r""" |
| 16 |
--- |
| 17 |
module: aci_rest |
| 18 |
short_description: Direct access to the Cisco APIC REST API |
| 19 |
description: |
| 20 |
- Enables the management of the Cisco ACI fabric through direct access to the Cisco APIC REST API. |
| 21 |
- Thanks to the idempotent nature of the APIC, this module is idempotent and reports changes. |
| 22 |
requirements: |
| 23 |
- lxml (when using XML payload) |
| 24 |
- xmljson >= 0.1.8 (when using XML payload) |
| 25 |
- python 2.7+ (when using xmljson) |
| 26 |
options: |
| 27 |
method: |
| 28 |
description: |
| 29 |
- The HTTP method of the request. |
| 30 |
- Using C(delete) is typically used for deleting objects. |
| 31 |
- Using C(get) is typically used for querying objects. |
| 32 |
- Using C(post) is typically used for modifying objects. |
| 33 |
type: str |
| 34 |
choices: [ delete, get, post ] |
| 35 |
default: get |
| 36 |
aliases: [ action ] |
| 37 |
path: |
| 38 |
description: |
| 39 |
- URI being used to execute API calls. |
| 40 |
- Must end in C(.xml) or C(.json). |
| 41 |
type: str |
| 42 |
required: true |
| 43 |
aliases: [ uri ] |
| 44 |
content: |
| 45 |
description: |
| 46 |
- When used instead of C(src), sets the payload of the API request directly. |
| 47 |
- This may be convenient to template simple requests. |
| 48 |
- For anything complex use the C(template) lookup plugin (see examples) |
| 49 |
or the C(template) module with parameter C(src). |
| 50 |
type: raw |
| 51 |
src: |
| 52 |
description: |
| 53 |
- Name of the absolute path of the filename that includes the body |
| 54 |
of the HTTP request being sent to the ACI fabric. |
| 55 |
- If you require a templated payload, use the C(content) parameter |
| 56 |
together with the C(template) lookup plugin, or use C(template). |
| 57 |
type: path |
| 58 |
aliases: [ config_file ] |
| 59 |
rsp_subtree_preserve: |
| 60 |
description: |
| 61 |
- Preserve the response for the provided path. |
| 62 |
type: bool |
| 63 |
default: false |
| 64 |
page_size: |
| 65 |
description: |
| 66 |
- The number of items to return in a single page. |
| 67 |
type: int |
| 68 |
page: |
| 69 |
description: |
| 70 |
- The page number to return. |
| 71 |
type: int |
| 72 |
normalize_payload_values: |
| 73 |
description: |
| 74 |
- If this parameter is not specified in the task, the value of environment variable ACI_NORMALIZE_PAYLOAD_VALUES will be used instead. |
| 75 |
- This parameter enforces the conversion of integer and float values to strings in Ansible Core v2.19.0 and later, as well as Jinja2 v3.1.6 and later. |
| 76 |
- To disable this conversion, set O(normalize_payload_values=false) or unset the ACI_NORMALIZE_PAYLOAD_VALUES environment variable. |
| 77 |
type: bool |
| 78 |
extends_documentation_fragment: |
| 79 |
- cisco.aci.aci |
| 80 |
- cisco.aci.annotation |
| 81 |
|
| 82 |
notes: |
| 83 |
- Certain payloads are known not to be idempotent, so be careful when constructing payloads, |
| 84 |
e.g. using C(status="created") will cause idempotency issues, use C(status="modified") instead. |
| 85 |
More information in :ref:`the ACI documentation <aci_guide_known_issues>`. |
| 86 |
- Certain payloads (and used paths) are known to report no changes happened when changes did happen. |
| 87 |
This is a known APIC problem and has been reported to the vendor. A workaround for this issue exists. |
| 88 |
More information in :ref:`the ACI documentation <aci_guide_known_issues>`. |
| 89 |
- XML payloads require the C(lxml) and C(xmljson) python libraries. For JSON payloads nothing special is needed. |
| 90 |
- If you do not have any attributes, it may be necessary to add the "attributes" key with an empty dictionnary "{}" for value |
| 91 |
as the APIC does expect the entry to precede any children. |
| 92 |
- Annotation set directly in c(src) or C(content) will take precedent over the C(annotation) parameter. |
| 93 |
seealso: |
| 94 |
- module: cisco.aci.aci_tenant |
| 95 |
- name: Cisco APIC REST API Configuration Guide |
| 96 |
description: More information about the APIC REST API. |
| 97 |
link: http://www.cisco.com/c/en/us/td/docs/switches/datacenter/aci/apic/sw/2-x/rest_cfg/2_1_x/b_Cisco_APIC_REST_API_Configuration_Guide.html |
| 98 |
author: |
| 99 |
- Dag Wieers (@dagwieers) |
| 100 |
- Cindy Zhao (@cizhao) |
| 101 |
- Samita Bhattacharjee (@samitab) |
| 102 |
""" |
| 103 |
|
| 104 |
EXAMPLES = r""" |
| 105 |
- name: Add a tenant using certificate authentication |
| 106 |
cisco.aci.aci_rest: |
| 107 |
host: apic |
| 108 |
username: admin |
| 109 |
private_key: pki/admin.key |
| 110 |
method: post |
| 111 |
path: /api/mo/uni.xml |
| 112 |
src: /home/cisco/ansible/aci/configs/aci_config.xml |
| 113 |
delegate_to: localhost |
| 114 |
|
| 115 |
- name: Add a tenant from a templated payload file from templates/ |
| 116 |
cisco.aci.aci_rest: |
| 117 |
host: apic |
| 118 |
username: admin |
| 119 |
private_key: pki/admin.key |
| 120 |
method: post |
| 121 |
path: /api/mo/uni.xml |
| 122 |
content: "{{ lookup('template', 'aci/tenant.xml.j2') }}" |
| 123 |
delegate_to: localhost |
| 124 |
|
| 125 |
- name: Add a tenant using inline YAML |
| 126 |
cisco.aci.aci_rest: |
| 127 |
host: apic |
| 128 |
username: admin |
| 129 |
private_key: pki/admin.key |
| 130 |
validate_certs: false |
| 131 |
path: /api/mo/uni.json |
| 132 |
method: post |
| 133 |
content: |
| 134 |
fvTenant: |
| 135 |
attributes: |
| 136 |
name: Sales |
| 137 |
descr: Sales department |
| 138 |
delegate_to: localhost |
| 139 |
|
| 140 |
- name: Add a tenant using a JSON string |
| 141 |
cisco.aci.aci_rest: |
| 142 |
host: apic |
| 143 |
username: admin |
| 144 |
private_key: pki/admin.key |
| 145 |
validate_certs: false |
| 146 |
path: /api/mo/uni.json |
| 147 |
method: post |
| 148 |
content: |
| 149 |
{ |
| 150 |
"fvTenant": { |
| 151 |
"attributes": { |
| 152 |
"name": "Sales", |
| 153 |
"descr": "Sales department" |
| 154 |
} |
| 155 |
} |
| 156 |
} |
| 157 |
delegate_to: localhost |
| 158 |
|
| 159 |
- name: Add a tenant using an XML string |
| 160 |
cisco.aci.aci_rest: |
| 161 |
host: apic |
| 162 |
username: admin |
| 163 |
private_key: pki/{{ aci_username }}.key |
| 164 |
validate_certs: false |
| 165 |
path: /api/mo/uni.xml |
| 166 |
method: post |
| 167 |
content: '<fvTenant name="Sales" descr="Sales departement"/>' |
| 168 |
delegate_to: localhost |
| 169 |
|
| 170 |
- name: Get tenants using password authentication |
| 171 |
cisco.aci.aci_rest: |
| 172 |
host: apic |
| 173 |
username: admin |
| 174 |
password: SomeSecretPassword |
| 175 |
method: get |
| 176 |
path: /api/node/class/fvTenant.json |
| 177 |
delegate_to: localhost |
| 178 |
register: query_result |
| 179 |
|
| 180 |
- name: Get first 5 tenants using password authentication and pagination |
| 181 |
cisco.aci.aci_rest: |
| 182 |
host: apic |
| 183 |
username: admin |
| 184 |
password: SomeSecretPassword |
| 185 |
method: get |
| 186 |
page_size: 5 |
| 187 |
path: /api/node/class/fvTenant.json |
| 188 |
delegate_to: localhost |
| 189 |
register: query_result |
| 190 |
|
| 191 |
- name: Configure contracts |
| 192 |
cisco.aci.aci_rest: |
| 193 |
host: apic |
| 194 |
username: admin |
| 195 |
private_key: pki/admin.key |
| 196 |
method: post |
| 197 |
path: /api/mo/uni.xml |
| 198 |
src: /home/cisco/ansible/aci/configs/contract_config.xml |
| 199 |
delegate_to: localhost |
| 200 |
|
| 201 |
- name: Register leaves and spines |
| 202 |
cisco.aci.aci_rest: |
| 203 |
host: apic |
| 204 |
username: admin |
| 205 |
private_key: pki/admin.key |
| 206 |
validate_certs: false |
| 207 |
method: post |
| 208 |
path: /api/mo/uni/controller/nodeidentpol.xml |
| 209 |
content: |
| 210 |
<fabricNodeIdentPol> |
| 211 |
<fabricNodeIdentP name="{{ item.name }}" nodeId="{{ item.nodeid }}" status="{{ item.status }}" serial="{{ item.serial }}"/> |
| 212 |
</fabricNodeIdentPol> |
| 213 |
with_items: |
| 214 |
- '{{ apic_leavesspines }}' |
| 215 |
delegate_to: localhost |
| 216 |
|
| 217 |
- name: Wait for all controllers to become ready |
| 218 |
cisco.aci.aci_rest: |
| 219 |
host: apic |
| 220 |
username: admin |
| 221 |
private_key: pki/admin.key |
| 222 |
validate_certs: false |
| 223 |
path: /api/node/class/topSystem.json?query-target-filter=eq(topSystem.role,"controller") |
| 224 |
register: apics |
| 225 |
until: "'totalCount' in apics and apics.totalCount|int >= groups['apic']|count" |
| 226 |
retries: 120 |
| 227 |
delay: 30 |
| 228 |
delegate_to: localhost |
| 229 |
run_once: true |
| 230 |
""" |
| 231 |
|
| 232 |
RETURN = r""" |
| 233 |
error_code: |
| 234 |
description: The REST ACI return code, useful for troubleshooting on failure |
| 235 |
returned: always |
| 236 |
type: int |
| 237 |
sample: 122 |
| 238 |
error_text: |
| 239 |
description: The REST ACI descriptive text, useful for troubleshooting on failure |
| 240 |
returned: always |
| 241 |
type: str |
| 242 |
sample: unknown managed object class foo |
| 243 |
imdata: |
| 244 |
description: Converted output returned by the APIC REST (register this for post-processing) |
| 245 |
returned: always |
| 246 |
type: str |
| 247 |
sample: [{"error": {"attributes": {"code": "122", "text": "unknown managed object class foo"}}}] |
| 248 |
payload: |
| 249 |
description: The (templated) payload send to the APIC REST API (xml or json) |
| 250 |
returned: always |
| 251 |
type: str |
| 252 |
sample: '<foo bar="boo"/>' |
| 253 |
raw: |
| 254 |
description: The raw output returned by the APIC REST API (xml or json) |
| 255 |
returned: parse error |
| 256 |
type: str |
| 257 |
sample: '<?xml version="1.0" encoding="UTF-8"?><imdata totalCount="1"><error code="122" text="unknown managed object class foo"/></imdata>' |
| 258 |
response: |
| 259 |
description: HTTP response string |
| 260 |
returned: always |
| 261 |
type: str |
| 262 |
sample: 'HTTP Error 400: Bad Request' |
| 263 |
status: |
| 264 |
description: HTTP status code |
| 265 |
returned: always |
| 266 |
type: int |
| 267 |
sample: 400 |
| 268 |
totalCount: |
| 269 |
description: Number of items in the imdata array |
| 270 |
returned: always |
| 271 |
type: str |
| 272 |
sample: '0' |
| 273 |
url: |
| 274 |
description: URL used for APIC REST call |
| 275 |
returned: success |
| 276 |
type: str |
| 277 |
sample: https://1.2.3.4/api/mo/uni/tn-[Dag].json?rsp-subtree=modified |
| 278 |
""" |
| 279 |
|
| 280 |
import json |
| 281 |
import os |
| 282 |
import re |
| 283 |
|
| 284 |
try: |
| 285 |
from ansible.module_utils.six.moves.urllib.parse import parse_qsl, urlencode, urlparse, urlunparse |
| 286 |
|
| 287 |
HAS_URLPARSE = True |
| 288 |
except Exception: |
| 289 |
HAS_URLPARSE = False |
| 290 |
|
| 291 |
# Optional, only used for XML payload |
| 292 |
try: |
| 293 |
from lxml import etree # noqa |
| 294 |
|
| 295 |
HAS_LXML_ETREE = True |
| 296 |
except ImportError: |
| 297 |
HAS_LXML_ETREE = False |
| 298 |
|
| 299 |
# Optional, only used for XML payload |
| 300 |
try: |
| 301 |
from xmljson import cobra # noqa |
| 302 |
|
| 303 |
HAS_XMLJSON_COBRA = True |
| 304 |
except ImportError: |
| 305 |
HAS_XMLJSON_COBRA = False |
| 306 |
|
| 307 |
# Optional, only used for YAML validation |
| 308 |
try: |
| 309 |
import yaml |
| 310 |
|
| 311 |
HAS_YAML = True |
| 312 |
except Exception: |
| 313 |
HAS_YAML = False |
| 314 |
|
| 315 |
from ansible.module_utils.basic import AnsibleModule, env_fallback |
| 316 |
from ansible_collections.cisco.aci.plugins.module_utils.aci import ( |
| 317 |
ACIModule, |
| 318 |
aci_argument_spec, |
| 319 |
aci_annotation_spec, |
| 320 |
convert_numbers_and_none_values_to_string, |
| 321 |
) |
| 322 |
from ansible.module_utils._text import to_text |
| 323 |
from ansible_collections.cisco.aci.plugins.module_utils.annotation_unsupported import ( |
| 324 |
ANNOTATION_UNSUPPORTED, |
| 325 |
) |
| 326 |
|
| 327 |
|
| 328 |
def update_qsl(url, params): |
| 329 |
"""Add or update a URL query string""" |
| 330 |
|
| 331 |
if HAS_URLPARSE: |
| 332 |
url_parts = list(urlparse(url)) |
| 333 |
query = dict(parse_qsl(url_parts[4])) |
| 334 |
query.update(params) |
| 335 |
url_parts[4] = urlencode(query) |
| 336 |
return urlunparse(url_parts) |
| 337 |
elif "?" in url: |
| 338 |
return url + "&" + "&".join(["%s=%s" % (k, v) for k, v in params.items()]) |
| 339 |
else: |
| 340 |
return url + "?" + "&".join(["%s=%s" % (k, v) for k, v in params.items()]) |
| 341 |
|
| 342 |
|
| 343 |
def add_annotation(annotation, payload): |
| 344 |
"""Add annotation to payload only if it has not already been added""" |
| 345 |
if annotation and isinstance(payload, dict): |
| 346 |
for key, val in payload.items(): |
| 347 |
if key in ANNOTATION_UNSUPPORTED: |
| 348 |
continue |
| 349 |
if isinstance(val, dict): |
| 350 |
att = val.get("attributes", {}) |
| 351 |
if "annotation" not in att.keys(): |
| 352 |
att["annotation"] = annotation |
| 353 |
# Recursively add annotation to children |
| 354 |
children = val.get("children", None) |
| 355 |
if children: |
| 356 |
for child in children: |
| 357 |
add_annotation(annotation, child) |
| 358 |
|
| 359 |
|
| 360 |
def add_annotation_xml(annotation, tree): |
| 361 |
"""Add annotation to payload xml only if it has not already been added""" |
| 362 |
if annotation: |
| 363 |
for element in tree.iter(): |
| 364 |
if element.tag in ANNOTATION_UNSUPPORTED: |
| 365 |
continue |
| 366 |
ann = element.get("annotation") |
| 367 |
if ann is None: |
| 368 |
element.set("annotation", annotation) |
| 369 |
|
| 370 |
|
| 371 |
class ACIRESTModule(ACIModule): |
| 372 |
def changed(self, d): |
| 373 |
"""Check ACI response for changes""" |
| 374 |
|
| 375 |
if isinstance(d, dict): |
| 376 |
for k, v in d.items(): |
| 377 |
if k == "status" and v in ("created", "modified", "deleted"): |
| 378 |
return True |
| 379 |
elif self.changed(v) is True: |
| 380 |
return True |
| 381 |
elif isinstance(d, list): |
| 382 |
for i in d: |
| 383 |
if self.changed(i) is True: |
| 384 |
return True |
| 385 |
|
| 386 |
return False |
| 387 |
|
| 388 |
def response_type(self, rawoutput, rest_type="xml"): |
| 389 |
"""Handle APIC response output""" |
| 390 |
|
| 391 |
if rest_type == "json": |
| 392 |
self.response_json(rawoutput) |
| 393 |
else: |
| 394 |
self.response_xml(rawoutput) |
| 395 |
|
| 396 |
# Use APICs built-in idempotency |
| 397 |
if HAS_URLPARSE: |
| 398 |
self.result["changed"] = self.changed(self.imdata) |
| 399 |
|
| 400 |
|
| 401 |
def main(): |
| 402 |
argument_spec = aci_argument_spec() |
| 403 |
argument_spec.update(aci_annotation_spec()) |
| 404 |
argument_spec.update( |
| 405 |
path=dict(type="str", required=True, aliases=["uri"]), |
| 406 |
method=dict(type="str", default="get", choices=["delete", "get", "post"], aliases=["action"]), |
| 407 |
src=dict(type="path", aliases=["config_file"]), |
| 408 |
content=dict(type="raw"), |
| 409 |
rsp_subtree_preserve=dict(type="bool", default=False), |
| 410 |
page_size=dict(type="int"), |
| 411 |
page=dict(type="int"), |
| 412 |
# To support Ansible Core 2.19.0 and later, Jinja2 3.1.6 and later versions. |
| 413 |
normalize_payload_values=dict( |
| 414 |
type="bool", |
| 415 |
fallback=(env_fallback, ["ACI_NORMALIZE_PAYLOAD_VALUES"]), |
| 416 |
), |
| 417 |
) |
| 418 |
|
| 419 |
module = AnsibleModule( |
| 420 |
argument_spec=argument_spec, |
| 421 |
supports_check_mode=True, |
| 422 |
mutually_exclusive=[["content", "src"]], |
| 423 |
) |
| 424 |
|
| 425 |
content = module.params.get("content") |
| 426 |
path = module.params.get("path") |
| 427 |
src = module.params.get("src") |
| 428 |
rsp_subtree_preserve = module.params.get("rsp_subtree_preserve") |
| 429 |
annotation = module.params.get("annotation") |
| 430 |
page_size = module.params.get("page_size") |
| 431 |
page = module.params.get("page") |
| 432 |
normalize_payload_values = module.params.get("normalize_payload_values") |
| 433 |
if module.params.get("method") != "get" and page_size: |
| 434 |
module.fail_json(msg="Pagination parameters (page and page_size) are only valid for GET method") |
| 435 |
|
| 436 |
# Report missing file |
| 437 |
file_exists = False |
| 438 |
if src: |
| 439 |
if os.path.isfile(src): |
| 440 |
file_exists = True |
| 441 |
else: |
| 442 |
module.fail_json(msg="Cannot find/access src '{0}'".format(src)) |
| 443 |
|
| 444 |
# Find request type |
| 445 |
if path.find(".xml") != -1: |
| 446 |
rest_type = "xml" |
| 447 |
if not HAS_LXML_ETREE: |
| 448 |
module.fail_json(msg="The lxml python library is missing, or lacks etree support.") |
| 449 |
if not HAS_XMLJSON_COBRA: |
| 450 |
module.fail_json(msg="The xmljson python library is missing, or lacks cobra support.") |
| 451 |
elif path.find(".json") != -1: |
| 452 |
rest_type = "json" |
| 453 |
else: |
| 454 |
module.fail_json(msg="Failed to find REST API payload type (neither .xml nor .json).") |
| 455 |
|
| 456 |
aci = ACIRESTModule(module) |
| 457 |
aci.result["status"] = -1 # Ensure we always return a status |
| 458 |
|
| 459 |
# We include the payload as it may be templated |
| 460 |
payload = content |
| 461 |
if file_exists: |
| 462 |
with open(src, "r") as config_object: |
| 463 |
# TODO: Would be nice to template this, requires action-plugin |
| 464 |
payload = config_object.read() |
| 465 |
|
| 466 |
# Validate payload |
| 467 |
if rest_type == "json" and payload: |
| 468 |
if isinstance(payload, str) and HAS_YAML: |
| 469 |
try: |
| 470 |
payload = yaml.safe_load(payload) |
| 471 |
except Exception as e: |
| 472 |
module.fail_json(msg="Failed to parse provided JSON/YAML payload: {0}".format(to_text(e)), exception=to_text(e), payload=payload) |
| 473 |
add_annotation(annotation, payload) |
| 474 |
payload = json.dumps(convert_numbers_and_none_values_to_string(payload) if normalize_payload_values else payload) |
| 475 |
|
| 476 |
elif rest_type == "xml" and HAS_LXML_ETREE: |
| 477 |
if payload and isinstance(payload, dict) and HAS_XMLJSON_COBRA: |
| 478 |
# Validate inline YAML/JSON |
| 479 |
add_annotation(annotation, payload) |
| 480 |
payload = etree.tostring(cobra.etree(payload)[0], encoding="unicode") |
| 481 |
elif payload and isinstance(payload, str): |
| 482 |
try: |
| 483 |
# Validate XML string |
| 484 |
payload = etree.fromstring(payload) |
| 485 |
add_annotation_xml(annotation, payload) |
| 486 |
payload = etree.tostring(payload, encoding="unicode") |
| 487 |
except Exception as e: |
| 488 |
module.fail_json(msg="Failed to parse provided XML payload: {0}".format(to_text(e)), payload=payload) |
| 489 |
|
| 490 |
# Perform actual request using auth cookie (Same as aci.request(), but also supports XML) |
| 491 |
# NOTE By setting aci.path we ensure that Ansible displays accurate URL info when the plugin and the aci_rest module are used. |
| 492 |
aci.path = path.lstrip("/") |
| 493 |
aci.url = "{0}/{1}".format(aci.base_url, aci.path) |
| 494 |
|
| 495 |
if aci.params.get("method") == "get" and page_size: |
| 496 |
aci.path = update_qsl(aci.path, {"page": page, "page-size": page_size}) |
| 497 |
aci.url = update_qsl(aci.url, {"page": page, "page-size": page_size}) |
| 498 |
if aci.params.get("method") != "get" and not rsp_subtree_preserve: |
| 499 |
aci.path = "{0}?rsp-subtree=modified".format(aci.path) |
| 500 |
aci.url = update_qsl(aci.url, {"rsp-subtree": "modified"}) |
| 501 |
|
| 502 |
method = aci.params.get("method").upper() |
| 503 |
# Perform request |
| 504 |
if not aci.module.check_mode: |
| 505 |
resp, info = aci.api_call(method, aci.url, data=payload, return_response=True) |
| 506 |
# Report failure |
| 507 |
if info.get("status") != 200: |
| 508 |
try: |
| 509 |
# APIC error |
| 510 |
aci.response_type(info["body"], rest_type) |
| 511 |
aci.fail_json(msg="APIC Error {code}: {text}".format_map(aci.error)) |
| 512 |
except KeyError: |
| 513 |
# Connection error |
| 514 |
aci.fail_json(msg="Connection failed for {url}. {msg}".format_map(info)) |
| 515 |
|
| 516 |
try: |
| 517 |
aci.response_type(resp.read(), rest_type) |
| 518 |
except AttributeError: |
| 519 |
aci.response_type(info.get("body"), rest_type) |
| 520 |
|
| 521 |
aci.result["status"] = aci.status |
| 522 |
aci.result["imdata"] = aci.imdata |
| 523 |
aci.result["totalCount"] = aci.totalCount |
| 524 |
|
| 525 |
else: |
| 526 |
# NOTE A case when aci_rest is used with check mode and the apic host is used directly from the inventory |
| 527 |
if aci.connection is not None and aci.params.get("host") is None: |
| 528 |
aci.url = urlunparse(urlparse(aci.url)._replace(netloc=re.sub(r"[[\]]", "", aci.connection.get_option("host")).split(",")[0])) |
| 529 |
aci.method = method |
| 530 |
# Set changed to true so check_mode changed result is behaving similar to non aci_rest modules |
| 531 |
aci.result["changed"] = True |
| 532 |
|
| 533 |
# Only set proposed if we have a payload and thus also only allow output_path if we have a payload |
| 534 |
# DELETE and GET do not have a payload |
| 535 |
if payload and method == "POST": |
| 536 |
if rest_type == "json": |
| 537 |
payload = json.loads(payload) |
| 538 |
|
| 539 |
aci.result["proposed"] = payload |
| 540 |
|
| 541 |
output_path = aci.params.get("output_path") |
| 542 |
if output_path is not None: |
| 543 |
with open(output_path, "a") as output_file: |
| 544 |
if rest_type == "json": |
| 545 |
json.dump([payload], output_file) |
| 546 |
else: |
| 547 |
output_file.write(str(payload)) |
| 548 |
|
| 549 |
# Report success |
| 550 |
aci.exit_json(**aci.result) |
| 551 |
|
| 552 |
|
| 553 |
if __name__ == "__main__": |
| 554 |
main() |