Debian Codegraph @

ansible_collections/cisco/aci/plugins/module_utils/aci.py

raw
1 # -*- coding: utf-8 -*-
2
3 # This code is part of Ansible, but is an independent component
4
5 # This particular file snippet, and this file snippet only, is BSD licensed.
6 # Modules you write using this snippet, which is embedded dynamically by Ansible
7 # still belong to the author of the module, and may assign their own license
8 # to the complete work.
9
10 # Copyright: (c) 2017, Dag Wieers <[email protected]>
11 # Copyright: (c) 2017, Jacob McGill (@jmcgill298)
12 # Copyright: (c) 2017, Swetha Chunduri (@schunduri)
13 # Copyright: (c) 2019, Rob Huelga (@RobW3LGA)
14 # Copyright: (c) 2020, Lionel Hercot (@lhercot) <[email protected]>
15 # Copyright: (c) 2020, Anvitha Jain (@anvitha-jain) <[email protected]>
16 # Copyright: (c) 2023, Gaspard Micol (@gmicol) <[email protected]>
17 # Copyright: (c) 2023, Shreyas Srish (@shrsr) <[email protected]>
18 # Copyright: (c) 2023, Tim Cragg (@timcragg) <[email protected]>
19 # Copyright: (c) 2024, Samita Bhattacharjee (@samiib) <[email protected]>
20 # All rights reserved.
21
22 # Redistribution and use in source and binary forms, with or without modification,
23 # are permitted provided that the following conditions are met:
24 #
25 # * Redistributions of source code must retain the above copyright
26 # notice, this list of conditions and the following disclaimer.
27 # * Redistributions in binary form must reproduce the above copyright notice,
28 # this list of conditions and the following disclaimer in the documentation
29 # and/or other materials provided with the distribution.
30 #
31 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
32 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
33 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
35 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
36 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
39 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40
41 from __future__ import absolute_import, division, print_function
42
43 __metaclass__ = type
44
45 import base64
46 import json
47 import os
48 from copy import deepcopy
49
50 from ansible.module_utils.urls import fetch_url
51 from ansible.module_utils._text import to_bytes, to_native
52 from ansible.module_utils.basic import env_fallback
53 from ansible.module_utils.connection import Connection
54
55 # Optional, only used for APIC signature-based authentication
56 try:
57 from OpenSSL.crypto import FILETYPE_PEM, load_privatekey, sign
58
59 HAS_OPENSSL = True
60 except ImportError:
61 HAS_OPENSSL = False
62
63 # Signature-based authentication using cryptography
64 try:
65 from cryptography.hazmat.primitives import serialization, hashes
66 from cryptography.hazmat.primitives.asymmetric import padding
67 from cryptography.hazmat.backends import default_backend
68
69 HAS_CRYPTOGRAPHY = True
70 except ImportError:
71 HAS_CRYPTOGRAPHY = False
72
73 # Optional, only used for XML payload
74 try:
75 import lxml.etree
76
77 HAS_LXML_ETREE = True
78 except ImportError:
79 HAS_LXML_ETREE = False
80
81 # Optional, only used for XML payload
82 try:
83 from xmljson import cobra
84
85 HAS_XMLJSON_COBRA = True
86 except ImportError:
87 HAS_XMLJSON_COBRA = False
88
89 try:
90 from ansible.module_utils.six.moves.urllib.parse import urlparse
91
92 HAS_URLPARSE = True
93 except Exception:
94 HAS_URLPARSE = False
95
96
97 def aci_argument_spec():
98 return dict(
99 host=dict(
100 type="str",
101 aliases=["hostname"],
102 fallback=(env_fallback, ["ACI_HOST"]),
103 ),
104 port=dict(type="int", required=False, fallback=(env_fallback, ["ACI_PORT"])),
105 username=dict(
106 type="str",
107 aliases=["user"],
108 fallback=(env_fallback, ["ACI_USERNAME", "ANSIBLE_NET_USERNAME"]),
109 ),
110 password=dict(
111 type="str",
112 no_log=True,
113 fallback=(env_fallback, ["ACI_PASSWORD", "ANSIBLE_NET_PASSWORD"]),
114 ),
115 # Beware, this is not the same as client_key !
116 private_key=dict(
117 type="str",
118 aliases=["cert_key"],
119 no_log=True,
120 fallback=(env_fallback, ["ACI_PRIVATE_KEY", "ANSIBLE_NET_SSH_KEYFILE"]),
121 ),
122 # Beware, this is not the same as client_cert !
123 certificate_name=dict(
124 type="str",
125 aliases=["cert_name"],
126 fallback=(env_fallback, ["ACI_CERTIFICATE_NAME"]),
127 ),
128 output_level=dict(
129 type="str",
130 default="normal",
131 choices=["debug", "info", "normal"],
132 fallback=(env_fallback, ["ACI_OUTPUT_LEVEL"]),
133 ),
134 timeout=dict(type="int", fallback=(env_fallback, ["ACI_TIMEOUT"])),
135 use_proxy=dict(type="bool", fallback=(env_fallback, ["ACI_USE_PROXY"])),
136 use_ssl=dict(type="bool", fallback=(env_fallback, ["ACI_USE_SSL"])),
137 validate_certs=dict(type="bool", fallback=(env_fallback, ["ACI_VALIDATE_CERTS"])),
138 output_path=dict(type="str", fallback=(env_fallback, ["ACI_OUTPUT_PATH"])),
139 suppress_verification=dict(
140 type="bool",
141 aliases=["no_verification", "no_verify", "suppress_verify", "ignore_verify", "ignore_verification"],
142 fallback=(env_fallback, ["ACI_SUPPRESS_VERIFICATION"]),
143 ),
144 suppress_previous=dict(type="bool", aliases=["no_previous", "ignore_previous"], fallback=(env_fallback, ["ACI_SUPPRESS_PREVIOUS"])),
145 )
146
147
148 def aci_annotation_spec():
149 return dict(
150 annotation=dict(
151 type="str",
152 default="orchestrator:ansible",
153 fallback=(env_fallback, ["ACI_ANNOTATION"]),
154 ),
155 )
156
157
158 def aci_owner_spec():
159 return dict(
160 owner_key=dict(type="str", no_log=False, fallback=(env_fallback, ["ACI_OWNER_KEY"])),
161 owner_tag=dict(type="str", fallback=(env_fallback, ["ACI_OWNER_TAG"])),
162 )
163
164
165 def enhanced_lag_spec(name_is_required=True):
166 return dict(
167 name=dict(type="str", required=name_is_required),
168 lacp_mode=dict(type="str", choices=["active", "passive"]),
169 load_balancing_mode=dict(
170 type="str",
171 choices=[
172 "dst-ip",
173 "dst-ip-l4port",
174 "dst-ip-vlan",
175 "dst-ip-l4port-vlan",
176 "dst-mac",
177 "dst-l4port",
178 "src-ip",
179 "src-ip-l4port",
180 "src-ip-vlan",
181 "src-ip-l4port-vlan",
182 "src-mac",
183 "src-l4port",
184 "src-dst-ip",
185 "src-dst-ip-l4port",
186 "src-dst-ip-vlan",
187 "src-dst-ip-l4port-vlan",
188 "src-dst-mac",
189 "src-dst-l4port",
190 "src-port-id",
191 "vlan",
192 ],
193 ),
194 number_uplinks=dict(type="int"),
195 )
196
197
198 def netflow_spec():
199 return dict(
200 name=dict(type="str", required=True),
201 active_flow_timeout=dict(type="int"),
202 idle_flow_timeout=dict(type="int"),
203 sampling_rate=dict(type="int"),
204 )
205
206
207 def expression_spec():
208 return dict(
209 key=dict(type="str", required=True, no_log=False),
210 operator=dict(
211 type="str",
212 choices=[
213 "not_in",
214 "in",
215 "equals",
216 "not_equals",
217 "has_key",
218 "does_not_have_key",
219 ],
220 required=True,
221 ),
222 value=dict(type="str"),
223 )
224
225
226 def aci_contract_qos_spec():
227 return dict(type="str", choices=["level1", "level2", "level3", "unspecified"])
228
229
230 def aci_contract_dscp_spec(direction=None):
231 return dict(
232 type="str",
233 aliases=["target" if not direction else "target_{0}".format(direction)],
234 choices=[
235 "AF11",
236 "AF12",
237 "AF13",
238 "AF21",
239 "AF22",
240 "AF23",
241 "AF31",
242 "AF32",
243 "AF33",
244 "AF41",
245 "AF42",
246 "AF43",
247 "CS0",
248 "CS1",
249 "CS2",
250 "CS3",
251 "CS4",
252 "CS5",
253 "CS6",
254 "CS7",
255 "EF",
256 "VA",
257 "unspecified",
258 ],
259 )
260
261
262 def route_control_profile_spec():
263 return dict(
264 profile=dict(type="str", required=True),
265 l3out=dict(type="str"),
266 direction=dict(type="str", required=True),
267 tenant=dict(type="str", required=True),
268 )
269
270
271 def destination_epg_spec():
272 return dict(
273 tenant=dict(type="str", required=True, aliases=["tenant_name"]),
274 ap=dict(type="str", required=True, aliases=["ap_name", "app_profile", "app_profile_name"]),
275 epg=dict(type="str", required=True, aliases=["epg_name"]),
276 source_ip=dict(type="str", required=True),
277 destination_ip=dict(type="str", required=True),
278 span_version=dict(type="str", choices=["version_1", "version_2"]),
279 version_enforced=dict(type="bool"),
280 flow_id=dict(type="int"),
281 ttl=dict(type="int"),
282 mtu=dict(type="int"),
283 dscp=dict(
284 type="str",
285 choices=[
286 "CS0",
287 "CS1",
288 "CS2",
289 "CS3",
290 "CS4",
291 "CS5",
292 "CS6",
293 "CS7",
294 "EF",
295 "VA",
296 "AF11",
297 "AF12",
298 "AF13",
299 "AF21",
300 "AF22",
301 "AF23",
302 "AF31",
303 "AF32",
304 "AF33",
305 "AF41",
306 "AF42",
307 "AF43",
308 "unspecified",
309 ],
310 ),
311 )
312
313
314 def ospf_spec():
315 return dict(
316 area_cost=dict(type="int"),
317 area_ctrl=dict(type="list", elements="str", choices=["redistribute", "summary", "suppress-fa", "unspecified"]),
318 area_id=dict(type="str"),
319 area_type=dict(type="str", choices=["nssa", "regular", "stub"]),
320 description=dict(type="str", aliases=["descr"]),
321 multipod_internal=dict(type="str", choices=["no", "yes"]),
322 name_alias=dict(type="str"),
323 )
324
325
326 def integrate_url(httpapi_url, local_path):
327 parse_url = urlparse(httpapi_url)
328 return {"protocol": parse_url.scheme, "host": parse_url.netloc, "path": local_path}
329
330
331 def action_rule_set_comm_spec():
332 return dict(
333 community=dict(type="str"),
334 criteria=dict(type="str", choices=["append", "none", "replace"]),
335 )
336
337
338 def action_rule_set_dampening_spec():
339 return dict(
340 half_life=dict(type="int"),
341 max_suppress_time=dict(type="int"),
342 reuse=dict(type="int"),
343 suppress=dict(type="int"),
344 )
345
346
347 def associated_netflow_exporter_epg_spec():
348 return dict(
349 tenant=dict(type="str"),
350 ap=dict(type="str"),
351 epg=dict(type="str"),
352 )
353
354
355 def associated_netflow_exporter_extepg_spec():
356 return dict(
357 tenant=dict(type="str"),
358 l3out=dict(type="str"),
359 extepg=dict(type="str"),
360 )
361
362
363 def associated_netflow_exporter_vrf_spec():
364 return dict(
365 tenant=dict(type="str"),
366 vrf=dict(type="str"),
367 )
368
369
370 def pim_interface_profile_spec():
371 return dict(
372 tenant=dict(type="str", aliases=["tenant_name"]),
373 pim=dict(type="str", aliases=["pim_interface_policy", "name"]),
374 )
375
376
377 def igmp_interface_profile_spec():
378 return dict(tenant=dict(type="str", aliases=["tenant_name"]), igmp=dict(type="str", aliases=["igmp_interface_policy", "name"]))
379
380
381 def storm_control_policy_rate_spec():
382 return dict(
383 rate=dict(type="str"),
384 burst_rate=dict(type="str"),
385 rate_type=dict(type="str", choices=["percentage", "pps"], required=True),
386 )
387
388
389 def switch_config_spec(policy_type):
390 return dict(
391 node_type=dict(type="str", aliases=["type", "switch_type"], choices=["leaf", "spine"]),
392 node=dict(type="int", aliases=["node_id"]),
393 policy_group=dict(
394 type="str",
395 aliases=[
396 "{0}_policy".format(policy_type),
397 "{0}_policy_group".format(policy_type),
398 ],
399 ),
400 state=dict(type="str", default="present", choices=["absent", "present", "query"]),
401 )
402
403
404 def convert_numbers_and_none_values_to_string(data):
405 """
406 Recursively converts None, int, and float values within dictionaries, lists, and other iterable structures to their string representations.
407 Boolean and string values are returned as-is.
408 None values are converted to an empty string "".
409 Integers and floats are converted using `str()`.
410
411 :param data: The input data structure, which can be a dictionary, list, tuple, set, int, float, str, bool, or None.
412 :return: A new data structure with None, int, and float values converted to strings.
413 """
414 if isinstance(data, (bool, str)):
415 return data
416 elif isinstance(data, (int, float)):
417 return str(data)
418 elif isinstance(data, dict):
419 return {k: convert_numbers_and_none_values_to_string(v) for k, v in data.items()}
420 elif hasattr(data, "__iter__"): # Handles lists, tuples, sets, etc.
421 return [convert_numbers_and_none_values_to_string(item) for item in data]
422 elif data is None:
423 return ""
424 else:
425 # For any other types not explicitly handled (e.g., custom objects), return as is
426 return data
427
428
429 class ACIModule(object):
430 def __init__(self, module):
431 self.module = module
432 self.params = module.params
433 self.result = dict(changed=False)
434 self.headers = dict()
435 self.child_classes = set()
436 self.connection = None
437
438 # error output
439 self.error = dict(code=None, text=None)
440
441 # normal output
442 self.existing = None
443
444 # info output
445 self.config = dict()
446 self.original = None
447 self.proposed = dict()
448 self.stdout = None
449
450 # debug output
451 self.filter_string = ""
452 self.obj_filter = None
453 self.method = None
454 self.path = None
455 self.parent_path = None
456 self.response = None
457 self.status = None
458 self.url = None
459 self.httpapi_logs = list()
460
461 # aci_rest output
462 self.imdata = None
463 self.totalCount = None
464
465 # get no verify flag
466 self.suppress_verification = self.params.get("suppress_verification")
467
468 # get suppress previous flag
469 self.suppress_previous = self.params.get("suppress_previous")
470
471 # Ensure protocol is set
472 self.define_protocol()
473
474 # Set Connection plugin
475 self.set_connection()
476
477 # Get the current working directory
478 self.params["working_directory"] = os.getcwd()
479
480 if self.module._debug:
481 self.module.warn("Enable debug output because ANSIBLE_DEBUG was set.")
482 self.params["output_level"] = "debug"
483
484 if self.params.get("port") is not None:
485 self.base_url = "{protocol}://{host}:{port}".format_map(self.params)
486 else:
487 self.base_url = "{protocol}://{host}".format_map(self.params)
488
489 if self.params.get("private_key"):
490 # Perform signature-based authentication, no need to log on separately
491 if not HAS_CRYPTOGRAPHY and not HAS_OPENSSL:
492 self.module.fail_json(msg="Cannot use signature-based authentication because cryptography (preferred) or pyopenssl are not available")
493 elif self.params.get("password") is not None:
494 self.module.warn("When doing ACI signatured-based authentication, providing parameter 'password' is not required")
495 elif self.connection is None:
496 if self.params.get("password"):
497 # Perform password-based authentication, log on using password
498 self.login()
499 else:
500 self.module.fail_json(msg="Either parameter 'password' or 'private_key' is required for authentication")
501
502 def boolean(self, value, true="yes", false="no"):
503 """Return an acceptable value back"""
504
505 # When we expect value is of type=bool
506 if value is None:
507 return None
508 elif value is True:
509 return true
510 elif value is False:
511 return false
512
513 # If all else fails, escalate back to user
514 self.module.fail_json(msg="Boolean value '%s' is an invalid ACI boolean value.")
515
516 def iso8601_format(self, dt):
517 """Return an ACI-compatible ISO8601 formatted time: 2123-12-12T00:00:00.000+00:00"""
518 try:
519 return dt.isoformat(timespec="milliseconds")
520 except Exception:
521 tz = dt.strftime("%z")
522 return "%s.%03d%s:%s" % (
523 dt.strftime("%Y-%m-%dT%H:%M:%S"),
524 dt.microsecond / 1000,
525 tz[:3],
526 tz[3:],
527 )
528
529 def define_protocol(self):
530 """Set protocol based on use_ssl parameter"""
531
532 # Set protocol for further use
533 self.params["protocol"] = "https" if self.params.get("use_ssl") or self.params.get("use_ssl") is None else "http"
534
535 def set_connection(self):
536 if self.connection is None and self.module._socket_path:
537 self.connection = Connection(self.module._socket_path)
538
539 def login(self):
540 """Log in to APIC"""
541
542 # Perform login request
543 url = "{0}/api/aaaLogin.json".format(self.base_url)
544 payload = {
545 "aaaUser": {
546 "attributes": {
547 "name": "admin" if self.params.get("username") is None else self.params.get("username"),
548 "pwd": self.params.get("password"),
549 }
550 }
551 }
552 resp, auth = self.api_call("POST", url, data=json.dumps(payload), return_response=True)
553
554 # Handle APIC response
555 if auth.get("status") != 200:
556 self.response = auth.get("msg")
557 self.status = auth.get("status")
558 try:
559 # APIC error
560 self.response_json(auth["body"])
561 self.fail_json(msg="Authentication failed: {code} {text}".format_map(self.error))
562 except KeyError:
563 # Connection error
564 self.fail_json(msg="Connection failed for {url}. {msg}".format_map(auth))
565
566 # Retain cookie for later use
567 self.headers["Cookie"] = resp.headers.get("Set-Cookie")
568
569 def cert_auth(self, path=None, payload="", method=None):
570 """Perform APIC signature-based authentication, not the expected SSL client certificate authentication."""
571
572 if method is None:
573 method = self.params.get("method").upper()
574
575 # NOTE: ACI documentation incorrectly uses complete URL
576 if path is None:
577 path = self.path
578 path = "/" + path.lstrip("/")
579
580 if payload is None:
581 payload = ""
582
583 # Check if we got a private key. This allows the use of vaulting the private key.
584 try:
585 if HAS_CRYPTOGRAPHY:
586 key = self.params.get("private_key").encode()
587 sig_key = serialization.load_pem_private_key(
588 key,
589 password=None,
590 backend=default_backend(),
591 )
592 else:
593 sig_key = load_privatekey(FILETYPE_PEM, self.params.get("private_key"))
594 except Exception:
595 if os.path.exists(self.params.get("private_key")):
596 try:
597 permission = "r"
598 if HAS_CRYPTOGRAPHY:
599 permission = "rb"
600 with open(self.params.get("private_key"), permission) as fh:
601 private_key_content = fh.read()
602 except Exception:
603 self.module.fail_json(msg="Cannot open private key file '{private_key}'.".format_map(self.params))
604 try:
605 if HAS_CRYPTOGRAPHY:
606 sig_key = serialization.load_pem_private_key(
607 private_key_content,
608 password=None,
609 backend=default_backend(),
610 )
611 else:
612 sig_key = load_privatekey(FILETYPE_PEM, private_key_content)
613 except Exception:
614 self.module.fail_json(msg="Cannot load private key file '{private_key}'.".format_map(self.params))
615 if self.params.get("certificate_name") is None:
616 self.params["certificate_name"] = os.path.basename(os.path.splitext(self.params.get("private_key"))[0])
617 else:
618 self.module.fail_json(
619 msg="Provided private key {private_key} does not appear to be a private key or provided file does not exist.".format_map(self.params)
620 )
621
622 if self.params.get("certificate_name") is None:
623 self.params["certificate_name"] = "admin" if self.params.get("username") is None else self.params.get("username")
624 # NOTE: ACI documentation incorrectly adds a space between method and path
625 sig_request = method + path + payload
626 if HAS_CRYPTOGRAPHY:
627 sig_signature = sig_key.sign(sig_request.encode(), padding.PKCS1v15(), hashes.SHA256())
628 else:
629 sig_signature = sign(sig_key, sig_request, "sha256")
630 sig_dn = "uni/userext/user-{username}/usercert-{certificate_name}".format_map(self.params)
631 self.headers["Cookie"] = (
632 "APIC-Certificate-Algorithm=v1.0; "
633 + "APIC-Certificate-DN={0}; ".format(sig_dn)
634 + "APIC-Certificate-Fingerprint=fingerprint; "
635 + "APIC-Request-Signature={0}".format(to_native(base64.b64encode(sig_signature)))
636 )
637
638 def response_json(self, rawoutput):
639 """Handle APIC JSON response output"""
640 try:
641 jsondata = json.loads(rawoutput)
642 except Exception as e:
643 # Expose RAW output for troubleshooting
644 self.error = dict(code=-1, text="Unable to parse output as JSON, see 'raw' output. {0}".format(e))
645 self.result["raw"] = rawoutput
646 return
647
648 # Extract JSON API output
649 if isinstance(jsondata, list):
650 self.imdata = jsondata
651 self.totalCount = len(jsondata)
652 else:
653 self.imdata = jsondata.get("imdata", {})
654 total_count = jsondata.get("totalCount")
655 if total_count is not None:
656 self.totalCount = int(total_count)
657
658 # Handle possible APIC error information
659 self.response_error()
660
661 def response_xml(self, rawoutput):
662 """Handle APIC XML response output"""
663
664 # NOTE: The XML-to-JSON conversion is using the "Cobra" convention
665 try:
666 xml = lxml.etree.fromstring(to_bytes(rawoutput))
667 xmldata = cobra.data(xml)
668 except Exception as e:
669 # Expose RAW output for troubleshooting
670 self.error = dict(code=-1, text="Unable to parse output as XML, see 'raw' output. {0}".format(e))
671 self.result["raw"] = rawoutput
672 return
673
674 # Reformat as ACI does for JSON API output
675 self.imdata = xmldata.get("imdata", {}).get("children")
676 if self.imdata is None:
677 self.imdata = dict()
678 self.totalCount = int(xmldata.get("imdata", {}).get("attributes", {}).get("totalCount", -1))
679
680 # Handle possible APIC error information
681 self.response_error()
682
683 def response_error(self):
684 """Set error information when found"""
685
686 # Handle possible APIC error information
687 if self.totalCount != "0":
688 try:
689 self.error = self.imdata[0].get("error").get("attributes")
690 except (AttributeError, IndexError, KeyError):
691 pass
692
693 # TODO: This could be designed to update existing keys
694 def update_qs(self, params):
695 """Append key-value pairs to self.filter_string"""
696 accepted_params = dict((k, v) for (k, v) in params.items() if v is not None)
697 if accepted_params:
698 if self.filter_string:
699 self.filter_string += "&"
700 else:
701 self.filter_string = "?"
702 self.filter_string += "&".join(["%s=%s" % (k, v) for (k, v) in accepted_params.items()])
703
704 # TODO: This could be designed to accept multiple obj_classes and keys
705 def build_filter(self, obj_class, params):
706 """Build an APIC filter based on obj_class and key-value pairs"""
707 accepted_params = dict((k, v) for (k, v) in params.items() if v is not None)
708 if len(accepted_params) == 1:
709 return ",".join('eq({0}.{1},"{2}")'.format(obj_class, k, v) for (k, v) in accepted_params.items())
710 elif len(accepted_params) > 1:
711 return "and(" + ",".join(['eq({0}.{1},"{2}")'.format(obj_class, k, v) for (k, v) in accepted_params.items()]) + ")"
712
713 def _deep_url_path_builder(self, obj):
714 target_class = obj.get("target_class")
715 target_filter = obj.get("target_filter")
716 subtree_class = obj.get("subtree_class")
717 subtree_filter = obj.get("subtree_filter")
718 object_rn = obj.get("object_rn")
719 mo = obj.get("module_object")
720 add_subtree_filter = obj.get("add_subtree_filter")
721 add_target_filter = obj.get("add_target_filter")
722
723 if self.module.params.get("state") in ("absent", "present") and mo is not None:
724 self.path = "api/mo/uni/{0}.json".format(object_rn)
725 self.update_qs({"rsp-prop-include": "config-only"})
726
727 else:
728 # State is 'query'
729 if object_rn is not None:
730 # Query for a specific object in the module's class
731 self.path = "api/mo/uni/{0}.json".format(object_rn)
732 else:
733 self.path = "api/class/{0}.json".format(target_class)
734
735 if add_target_filter:
736 self.update_qs({"query-target-filter": self.build_filter(target_class, target_filter)})
737
738 if add_subtree_filter:
739 self.update_qs({"rsp-subtree-filter": self.build_filter(subtree_class, subtree_filter)})
740
741 if self.params.get("port") is not None:
742 self.url = "{protocol}://{host}:{port}/{path}".format(path=self.path, **self.module.params)
743
744 else:
745 self.url = "{protocol}://{host}/{path}".format(path=self.path, **self.module.params)
746
747 if self.child_classes:
748 self.update_qs(
749 {
750 "rsp-subtree": "full",
751 "rsp-subtree-class": ",".join(sorted(self.child_classes)),
752 }
753 )
754
755 def _deep_url_parent_object(self, parent_objects, parent_class):
756 for parent_object in parent_objects:
757 if parent_object.get("aci_class") is parent_class:
758 return parent_object
759
760 return None
761
762 def construct_deep_url(self, target_object, parent_objects=None, child_classes=None):
763 """
764 This method is used to retrieve the appropriate URL path and filter_string to make the request to the APIC.
765
766 :param target_object: The target class dictionary containing parent_class, aci_class, aci_rn, target_filter, and module_object keys.
767 :param parent_objects: The parent class list of dictionaries containing parent_class, aci_class, aci_rn, target_filter, and module_object keys.
768 :param child_classes: The list of child classes that the module supports along with the object.
769 :type target_object: dict
770 :type parent_objects: list[dict]
771 :type child_classes: list[string]
772 :return: The path and filter_string needed to build the full URL.
773 """
774
775 self.filter_string = ""
776 rn_builder = None
777 subtree_classes = None
778 add_subtree_filter = False
779 add_target_filter = False
780 has_target_query = False
781 has_target_query_compare = False
782 has_target_query_difference = False
783 has_target_query_called = False
784
785 if child_classes is None:
786 self.child_classes = set()
787 else:
788 self.child_classes = set(child_classes)
789
790 target_parent_class = target_object.get("parent_class")
791 target_class = target_object.get("aci_class")
792 target_rn = target_object.get("aci_rn")
793 target_filter = target_object.get("target_filter")
794 target_module_object = target_object.get("module_object")
795
796 url_path_object = dict(
797 target_class=target_class,
798 target_filter=target_filter,
799 subtree_class=target_class,
800 subtree_filter=target_filter,
801 module_object=target_module_object,
802 )
803
804 if target_module_object is not None:
805 rn_builder = target_rn
806 else:
807 has_target_query = True
808 has_target_query_compare = True
809
810 if parent_objects is not None:
811 current_parent_class = target_parent_class
812 has_parent_query_compare = False
813 has_parent_query_difference = False
814 is_first_parent = True
815 is_single_parent = None
816 search_classes = set()
817
818 while current_parent_class != "uni":
819 parent_object = self._deep_url_parent_object(parent_objects=parent_objects, parent_class=current_parent_class)
820
821 if parent_object is not None:
822 parent_parent_class = parent_object.get("parent_class")
823 parent_class = parent_object.get("aci_class")
824 parent_rn = parent_object.get("aci_rn")
825 parent_filter = parent_object.get("target_filter")
826 parent_module_object = parent_object.get("module_object")
827
828 if is_first_parent:
829 is_single_parent = True
830 else:
831 is_single_parent = False
832 is_first_parent = False
833
834 if parent_parent_class != "uni":
835 search_classes.add(parent_class)
836
837 if parent_module_object is not None:
838 if rn_builder is not None:
839 rn_builder = "{0}/{1}".format(parent_rn, rn_builder)
840 else:
841 rn_builder = parent_rn
842
843 url_path_object["target_class"] = parent_class
844 url_path_object["target_filter"] = parent_filter
845
846 has_target_query = False
847 else:
848 rn_builder = None
849 subtree_classes = search_classes
850
851 has_target_query = True
852 if is_single_parent:
853 has_parent_query_compare = True
854
855 current_parent_class = parent_parent_class
856 else:
857 raise ValueError("Reference error for parent_class '{0}'. Each parent_class must reference a valid object".format(current_parent_class))
858
859 if not has_target_query_difference and not has_target_query_called:
860 if has_target_query is not has_target_query_compare:
861 has_target_query_difference = True
862 else:
863 if not has_parent_query_difference and has_target_query is not has_parent_query_compare:
864 has_parent_query_difference = True
865 has_target_query_called = True
866
867 if not has_parent_query_difference and has_parent_query_compare and target_module_object is not None:
868 add_target_filter = True
869
870 elif has_parent_query_difference and target_module_object is not None:
871 add_subtree_filter = True
872 self.child_classes.add(target_class)
873
874 if has_target_query:
875 add_target_filter = True
876
877 elif has_parent_query_difference and not has_target_query and target_module_object is None:
878 self.child_classes.add(target_class)
879 self.child_classes.update(subtree_classes)
880
881 elif not has_parent_query_difference and not has_target_query and target_module_object is None:
882 self.child_classes.add(target_class)
883
884 elif not has_target_query and is_single_parent and target_module_object is None:
885 self.child_classes.add(target_class)
886
887 url_path_object["object_rn"] = rn_builder
888 url_path_object["add_subtree_filter"] = add_subtree_filter
889 url_path_object["add_target_filter"] = add_target_filter
890
891 self._deep_url_path_builder(url_path_object)
892
893 def construct_url(
894 self,
895 root_class,
896 subclass_1=None,
897 subclass_2=None,
898 subclass_3=None,
899 subclass_4=None,
900 subclass_5=None,
901 subclass_6=None,
902 child_classes=None,
903 config_only=True,
904 rsp_subtree="full",
905 ):
906 """
907 This method is used to retrieve the appropriate URL path and filter_string to make the request to the APIC.
908
909 :param root_class: The top-level class dictionary containing aci_class, aci_rn, target_filter, and module_object keys.
910 :param sublass_1: The second-level class dictionary containing aci_class, aci_rn, target_filter, and module_object keys.
911 :param sublass_2: The third-level class dictionary containing aci_class, aci_rn, target_filter, and module_object keys.
912 :param sublass_3: The fourth-level class dictionary containing aci_class, aci_rn, target_filter, and module_object keys.
913 :param child_classes: The list of child classes that the module supports along with the object.
914 :type root_class: dict
915 :type subclass_1: dict
916 :type subclass_2: dict
917 :type subclass_3: dict
918 :type subclass_4: dict
919 :type subclass_5: dict
920 :type subclass_6: dict
921 :type child_classes: list
922 :return: The path and filter_string needed to build the full URL.
923 """
924 self.filter_string = ""
925
926 if child_classes is None:
927 self.child_classes = set()
928 else:
929 self.child_classes = set(child_classes)
930
931 if subclass_6 is not None:
932 self._construct_url_7(root_class, subclass_1, subclass_2, subclass_3, subclass_4, subclass_5, subclass_6, config_only)
933 elif subclass_5 is not None:
934 self._construct_url_6(root_class, subclass_1, subclass_2, subclass_3, subclass_4, subclass_5, config_only)
935 elif subclass_4 is not None:
936 self._construct_url_5(root_class, subclass_1, subclass_2, subclass_3, subclass_4, config_only)
937 elif subclass_3 is not None:
938 self._construct_url_4(root_class, subclass_1, subclass_2, subclass_3, config_only)
939 elif subclass_2 is not None:
940 self._construct_url_3(root_class, subclass_1, subclass_2, config_only)
941 elif subclass_1 is not None:
942 self._construct_url_2(root_class, subclass_1, config_only)
943 else:
944 self._construct_url_1(root_class, config_only)
945
946 if self.params.get("port") is not None:
947 self.url = "{protocol}://{host}:{port}/{path}".format(path=self.path, **self.module.params)
948 else:
949 self.url = "{protocol}://{host}/{path}".format(path=self.path, **self.module.params)
950
951 if self.child_classes:
952 # Append child_classes to filter_string if filter string is empty
953 self.update_qs(
954 {
955 "rsp-subtree": rsp_subtree,
956 "rsp-subtree-class": ",".join(sorted(self.child_classes)),
957 }
958 )
959 elif rsp_subtree == "children":
960 self.update_qs({"rsp-subtree": rsp_subtree})
961
962 def _construct_url_1(self, obj, config_only=True):
963 """
964 This method is used by construct_url when the object is the top-level class.
965 """
966 obj_class = obj.get("aci_class")
967 obj_rn = obj.get("aci_rn")
968 obj_filter = obj.get("target_filter")
969 mo = obj.get("module_object")
970
971 if self.module.params.get("state") in ("absent", "present"):
972 # State is absent or present
973 self.path = "api/mo/uni/{0}.json".format(obj_rn)
974 self.parent_path = "api/mo/uni.json"
975 if config_only:
976 self.update_qs({"rsp-prop-include": "config-only"})
977 self.obj_filter = obj_filter
978 elif mo is None:
979 # Query for all objects of the module's class (filter by properties)
980 self.path = "api/class/{0}.json".format(obj_class)
981 if obj_filter is not None:
982 self.update_qs({"query-target-filter": self.build_filter(obj_class, obj_filter)})
983 else:
984 # Query for a specific object in the module's class
985 self.path = "api/mo/uni/{0}.json".format(obj_rn)
986
987 def _construct_url_2(self, parent, obj, config_only=True):
988 """
989 This method is used by construct_url when the object is the second-level class.
990 """
991 parent_rn = parent.get("aci_rn")
992 parent_obj = parent.get("module_object")
993 obj_class = obj.get("aci_class")
994 obj_rn = obj.get("aci_rn")
995 obj_filter = obj.get("target_filter")
996 mo = obj.get("module_object")
997
998 if self.module.params.get("state") in ("absent", "present"):
999 # State is absent or present
1000 self.path = "api/mo/uni/{0}/{1}.json".format(parent_rn, obj_rn)
1001 self.parent_path = "api/mo/uni/{0}.json".format(parent_rn)
1002 if config_only:
1003 self.update_qs({"rsp-prop-include": "config-only"})
1004 self.obj_filter = obj_filter
1005 elif parent_obj is None and mo is None:
1006 # Query for all objects of the module's class
1007 self.path = "api/class/{0}.json".format(obj_class)
1008 self.update_qs({"query-target-filter": self.build_filter(obj_class, obj_filter)})
1009 elif parent_obj is None: # mo is known
1010 # Query for all objects of the module's class that match the provided ID value
1011 self.path = "api/class/{0}.json".format(obj_class)
1012 self.update_qs({"query-target-filter": self.build_filter(obj_class, obj_filter)})
1013 elif mo is None: # parent_obj is known
1014 # Query for all object's of the module's class that belong to a specific parent object
1015 self.child_classes.add(obj_class)
1016 self.path = "api/mo/uni/{0}.json".format(parent_rn)
1017 else:
1018 # Query for specific object in the module's class
1019 self.path = "api/mo/uni/{0}/{1}.json".format(parent_rn, obj_rn)
1020
1021 def _construct_url_3(self, root, parent, obj, config_only=True):
1022 """
1023 This method is used by construct_url when the object is the third-level class.
1024 """
1025 root_rn = root.get("aci_rn")
1026 root_obj = root.get("module_object")
1027 parent_class = parent.get("aci_class")
1028 parent_rn = parent.get("aci_rn")
1029 parent_filter = parent.get("target_filter")
1030 parent_obj = parent.get("module_object")
1031 obj_class = obj.get("aci_class")
1032 obj_rn = obj.get("aci_rn")
1033 obj_filter = obj.get("target_filter")
1034 mo = obj.get("module_object")
1035
1036 if self.module.params.get("state") in ("absent", "present"):
1037 # State is absent or present
1038 self.path = "api/mo/uni/{0}/{1}/{2}.json".format(root_rn, parent_rn, obj_rn)
1039 self.parent_path = "api/mo/uni/{0}/{1}.json".format(root_rn, parent_rn)
1040 if config_only:
1041 self.update_qs({"rsp-prop-include": "config-only"})
1042 self.obj_filter = obj_filter
1043 elif root_obj is None and parent_obj is None and mo is None:
1044 # Query for all objects of the module's class
1045 self.path = "api/class/{0}.json".format(obj_class)
1046 self.update_qs({"query-target-filter": self.build_filter(obj_class, obj_filter)})
1047 elif root_obj is None and parent_obj is None: # mo is known
1048 # Query for all objects of the module's class matching the provided ID value of the object
1049 self.path = "api/class/{0}.json".format(obj_class)
1050 self.update_qs({"query-target-filter": self.build_filter(obj_class, obj_filter)})
1051 elif root_obj is None and mo is None: # parent_obj is known
1052 # Query for all objects of the module's class that belong to any parent class
1053 # matching the provided ID value for the parent object
1054 self.child_classes.add(obj_class)
1055 self.path = "api/class/{0}.json".format(parent_class)
1056 self.update_qs({"query-target-filter": self.build_filter(parent_class, parent_filter)})
1057 elif parent_obj is None and mo is None: # root_obj is known
1058 # Query for all objects of the module's class that belong to a specific root object
1059 self.child_classes.update([parent_class, obj_class])
1060 self.path = "api/mo/uni/{0}.json".format(root_rn)
1061 # NOTE: No need to select by root_filter
1062 # self.update_qs({'query-target-filter': self.build_filter(root_class, root_filter)})
1063 elif root_obj is None: # mo and parent_obj are known
1064 # Query for all objects of the module's class that belong to any parent class
1065 # matching the provided ID values for both object and parent object
1066 self.child_classes.add(obj_class)
1067 self.path = "api/class/{0}.json".format(parent_class)
1068 self.update_qs({"query-target-filter": self.build_filter(parent_class, parent_filter)})
1069 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1070 elif parent_obj is None: # mo and root_obj are known
1071 # Query for all objects of the module's class that match the provided ID value and belong to a specific root object
1072 self.child_classes.add(obj_class)
1073 self.path = "api/mo/uni/{0}.json".format(root_rn)
1074 # NOTE: No need to select by root_filter
1075 # self.update_qs({'query-target-filter': self.build_filter(root_class, root_filter)})
1076 # TODO: Filter by parent_filter and obj_filter
1077 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1078 elif mo is None: # root_obj and parent_obj are known
1079 # Query for all objects of the module's class that belong to a specific parent object
1080 self.child_classes.add(obj_class)
1081 self.path = "api/mo/uni/{0}/{1}.json".format(root_rn, parent_rn)
1082 # NOTE: No need to select by parent_filter
1083 # self.update_qs({'query-target-filter': self.build_filter(parent_class, parent_filter)})
1084 else:
1085 # Query for a specific object of the module's class
1086 self.path = "api/mo/uni/{0}/{1}/{2}.json".format(root_rn, parent_rn, obj_rn)
1087
1088 def _construct_url_4(self, root, sec, parent, obj, config_only=True):
1089 """
1090 This method is used by construct_url when the object is the fourth-level class.
1091 """
1092 root_rn = root.get("aci_rn")
1093 root_obj = root.get("module_object")
1094 sec_rn = sec.get("aci_rn")
1095 sec_obj = sec.get("module_object")
1096 parent_rn = parent.get("aci_rn")
1097 parent_obj = parent.get("module_object")
1098 obj_class = obj.get("aci_class")
1099 obj_rn = obj.get("aci_rn")
1100 obj_filter = obj.get("target_filter")
1101 mo = obj.get("module_object")
1102
1103 if self.child_classes is None:
1104 self.child_classes = [obj_class]
1105
1106 if self.module.params.get("state") in ("absent", "present"):
1107 # State is absent or present
1108 self.path = "api/mo/uni/{0}/{1}/{2}/{3}.json".format(root_rn, sec_rn, parent_rn, obj_rn)
1109 self.parent_path = "api/mo/uni/{0}/{1}/{2}.json".format(root_rn, sec_rn, parent_rn)
1110 if config_only:
1111 self.update_qs({"rsp-prop-include": "config-only"})
1112 self.obj_filter = obj_filter
1113 # TODO: Add all missing cases
1114 elif root_obj is None:
1115 self.child_classes.add(obj_class)
1116 self.path = "api/class/{0}.json".format(obj_class)
1117 self.update_qs({"query-target-filter": self.build_filter(obj_class, obj_filter)})
1118 elif sec_obj is None:
1119 self.child_classes.add(obj_class)
1120 self.path = "api/mo/uni/{0}.json".format(root_rn)
1121 # NOTE: No need to select by root_filter
1122 # self.update_qs({'query-target-filter': self.build_filter(root_class, root_filter)})
1123 # TODO: Filter by sec_filter, parent and obj_filter
1124 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1125 elif parent_obj is None:
1126 self.child_classes.add(obj_class)
1127 self.path = "api/mo/uni/{0}/{1}.json".format(root_rn, sec_rn)
1128 # NOTE: No need to select by sec_filter
1129 # self.update_qs({'query-target-filter': self.build_filter(sec_class, sec_filter)})
1130 # TODO: Filter by parent_filter and obj_filter
1131 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1132 elif mo is None:
1133 self.child_classes.add(obj_class)
1134 self.path = "api/mo/uni/{0}/{1}/{2}.json".format(root_rn, sec_rn, parent_rn)
1135 # NOTE: No need to select by parent_filter
1136 # self.update_qs({'query-target-filter': self.build_filter(parent_class, parent_filter)})
1137 else:
1138 # Query for a specific object of the module's class
1139 self.path = "api/mo/uni/{0}/{1}/{2}/{3}.json".format(root_rn, sec_rn, parent_rn, obj_rn)
1140
1141 def _construct_url_5(self, root, ter, sec, parent, obj, config_only=True):
1142 """
1143 This method is used by construct_url when the object is the fourth-level class.
1144 """
1145
1146 root_rn = root.get("aci_rn")
1147 root_obj = root.get("module_object")
1148 ter_rn = ter.get("aci_rn")
1149 ter_obj = ter.get("module_object")
1150 sec_rn = sec.get("aci_rn")
1151 sec_obj = sec.get("module_object")
1152 parent_rn = parent.get("aci_rn")
1153 parent_obj = parent.get("module_object")
1154 obj_class = obj.get("aci_class")
1155 obj_rn = obj.get("aci_rn")
1156 obj_filter = obj.get("target_filter")
1157 mo = obj.get("module_object")
1158
1159 if self.child_classes is None:
1160 self.child_classes = [obj_class]
1161
1162 if self.module.params.get("state") in ("absent", "present"):
1163 # State is absent or present
1164 self.path = "api/mo/uni/{0}/{1}/{2}/{3}/{4}.json".format(root_rn, ter_rn, sec_rn, parent_rn, obj_rn)
1165 self.parent_path = "api/mo/uni/{0}/{1}/{2}/{3}.json".format(root_rn, ter_rn, sec_rn, parent_rn)
1166 if config_only:
1167 self.update_qs({"rsp-prop-include": "config-only"})
1168 self.obj_filter = obj_filter
1169 # TODO: Add all missing cases
1170 elif root_obj is None:
1171 self.child_classes.add(obj_class)
1172 self.path = "api/class/{0}.json".format(obj_class)
1173 self.update_qs({"query-target-filter": self.build_filter(obj_class, obj_filter)})
1174 elif ter_obj is None:
1175 self.child_classes.add(obj_class)
1176 self.path = "api/mo/uni/{0}.json".format(root_rn)
1177 # NOTE: No need to select by root_filter
1178 # self.update_qs({'query-target-filter': self.build_filter(root_class, root_filter)})
1179 # TODO: Filter by ter_filter, parent and obj_filter
1180 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1181 elif sec_obj is None:
1182 self.child_classes.add(obj_class)
1183 self.path = "api/mo/uni/{0}/{1}.json".format(root_rn, ter_rn)
1184 # NOTE: No need to select by ter_filter
1185 # self.update_qs({'query-target-filter': self.build_filter(ter_class, ter_filter)})
1186 # TODO: Filter by sec_filter, parent and obj_filter
1187 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1188 elif parent_obj is None:
1189 self.child_classes.add(obj_class)
1190 self.path = "api/mo/uni/{0}/{1}/{2}.json".format(root_rn, ter_rn, sec_rn)
1191 # NOTE: No need to select by sec_filter
1192 # self.update_qs({'query-target-filter': self.build_filter(sec_class, sec_filter)})
1193 # TODO: Filter by parent_filter and obj_filter
1194 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1195 elif mo is None:
1196 self.child_classes.add(obj_class)
1197 self.path = "api/mo/uni/{0}/{1}/{2}/{3}.json".format(root_rn, ter_rn, sec_rn, parent_rn)
1198 # NOTE: No need to select by parent_filter
1199 # self.update_qs({'query-target-filter': self.build_filter(parent_class, parent_filter)})
1200 else:
1201 # Query for a specific object of the module's class
1202 self.path = "api/mo/uni/{0}/{1}/{2}/{3}/{4}.json".format(root_rn, ter_rn, sec_rn, parent_rn, obj_rn)
1203
1204 def _construct_url_6(self, root, quad, ter, sec, parent, obj, config_only=True):
1205 """
1206 This method is used by construct_url when the object is the fifth-level class.
1207 """
1208 root_rn = root.get("aci_rn")
1209 root_obj = root.get("module_object")
1210 quad_rn = quad.get("aci_rn")
1211 quad_obj = quad.get("module_object")
1212 ter_rn = ter.get("aci_rn")
1213 ter_obj = ter.get("module_object")
1214 sec_rn = sec.get("aci_rn")
1215 sec_obj = sec.get("module_object")
1216 parent_rn = parent.get("aci_rn")
1217 parent_obj = parent.get("module_object")
1218 obj_class = obj.get("aci_class")
1219 obj_rn = obj.get("aci_rn")
1220 obj_filter = obj.get("target_filter")
1221 mo = obj.get("module_object")
1222
1223 if self.child_classes is None:
1224 self.child_classes = [obj_class]
1225
1226 if self.module.params.get("state") in ("absent", "present"):
1227 # State is absent or present
1228 self.path = "api/mo/uni/{0}/{1}/{2}/{3}/{4}/{5}.json".format(root_rn, quad_rn, ter_rn, sec_rn, parent_rn, obj_rn)
1229 if config_only:
1230 self.update_qs({"rsp-prop-include": "config-only"})
1231 self.obj_filter = obj_filter
1232 # TODO: Add all missing cases
1233 elif root_obj is None:
1234 self.child_classes.add(obj_class)
1235 self.path = "api/class/{0}.json".format(obj_class)
1236 self.update_qs({"query-target-filter": self.build_filter(obj_class, obj_filter)})
1237 elif quad_obj is None:
1238 self.child_classes.add(obj_class)
1239 self.path = "api/mo/uni/{0}.json".format(root_rn)
1240 # NOTE: No need to select by root_filter
1241 # self.update_qs({'query-target-filter': self.build_filter(root_class, root_filter)})
1242 # TODO: Filter by quad_filter, parent and obj_filter
1243 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1244 elif ter_obj is None:
1245 self.child_classes.add(obj_class)
1246 self.path = "api/mo/uni/{0}/{1}.json".format(root_rn, quad_rn)
1247 # NOTE: No need to select by quad_filter
1248 # self.update_qs({'query-target-filter': self.build_filter(quad_class, quad_filter)})
1249 # TODO: Filter by ter_filter, parent and obj_filter
1250 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1251 elif sec_obj is None:
1252 self.child_classes.add(obj_class)
1253 self.path = "api/mo/uni/{0}/{1}/{2}.json".format(root_rn, quad_rn, ter_rn)
1254 # NOTE: No need to select by ter_filter
1255 # self.update_qs({'query-target-filter': self.build_filter(ter_class, ter_filter)})
1256 # TODO: Filter by sec_filter, parent and obj_filter
1257 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1258 elif parent_obj is None:
1259 self.child_classes.add(obj_class)
1260 self.path = "api/mo/uni/{0}/{1}/{2}/{3}.json".format(root_rn, quad_rn, ter_rn, sec_rn)
1261 # NOTE: No need to select by sec_filter
1262 # self.update_qs({'query-target-filter': self.build_filter(sec_class, sec_filter)})
1263 # TODO: Filter by parent_filter and obj_filter
1264 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1265 elif mo is None:
1266 self.child_classes.add(obj_class)
1267 self.path = "api/mo/uni/{0}/{1}/{2}/{3}/{4}.json".format(root_rn, quad_rn, ter_rn, sec_rn, parent_rn)
1268 # NOTE: No need to select by parent_filter
1269 # self.update_qs({'query-target-filter': self.build_filter(parent_class, parent_filter)})
1270 else:
1271 # Query for a specific object of the module's class
1272 self.path = "api/mo/uni/{0}/{1}/{2}/{3}/{4}/{5}.json".format(root_rn, quad_rn, ter_rn, sec_rn, parent_rn, obj_rn)
1273
1274 def _construct_url_7(self, root, quin, quad, ter, sec, parent, obj, config_only=True):
1275 """
1276 This method is used by construct_url when the object is the sixth-level class.
1277 """
1278 root_rn = root.get("aci_rn")
1279 root_obj = root.get("module_object")
1280 quin_rn = quin.get("aci_rn")
1281 quin_obj = quin.get("module_object")
1282 quad_rn = quad.get("aci_rn")
1283 quad_obj = quad.get("module_object")
1284 ter_rn = ter.get("aci_rn")
1285 ter_obj = ter.get("module_object")
1286 sec_rn = sec.get("aci_rn")
1287 sec_obj = sec.get("module_object")
1288 parent_rn = parent.get("aci_rn")
1289 parent_obj = parent.get("module_object")
1290 obj_class = obj.get("aci_class")
1291 obj_rn = obj.get("aci_rn")
1292 obj_filter = obj.get("target_filter")
1293 mo = obj.get("module_object")
1294
1295 if self.child_classes is None:
1296 self.child_classes = [obj_class]
1297
1298 if self.module.params.get("state") in ("absent", "present"):
1299 # State is absent or present
1300 self.path = "api/mo/uni/{0}/{1}/{2}/{3}/{4}/{5}/{6}.json".format(root_rn, quin_rn, quad_rn, ter_rn, sec_rn, parent_rn, obj_rn)
1301 if config_only:
1302 self.update_qs({"rsp-prop-include": "config-only"})
1303 self.obj_filter = obj_filter
1304 # TODO: Add all missing cases
1305 elif root_obj is None:
1306 self.child_classes.add(obj_class)
1307 self.path = "api/class/{0}.json".format(obj_class)
1308 self.update_qs({"query-target-filter": self.build_filter(obj_class, obj_filter)})
1309 elif quin_obj is None:
1310 self.child_classes.add(obj_class)
1311 self.path = "api/mo/uni/{0}.json".format(root_rn)
1312 # NOTE: No need to select by root_filter
1313 # self.update_qs({'query-target-filter': self.build_filter(root_class, root_filter)})
1314 # TODO: Filter by quin_filter, parent and obj_filter
1315 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1316 elif quad_obj is None:
1317 self.child_classes.add(obj_class)
1318 self.path = "api/mo/uni/{0}/{1}.json".format(root_rn, quin_rn)
1319 # NOTE: No need to select by root_filter
1320 # self.update_qs({'query-target-filter': self.build_filter(root_class, root_filter)})
1321 # TODO: Filter by quin_filter, parent and obj_filter
1322 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1323 elif ter_obj is None:
1324 self.child_classes.add(obj_class)
1325 self.path = "api/mo/uni/{0}/{1}/{2}.json".format(root_rn, quin_rn, quad_rn)
1326 # NOTE: No need to select by quad_filter
1327 # self.update_qs({'query-target-filter': self.build_filter(quin_class, quin_filter)})
1328 # TODO: Filter by ter_filter, parent and obj_filter
1329 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1330 elif sec_obj is None:
1331 self.child_classes.add(obj_class)
1332 self.path = "api/mo/uni/{0}/{1}/{2}/{3}.json".format(root_rn, quin_rn, quad_rn, ter_rn)
1333 # NOTE: No need to select by ter_filter
1334 # self.update_qs({'query-target-filter': self.build_filter(ter_class, ter_filter)})
1335 # TODO: Filter by sec_filter, parent and obj_filter
1336 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1337 elif parent_obj is None:
1338 self.child_classes.add(obj_class)
1339 self.path = "api/mo/uni/{0}/{1}/{2}/{3}/{4}.json".format(root_rn, quin_rn, quad_rn, ter_rn, sec_rn)
1340 # NOTE: No need to select by sec_filter
1341 # self.update_qs({'query-target-filter': self.build_filter(sec_class, sec_filter)})
1342 # TODO: Filter by parent_filter and obj_filter
1343 self.update_qs({"rsp-subtree-filter": self.build_filter(obj_class, obj_filter)})
1344 elif mo is None:
1345 self.child_classes.add(obj_class)
1346 self.path = "api/mo/uni/{0}/{1}/{2}/{3}/{4}/{5}.json".format(root_rn, quin_rn, quad_rn, ter_rn, sec_rn, parent_rn)
1347 # NOTE: No need to select by parent_filter
1348 # self.update_qs({'query-target-filter': self.build_filter(parent_class, parent_filter)})
1349 else:
1350 # Query for a specific object of the module's class
1351 self.path = "api/mo/uni/{0}/{1}/{2}/{3}/{4}/{5}/{6}.json".format(root_rn, quin_rn, quad_rn, ter_rn, sec_rn, parent_rn, obj_rn)
1352
1353 def delete_config(self):
1354 """
1355 This method is used to handle the logic when the modules state is equal to absent. The method only pushes a change if
1356 the object exists, and if check_mode is False. A successful change will mark the module as changed.
1357 """
1358 self.proposed = dict()
1359
1360 if not self.existing and not self.suppress_previous:
1361 return
1362 elif not self.module.check_mode:
1363 # Sign and encode request as to APIC's wishes
1364 self.api_call("DELETE", self.url, None, return_response=False)
1365 else:
1366 self.result["changed"] = True
1367 self.method = "DELETE"
1368
1369 def get_diff(self, aci_class, required_properties=None):
1370 """
1371 This method is used to get the difference between the proposed and existing configurations. Each module
1372 should call the get_existing method before this method, and add the proposed config to the module results
1373 using the module's config parameters. The new config will added to the self.result dictionary.
1374 :param aci_class: Type str.
1375 This is the root dictionary key for the MO's configuration body, or the ACI class of the MO.
1376 """
1377 proposed_config = self.proposed[aci_class]["attributes"]
1378 if self.existing:
1379 existing_config = self.existing[0][aci_class]["attributes"]
1380 config = {}
1381
1382 # values are strings, so any diff between proposed and existing can be a straight replace
1383 for key, value in proposed_config.items():
1384 existing_field = existing_config.get(key)
1385 if value != existing_field:
1386 config[key] = value
1387
1388 # add name back to config only if the configs do not match
1389 if config:
1390 # TODO: If URLs are built with the object's name, then we should be able to leave off adding the name back
1391 if required_properties and isinstance(required_properties, dict):
1392 config.update(required_properties)
1393 config = {aci_class: {"attributes": config}}
1394
1395 # check for updates to child configs and update new config dictionary
1396 children = self.get_diff_children(aci_class)
1397
1398 if children and config:
1399 config[aci_class].update({"children": children})
1400 elif children:
1401 config = {aci_class: {"attributes": {}, "children": children}}
1402
1403 else:
1404 config = self.proposed
1405 self.config = config
1406
1407 @staticmethod
1408 def get_diff_child(child_class, proposed_child, existing_child):
1409 """
1410 This method is used to get the difference between a proposed and existing child configs. The get_nested_config()
1411 method should be used to return the proposed and existing config portions of child.
1412 :param child_class: Type str.
1413 The root class (dict key) for the child dictionary.
1414 :param proposed_child: Type dict.
1415 The config portion of the proposed child dictionary.
1416 :param existing_child: Type dict.
1417 The config portion of the existing child dictionary.
1418 :return: The child config with only values that are updated. If the proposed dictionary has no updates to make
1419 to what exists on the APIC, then None is returned.
1420 """
1421 update_config = {child_class: {"attributes": {}}}
1422 for key, value in proposed_child.items():
1423 existing_field = existing_child.get(key)
1424 if value != existing_field:
1425 update_config[child_class]["attributes"][key] = value
1426
1427 if not update_config[child_class]["attributes"]:
1428 return None
1429
1430 return update_config
1431
1432 def get_diff_children(self, aci_class, proposed_obj=None, existing_obj=None):
1433 """
1434 This method is used to retrieve the updated child configs by comparing the proposed children configs
1435 against the objects existing children configs.
1436 :param aci_class: Type str.
1437 This is the root dictionary key for the MO's configuration body, or the ACI class of the MO.
1438 :return: The list of updated child config dictionaries. None is returned if there are no changes to the child
1439 configurations.
1440 """
1441 if proposed_obj is None:
1442 proposed_children = self.proposed[aci_class].get("children")
1443 else:
1444 proposed_children = proposed_obj
1445
1446 if proposed_children:
1447 child_updates = []
1448 if existing_obj is None:
1449 existing_children = self.existing[0][aci_class].get("children", [])
1450 else:
1451 existing_children = existing_obj
1452
1453 # Loop through proposed child configs and compare against existing child configuration
1454 for child in proposed_children:
1455 child_class, proposed_child, existing_child = self.get_nested_config(child, existing_children)
1456 (
1457 proposed_child_children,
1458 existing_child_children,
1459 ) = self.get_nested_children(child, existing_children)
1460
1461 if existing_child is None:
1462 child_update = child
1463 else:
1464 child_update = self.get_diff_child(child_class, proposed_child, existing_child)
1465 if proposed_child_children:
1466 child_update_children = self.get_diff_children(aci_class, proposed_child_children, existing_child_children)
1467
1468 if child_update_children:
1469 child_update = child
1470
1471 # Update list of updated child configs only if the child config is different than what exists
1472 if child_update:
1473 child_updates.append(child_update)
1474 else:
1475 return None
1476
1477 return child_updates
1478
1479 def get_existing(self):
1480 """
1481 This method is used to get the existing object(s) based on the path specified in the module. Each module should
1482 build the URL so that if the object's name is supplied, then it will retrieve the configuration for that particular
1483 object, but if no name is supplied, then it will retrieve all MOs for the class. Following this method will ensure
1484 that this method can be used to supply the existing configuration when using the get_diff method. The response, status,
1485 and existing configuration will be added to the self.result dictionary.
1486 """
1487 if self.suppress_previous:
1488 self.existing = []
1489 return
1490
1491 uri = self.url + self.filter_string
1492 self.api_call("GET", uri, data=None, return_response=False)
1493
1494 def __get_existing_validation(self, changed):
1495 """
1496 This method is used to get the existing object(s) state after a config change has been completed.
1497 It will not get the object(s) state if there is no change or suppress_verification is enabled.
1498 When suppress_verification is enabled, the existing will be set to proposed if there was a change or suppress_previous is enabled.
1499 """
1500 if self.suppress_verification:
1501 if changed or self.suppress_previous:
1502 self.result["current_verified"] = False
1503 self.existing = [self.proposed] if self.proposed != {} else []
1504 else:
1505 # existing already equals the previous
1506 self.result["current_verified"] = True
1507 elif changed:
1508 uri = self.url + self.filter_string
1509 self.api_call("GET", uri, data=None, return_response=False)
1510
1511 @staticmethod
1512 def get_nested_config(proposed_child, existing_children):
1513 """
1514 This method is used for stiping off the outer layers of the child dictionaries so only the configuration
1515 key, value pairs are returned.
1516 :param proposed_child: Type dict.
1517 The dictionary that represents the child config.
1518 :param existing_children: Type list.
1519 The list of existing child config dictionaries.
1520 :return: The child's class as str (root config dict key), the child's proposed config dict, and the child's
1521 existing configuration dict.
1522 """
1523 for key in proposed_child.keys():
1524 child_class = key
1525 proposed_config = proposed_child[key]["attributes"]
1526 existing_config = None
1527
1528 # FIXME: Design causes issues for repeated child_classes
1529 # get existing dictionary from the list of existing to use for comparison
1530 for child in existing_children:
1531 if child.get(child_class):
1532 existing_config = child[key]["attributes"]
1533 # NOTE: This is an ugly fix
1534 # Return the one that is a subset match
1535 if set(proposed_config.items()).issubset(set(existing_config.items())):
1536 break
1537 existing_config = None
1538
1539 return child_class, proposed_config, existing_config
1540
1541 @staticmethod
1542 def get_nested_children(proposed_child, existing_children):
1543 """
1544 This method is used for stiping off the outer layers of the child dictionaries so only the children are returned.
1545 :param proposed_child: Type dict.
1546 The dictionary that represents the child config.
1547 :param existing_children: Type list.
1548 The list of existing child config dictionaries.
1549 :return: The child's class as str (root config dict key), the child's proposed children as a list and the child's
1550 existing children as a list.
1551 """
1552 for key in proposed_child.keys():
1553 child_class = key
1554 proposed_config = proposed_child[key]["attributes"]
1555 existing_config = None
1556 proposed_children = proposed_child[key].get("children")
1557 existing_child_children = None
1558
1559 # FIXME: Design causes issues for repeated child_classes
1560 # get existing dictionary from the list of existing to use for comparison
1561 for child in existing_children:
1562 if child.get(child_class):
1563 existing_config = child[key]["attributes"]
1564 existing_child_children = child[key].get("children")
1565 # NOTE: This is an ugly fix
1566 # Return the one that is a subset match
1567 if set(proposed_config.items()).issubset(set(existing_config.items())):
1568 break
1569 existing_child_children = None
1570 existing_config = None
1571
1572 return proposed_children, existing_child_children
1573
1574 def payload(self, aci_class, class_config, child_configs=None):
1575 """
1576 This method is used to dynamically build the proposed configuration dictionary from the config related parameters
1577 passed into the module. All values that were not passed values from the playbook task will be removed so as to not
1578 inadvertently change configurations.
1579 :param aci_class: Type str
1580 This is the root dictionary key for the MO's configuration body, or the ACI class of the MO.
1581 :param class_config: Type dict
1582 This is the configuration of the MO using the dictionary keys expected by the API
1583 :param child_configs: Type list
1584 This is a list of child dictionaries associated with the MOs config. The list should only
1585 include child objects that are used to associate two MOs together. Children that represent
1586 MOs should have their own module.
1587 """
1588 proposed = dict((k, str(v)) for k, v in class_config.items() if v is not None)
1589 if self.params.get("annotation") is not None:
1590 proposed["annotation"] = self.params.get("annotation")
1591 if self.params.get("owner_key") is not None:
1592 proposed["ownerKey"] = self.params.get("owner_key")
1593 if self.params.get("owner_tag") is not None:
1594 proposed["ownerTag"] = self.params.get("owner_tag")
1595 self.proposed = {aci_class: {"attributes": proposed}}
1596
1597 # add child objects to proposed
1598 if child_configs:
1599 children = self.handle_child_configs(child_configs)
1600
1601 if children:
1602 self.proposed[aci_class].update(dict(children=children))
1603
1604 def handle_child_configs(self, child_configs):
1605 children = []
1606 for child in child_configs:
1607 child_copy = deepcopy(child)
1608 has_value = False
1609 for class_name in child_copy.keys():
1610 for attribute, value in child_copy[class_name]["attributes"].items():
1611 if value is None:
1612 child[class_name]["attributes"].pop(attribute)
1613 else:
1614 child[class_name]["attributes"][attribute] = str(value)
1615 has_value = True
1616 if child_copy[class_name].get("children") is not None:
1617 has_value = True
1618 child[class_name]["children"] = self.handle_child_configs(child_copy[class_name]["children"])
1619 if has_value:
1620 children.append(child)
1621 return children
1622
1623 def post_config(self, parent_class=None):
1624 """
1625 This method is used to handle the logic when the modules state is equal to present. The method only pushes a change if
1626 the object has differences than what exists on the APIC, and if check_mode is False. A successful change will mark the
1627 module as changed.
1628 """
1629 if not self.config:
1630 return
1631 elif not self.module.check_mode:
1632 # Sign and encode request as to APIC's wishes
1633 url = self.url
1634 if parent_class is not None:
1635 if self.params.get("port") is not None:
1636 url = "{protocol}://{host}:{port}/{path}".format(path=self.parent_path, **self.module.params)
1637 else:
1638 url = "{protocol}://{host}/{path}".format(path=self.parent_path, **self.module.params)
1639 self.config = {parent_class: {"attributes": {}, "children": [self.config]}}
1640 self.api_call("POST", url, json.dumps(self.config), return_response=False)
1641 else:
1642 self.result["changed"] = True
1643 self.method = "POST"
1644
1645 def exit_json(self, filter_existing=None, **kwargs):
1646 """
1647 :param filter_existing: tuple consisting of the function at (index 0) and the args at (index 1)
1648 CAUTION: the function should always take in self.existing in its first parameter
1649 :param kwargs: kwargs to be passed to ansible module exit_json()
1650 filter_existing is not passed via kwargs since it cant handle function type and should not be exposed to user
1651 """
1652
1653 if "state" in self.params:
1654 if self.params.get("state") in ("absent", "present"):
1655 if self.params.get("output_level") in ("debug", "info"):
1656 self.result["previous"] = self.existing if not filter_existing else filter_existing[0](self.existing, filter_existing[1])
1657
1658 # Return the gory details when we need it
1659 if self.params.get("output_level") == "debug":
1660 if "state" in self.params:
1661 self.result["filter_string"] = self.filter_string
1662 self.result["method"] = self.method
1663 # self.result['path'] = self.path # Adding 'path' in result causes state: absent in output
1664 self.result["response"] = self.response
1665 self.result["status"] = self.status
1666 self.result["url"] = self.url
1667 if self.httpapi_logs is not None:
1668 self.result["httpapi_logs"] = self.httpapi_logs
1669 if self.stdout:
1670 self.result["stdout"] = self.stdout
1671
1672 if "state" in self.params:
1673 self.original = self.existing
1674 if self.params.get("state") in ("absent", "present"):
1675 self.__get_existing_validation(self.result["changed"])
1676
1677 # if self.module._diff and self.original != self.existing:
1678 # self.result['diff'] = dict(
1679 # before=json.dumps(self.original, sort_keys=True, indent=4),
1680 # after=json.dumps(self.existing, sort_keys=True, indent=4),
1681 # )
1682 self.result["current"] = self.existing if not filter_existing else filter_existing[0](self.existing, filter_existing[1])
1683
1684 if self.params.get("output_level") in ("debug", "info"):
1685 self.result["sent"] = self.config
1686 self.result["proposed"] = self.proposed
1687
1688 self.dump_json()
1689 self.result.update(**kwargs)
1690 self.module.exit_json(**self.result)
1691
1692 def fail_json(self, msg, **kwargs):
1693 # Return error information, if we have it
1694 if self.error.get("code") is not None and self.error.get("text") is not None:
1695 self.result["error"] = self.error
1696
1697 if self.stdout:
1698 self.result["stdout"] = self.stdout
1699
1700 if "state" in self.params:
1701 if self.params.get("state") in ("absent", "present"):
1702 if self.params.get("output_level") in ("debug", "info"):
1703 self.result["previous"] = self.existing
1704
1705 # Return the gory details when we need it
1706 if self.params.get("output_level") == "debug":
1707 if self.imdata is not None:
1708 self.result["imdata"] = self.imdata
1709 self.result["totalCount"] = self.totalCount
1710
1711 if self.params.get("output_level") == "debug":
1712 if self.url is not None:
1713 if "state" in self.params:
1714 self.result["filter_string"] = self.filter_string
1715 self.result["method"] = self.method
1716 # self.result['path'] = self.path # Adding 'path' in result causes state: absent in output
1717 self.result["response"] = self.response
1718 self.result["status"] = self.status
1719 self.result["url"] = self.url
1720 if self.httpapi_logs is not None:
1721 self.result["httpapi_logs"] = self.httpapi_logs
1722
1723 if "state" in self.params:
1724 if self.params.get("output_level") in ("debug", "info"):
1725 self.result["sent"] = self.config
1726 self.result["proposed"] = self.proposed
1727
1728 self.result.update(**kwargs)
1729 self.module.fail_json(msg=msg, **self.result)
1730
1731 def dump_json(self):
1732 if self.params.get("state") in ("absent", "present"):
1733 dn_path = self.url.rsplit("/mo/", maxsplit=1)[-1]
1734 if dn_path[-5:] == ".json":
1735 dn_path = dn_path[:-5]
1736 mo = {}
1737 if self.proposed:
1738 mo = self.proposed
1739 for aci_class in mo:
1740 mo[aci_class]["attributes"]["dn"] = dn_path
1741 if self.obj_filter is not None:
1742 if "tDn" in self.obj_filter:
1743 mo[aci_class]["attributes"]["tDn"] = self.obj_filter["tDn"]
1744
1745 elif self.params.get("state") == "absent" and self.existing:
1746 for aci_class in self.existing[0]:
1747 mo[aci_class] = dict(attributes=dict(dn=dn_path, status="deleted"))
1748
1749 self.result["mo"] = mo
1750 output_path = self.params.get("output_path")
1751 if output_path is not None:
1752 with open(output_path, "a") as output_file:
1753 if self.result.get("changed") is True:
1754 json.dump([mo], output_file)
1755
1756 def parsed_url_path(self, url):
1757 if not HAS_URLPARSE:
1758 self.fail_json(msg="urlparse is not installed")
1759 parse_result = urlparse(url)
1760 if parse_result.query == "":
1761 return parse_result.path
1762 else:
1763 return parse_result.path + "?" + parse_result.query
1764
1765 def api_call(self, method, url, data=None, return_response=False):
1766 resp = None
1767 if self.connection is not None:
1768 self.connection.set_params(self.params)
1769 info = self.connection.send_request(method, self.parsed_url_path(url), data)
1770 self.url = "{protocol}://{host}/{path}".format_map(integrate_url(info.get("url"), self.path))
1771 self.error = info.get("error")
1772 self.httpapi_logs.extend(self.connection.pop_messages())
1773 else:
1774 if self.params.get("private_key"):
1775 self.cert_auth(path=self.parsed_url_path(url), payload=data, method=method)
1776 resp, info = fetch_url(
1777 self.module,
1778 url,
1779 data=data,
1780 headers=self.headers,
1781 method=method,
1782 timeout=30 if self.params.get("timeout") is None else self.params.get("timeout"),
1783 use_proxy=True if self.params.get("use_proxy") is None else self.params.get("use_proxy"),
1784 )
1785
1786 self.response = info.get("msg")
1787 self.status = info.get("status")
1788 self.method = method
1789
1790 if return_response:
1791 return resp, info
1792 else:
1793 # Handle APIC response
1794 if info.get("status") == 200:
1795 if method == "POST" or method == "DELETE":
1796 self.result["changed"] = True
1797 try:
1798 if method == "GET":
1799 self.existing = json.loads(resp.read())["imdata"]
1800 else:
1801 self.response_json(resp.read())
1802 except AttributeError:
1803 if method == "GET":
1804 self.existing = json.loads(info.get("body"))["imdata"]
1805 else:
1806 self.response_json(info.get("body"))
1807 else:
1808 try:
1809 # APIC error
1810 self.response_json(info["body"])
1811 self.fail_json(msg="APIC Error {code}: {text}".format_map(self.error))
1812 except KeyError:
1813 # Connection error
1814 self.fail_json(msg="Connection failed for {url}. {msg}".format_map(info))