| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2018, Dag Wieers (@dagwieers) <[email protected]> |
| 4 |
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) |
| 5 |
|
| 6 |
from __future__ import absolute_import, division, print_function |
| 7 |
|
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
from copy import deepcopy |
| 11 |
import re |
| 12 |
import os |
| 13 |
import ast |
| 14 |
import datetime |
| 15 |
import shutil |
| 16 |
import tempfile |
| 17 |
from ansible.module_utils.basic import json |
| 18 |
from ansible.module_utils.basic import env_fallback |
| 19 |
from ansible.module_utils.six import PY3 |
| 20 |
from ansible.module_utils.six.moves import filterfalse |
| 21 |
from ansible.module_utils.six.moves.urllib.parse import urlencode, urljoin |
| 22 |
from ansible.module_utils.urls import fetch_url |
| 23 |
from ansible.module_utils._text import to_native, to_text |
| 24 |
from ansible.module_utils.connection import Connection |
| 25 |
from ansible_collections.cisco.mso.plugins.module_utils.constants import ( |
| 26 |
NDO_API_VERSION_PATH_FORMAT, |
| 27 |
AZURE_L4L7_CONNECTOR_TYPE_MAP, |
| 28 |
LISTENER_REDIRECT_CODE_MAP, |
| 29 |
LISTENER_CONTENT_TYPE_MAP, |
| 30 |
LISTENER_ACTION_TYPE_MAP, |
| 31 |
LISTENER_PROTOCOLS, |
| 32 |
) |
| 33 |
|
| 34 |
try: |
| 35 |
from requests_toolbelt.multipart.encoder import MultipartEncoder |
| 36 |
|
| 37 |
HAS_MULTIPART_ENCODER = True |
| 38 |
except ImportError: |
| 39 |
HAS_MULTIPART_ENCODER = False |
| 40 |
|
| 41 |
|
| 42 |
if PY3: |
| 43 |
|
| 44 |
def cmp(a, b): |
| 45 |
return (a > b) - (a < b) |
| 46 |
|
| 47 |
|
| 48 |
def issubset(subset, superset): |
| 49 |
"""Recurse through nested dictionary and compare entries""" |
| 50 |
|
| 51 |
# Both objects are the same object |
| 52 |
if subset is superset: |
| 53 |
return True |
| 54 |
|
| 55 |
# Both objects are identical |
| 56 |
if subset == superset: |
| 57 |
return True |
| 58 |
|
| 59 |
# Both objects have a different type |
| 60 |
if type(subset) is not type(superset): |
| 61 |
return False |
| 62 |
|
| 63 |
for key, value in subset.items(): |
| 64 |
# Ignore empty values |
| 65 |
if value is None: |
| 66 |
return True |
| 67 |
|
| 68 |
# Item from subset is missing from superset |
| 69 |
if key not in superset: |
| 70 |
return False |
| 71 |
|
| 72 |
# Item has different types in subset and superset |
| 73 |
if not isinstance(superset.get(key), type(value)): |
| 74 |
return False |
| 75 |
|
| 76 |
# Compare if item values are subset |
| 77 |
if isinstance(value, dict): |
| 78 |
if not issubset(superset.get(key), value): |
| 79 |
return False |
| 80 |
elif isinstance(value, list): |
| 81 |
try: |
| 82 |
# NOTE: Fails for lists of dicts |
| 83 |
if not set(value) <= set(superset.get(key)): |
| 84 |
return False |
| 85 |
except TypeError: |
| 86 |
# Fall back to exact comparison for lists of dicts |
| 87 |
diff = list(filterfalse(lambda i: i in value, superset.get(key))) + list(filterfalse(lambda j: j in superset.get(key), value)) |
| 88 |
if diff: |
| 89 |
return False |
| 90 |
elif isinstance(value, set): |
| 91 |
if not value <= superset.get(key): |
| 92 |
return False |
| 93 |
else: |
| 94 |
if not value == superset.get(key): |
| 95 |
return False |
| 96 |
|
| 97 |
return True |
| 98 |
|
| 99 |
|
| 100 |
def update_qs(params): |
| 101 |
"""Append key-value pairs to self.filter_string""" |
| 102 |
accepted_params = dict((k, v) for (k, v) in params.items() if v is not None) |
| 103 |
return "?" + urlencode(accepted_params) |
| 104 |
|
| 105 |
|
| 106 |
def mso_argument_spec(): |
| 107 |
return dict( |
| 108 |
host=dict(type="str", required=False, aliases=["hostname"], fallback=(env_fallback, ["MSO_HOST"])), |
| 109 |
port=dict(type="int", required=False, fallback=(env_fallback, ["MSO_PORT"])), |
| 110 |
username=dict(type="str", required=False, fallback=(env_fallback, ["MSO_USERNAME", "ANSIBLE_NET_USERNAME"])), |
| 111 |
password=dict(type="str", required=False, no_log=True, fallback=(env_fallback, ["MSO_PASSWORD", "ANSIBLE_NET_PASSWORD"])), |
| 112 |
output_level=dict(type="str", default="normal", choices=["debug", "info", "normal"], fallback=(env_fallback, ["MSO_OUTPUT_LEVEL"])), |
| 113 |
timeout=dict(type="int", fallback=(env_fallback, ["MSO_TIMEOUT"])), |
| 114 |
use_proxy=dict(type="bool", fallback=(env_fallback, ["MSO_USE_PROXY"])), |
| 115 |
use_ssl=dict(type="bool", fallback=(env_fallback, ["MSO_USE_SSL"])), |
| 116 |
validate_certs=dict(type="bool", fallback=(env_fallback, ["MSO_VALIDATE_CERTS"])), |
| 117 |
login_domain=dict(type="str", fallback=(env_fallback, ["MSO_LOGIN_DOMAIN"])), |
| 118 |
) |
| 119 |
|
| 120 |
|
| 121 |
def mso_reference_spec(): |
| 122 |
return dict( |
| 123 |
name=dict(type="str", required=True), |
| 124 |
schema=dict(type="str"), |
| 125 |
template=dict(type="str"), |
| 126 |
) |
| 127 |
|
| 128 |
|
| 129 |
def mso_l3out_reference_spec(): |
| 130 |
return dict( |
| 131 |
name=dict(type="str", required=True), |
| 132 |
schema=dict(type="str"), |
| 133 |
template=dict(type="str"), |
| 134 |
tenant=dict(type="str"), |
| 135 |
) |
| 136 |
|
| 137 |
|
| 138 |
def mso_epg_subnet_spec(): |
| 139 |
return dict( |
| 140 |
subnet=dict(type="str", required=True, aliases=["ip"]), |
| 141 |
description=dict(type="str"), |
| 142 |
scope=dict(type="str", default="private", choices=["private", "public"]), |
| 143 |
shared=dict(type="bool", default=False), |
| 144 |
no_default_gateway=dict(type="bool", default=False), |
| 145 |
) |
| 146 |
|
| 147 |
|
| 148 |
def mso_subnet_spec(): |
| 149 |
subnet_spec = mso_epg_subnet_spec() |
| 150 |
subnet_spec.update(dict(querier=dict(type="bool", default=False))) |
| 151 |
return subnet_spec |
| 152 |
|
| 153 |
|
| 154 |
def mso_bd_subnet_spec(): |
| 155 |
subnet_spec = mso_epg_subnet_spec() |
| 156 |
subnet_spec.update(dict(querier=dict(type="bool", default=False))) |
| 157 |
subnet_spec.update(dict(primary=dict(type="bool", default=False))) |
| 158 |
subnet_spec.update(dict(virtual=dict(type="bool", default=False))) |
| 159 |
return subnet_spec |
| 160 |
|
| 161 |
|
| 162 |
def mso_dhcp_spec(): |
| 163 |
return dict( |
| 164 |
dhcp_option_policy=dict(type="dict", options=mso_dhcp_option_spec()), |
| 165 |
name=dict(type="str", required=True), |
| 166 |
version=dict(type="int", required=True), |
| 167 |
) |
| 168 |
|
| 169 |
|
| 170 |
def mso_dhcp_option_spec(): |
| 171 |
return dict( |
| 172 |
name=dict(type="str", required=True), |
| 173 |
version=dict(type="int", required=True), |
| 174 |
) |
| 175 |
|
| 176 |
|
| 177 |
def mso_contractref_spec(): |
| 178 |
return dict( |
| 179 |
name=dict(type="str", required=True), |
| 180 |
schema=dict(type="str"), |
| 181 |
template=dict(type="str"), |
| 182 |
type=dict(type="str", required=True, choices=["consumer", "provider"]), |
| 183 |
) |
| 184 |
|
| 185 |
|
| 186 |
def mso_expression_spec(): |
| 187 |
return dict( |
| 188 |
type=dict(type="str", required=True, aliases=["tag"]), |
| 189 |
operator=dict(type="str", choices=["not_in", "in", "equals", "not_equals", "has_key", "does_not_have_key"], required=True), |
| 190 |
value=dict(type="str"), |
| 191 |
) |
| 192 |
|
| 193 |
|
| 194 |
def mso_expression_spec_ext_epg(): |
| 195 |
return dict( |
| 196 |
type=dict(type="str", choices=["ip_address"], required=True), |
| 197 |
operator=dict(type="str", choices=["equals"], required=True), |
| 198 |
value=dict(type="str", required=True), |
| 199 |
) |
| 200 |
|
| 201 |
|
| 202 |
def mso_hub_network_spec(): |
| 203 |
return dict( |
| 204 |
name=dict(type="str", required=True), |
| 205 |
tenant=dict(type="str", required=True), |
| 206 |
) |
| 207 |
|
| 208 |
|
| 209 |
def mso_object_migrate_spec(): |
| 210 |
return dict( |
| 211 |
epg=dict(type="str", required=True), |
| 212 |
anp=dict(type="str", required=True), |
| 213 |
) |
| 214 |
|
| 215 |
|
| 216 |
def mso_service_graph_node_spec(): |
| 217 |
return dict( |
| 218 |
type=dict(type="str", required=True), |
| 219 |
) |
| 220 |
|
| 221 |
|
| 222 |
def mso_service_graph_node_device_spec(): |
| 223 |
return dict( |
| 224 |
device_name=dict(type="str", aliases=["name"], required=True), |
| 225 |
provider_connector_type=dict(type="str", choices=list(AZURE_L4L7_CONNECTOR_TYPE_MAP.keys())), |
| 226 |
provider_interface=dict(type="str"), |
| 227 |
consumer_connector_type=dict(type="str", choices=["none", "redirect"]), |
| 228 |
consumer_interface=dict(type="str"), |
| 229 |
) |
| 230 |
|
| 231 |
|
| 232 |
def mso_service_graph_connector_spec(): |
| 233 |
return dict( |
| 234 |
provider=dict(type="str", required=True), |
| 235 |
consumer=dict(type="str", required=True), |
| 236 |
# Only connectorType bd with value "general" is supported for now thus fixed in code |
| 237 |
# when connectorType externalEpg is supported "route-peering" should be added |
| 238 |
# also change SERVICE_NODE_CONNECTOR_TYPE_MAP in constants.py |
| 239 |
# also verify if connector type is specific to provider or always same for both |
| 240 |
connector_object_type=dict(type="str", default="bd", choices=["bd"]), |
| 241 |
provider_schema=dict(type="str"), |
| 242 |
provider_template=dict(type="str"), |
| 243 |
consumer_schema=dict(type="str"), |
| 244 |
consumer_template=dict(type="str"), |
| 245 |
) |
| 246 |
|
| 247 |
|
| 248 |
def mso_site_anp_epg_bulk_staticport_spec(): |
| 249 |
return dict( |
| 250 |
type=dict(type="str", choices=["port", "vpc", "dpc"]), |
| 251 |
pod=dict(type="str"), # This parameter is not required for querying all objects |
| 252 |
leaf=dict(type="str"), # This parameter is not required for querying all objects |
| 253 |
fex=dict(type="str"), # This parameter is not required for querying all objects |
| 254 |
path=dict(type="str"), # This parameter is not required for querying all objects |
| 255 |
vlan=dict(type="int"), # This parameter is not required for querying all objects |
| 256 |
primary_micro_segment_vlan=dict(type="int"), # This parameter is not required for querying all objects |
| 257 |
deployment_immediacy=dict(type="str", choices=["immediate", "lazy"]), |
| 258 |
mode=dict(type="str", choices=["native", "regular", "untagged"]), |
| 259 |
) |
| 260 |
|
| 261 |
|
| 262 |
def ndo_remote_user_spec(): |
| 263 |
return dict( |
| 264 |
name=dict(type="str", required=True), |
| 265 |
login_domain=dict(type="str", required=True), |
| 266 |
) |
| 267 |
|
| 268 |
|
| 269 |
def ndo_bfd_multi_hop_settings_spec(): |
| 270 |
return dict( |
| 271 |
type="dict", |
| 272 |
options=dict( |
| 273 |
state=dict(type="str", choices=["enabled", "disabled"]), |
| 274 |
admin_state=dict(type="str", choices=["enabled", "disabled"]), |
| 275 |
detection_multiplier=dict(type="int"), |
| 276 |
min_receive_interval=dict(type="int"), # msec |
| 277 |
min_transmit_interval=dict(type="int"), # msec |
| 278 |
), |
| 279 |
) |
| 280 |
|
| 281 |
|
| 282 |
def ndo_template_object_spec(aliases=None): |
| 283 |
return dict( |
| 284 |
type="dict", |
| 285 |
options=dict( |
| 286 |
name=dict(type="str", aliases=aliases) if aliases else dict(type="str"), |
| 287 |
template=dict(type="str"), |
| 288 |
template_id=dict(type="str"), |
| 289 |
), |
| 290 |
required_by={ |
| 291 |
"template": "name", |
| 292 |
"template_id": "name", |
| 293 |
}, |
| 294 |
mutually_exclusive=[ |
| 295 |
["template", "template_id"], |
| 296 |
], |
| 297 |
) |
| 298 |
|
| 299 |
|
| 300 |
def ndo_l3out_ptp_spec(aliases=None): |
| 301 |
return dict( |
| 302 |
type="dict", |
| 303 |
options=dict( |
| 304 |
mode=dict(type="str", choices=["multicast_dynamic", "multicast_master", "unicast_master"]), |
| 305 |
source_address=dict(type="str"), |
| 306 |
unicast_destinations=dict(type="list", elements="str"), |
| 307 |
user_profile=dict( |
| 308 |
type="dict", |
| 309 |
options=dict( |
| 310 |
uuid=dict(type="str"), |
| 311 |
reference=dict( |
| 312 |
type="dict", |
| 313 |
aliases=["ref"], |
| 314 |
options=dict( |
| 315 |
name=dict(type="str", required=True), |
| 316 |
template=dict(type="str"), |
| 317 |
template_id=dict(type="str"), |
| 318 |
), |
| 319 |
required_one_of=[ |
| 320 |
["template", "template_id"], |
| 321 |
], |
| 322 |
mutually_exclusive=[ |
| 323 |
("template", "template_id"), |
| 324 |
], |
| 325 |
), |
| 326 |
), |
| 327 |
required_one_of=[ |
| 328 |
["reference", "uuid"], |
| 329 |
], |
| 330 |
mutually_exclusive=[ |
| 331 |
("reference", "uuid"), |
| 332 |
], |
| 333 |
), |
| 334 |
), |
| 335 |
) |
| 336 |
|
| 337 |
|
| 338 |
def ndo_l3out_virtual_port_channel_spec(side_b=True, secondary_address=False): |
| 339 |
virtual_port_channel_spec = dict( |
| 340 |
type="dict", |
| 341 |
aliases=["vpc"], |
| 342 |
options=dict( |
| 343 |
uuid=dict(type="str"), |
| 344 |
reference=dict( |
| 345 |
type="dict", |
| 346 |
aliases=["ref"], |
| 347 |
options=dict( |
| 348 |
name=dict(type="str", required=True), |
| 349 |
template=dict(type="str"), |
| 350 |
template_id=dict(type="str"), |
| 351 |
), |
| 352 |
required_one_of=[ |
| 353 |
["template", "template_id"], |
| 354 |
], |
| 355 |
mutually_exclusive=[ |
| 356 |
("template", "template_id"), |
| 357 |
], |
| 358 |
), |
| 359 |
), |
| 360 |
required_one_of=[ |
| 361 |
["reference", "uuid"], |
| 362 |
], |
| 363 |
mutually_exclusive=[ |
| 364 |
("reference", "uuid"), |
| 365 |
], |
| 366 |
) |
| 367 |
|
| 368 |
if side_b: |
| 369 |
virtual_port_channel_spec["options"]["side_b_ipv4_address"] = dict(type="str") |
| 370 |
virtual_port_channel_spec["options"]["side_b_ipv6_address"] = dict(type="str") |
| 371 |
virtual_port_channel_spec["options"]["side_b_ipv6_link_local_address"] = dict(type="str") |
| 372 |
virtual_port_channel_spec["options"]["side_b_ipv6_dad"] = dict(type="str", choices=["enabled", "disabled"]) |
| 373 |
virtual_port_channel_spec["options"]["side_b_node_group_policy"] = dict(type="str") |
| 374 |
virtual_port_channel_spec["options"]["side_b_node_router_id"] = dict(type="str", aliases=["router_id"]) |
| 375 |
virtual_port_channel_spec["options"]["side_b_use_router_id_as_loopback"] = dict(type="bool") |
| 376 |
virtual_port_channel_spec["options"]["side_b_node_loopback_ip"] = dict(type="str", aliases=["loopback_ip"]) |
| 377 |
if secondary_address: |
| 378 |
# enforcing default for clarity of module behaviour, this value is not send to API but is just for calculation of VPC path |
| 379 |
virtual_port_channel_spec["options"]["side_b"] = dict(type="bool", default=False) |
| 380 |
|
| 381 |
return virtual_port_channel_spec |
| 382 |
|
| 383 |
|
| 384 |
def ndo_l3out_port_channel_spec(micro_bfd=True): |
| 385 |
port_channel_spec = dict( |
| 386 |
type="dict", |
| 387 |
aliases=["pc"], |
| 388 |
options=dict( |
| 389 |
uuid=dict(type="str"), |
| 390 |
reference=dict( |
| 391 |
type="dict", |
| 392 |
aliases=["ref"], |
| 393 |
options=dict( |
| 394 |
name=dict(type="str", required=True), |
| 395 |
template=dict(type="str"), |
| 396 |
template_id=dict(type="str"), |
| 397 |
), |
| 398 |
required_one_of=[ |
| 399 |
["template", "template_id"], |
| 400 |
], |
| 401 |
mutually_exclusive=[ |
| 402 |
("template", "template_id"), |
| 403 |
], |
| 404 |
), |
| 405 |
), |
| 406 |
required_one_of=[ |
| 407 |
["reference", "uuid"], |
| 408 |
], |
| 409 |
mutually_exclusive=[ |
| 410 |
("reference", "uuid"), |
| 411 |
], |
| 412 |
) |
| 413 |
|
| 414 |
if micro_bfd: |
| 415 |
port_channel_spec["options"]["micro_bfd_enabled"] = dict(type="bool") |
| 416 |
port_channel_spec["options"]["micro_bfd_address"] = dict(type="str") |
| 417 |
port_channel_spec["options"]["micro_bfd_start_timer"] = dict(type="int") |
| 418 |
|
| 419 |
return port_channel_spec |
| 420 |
|
| 421 |
|
| 422 |
def ndo_schema_template_object_references_spec(aliases=None): |
| 423 |
schema_template_object_references_spec = dict( |
| 424 |
type="dict", |
| 425 |
options=dict( |
| 426 |
uuid=dict(type="str"), |
| 427 |
reference=dict( |
| 428 |
type="dict", |
| 429 |
options=dict( |
| 430 |
name=dict(type="str", required=True), |
| 431 |
schema=dict(type="str"), |
| 432 |
schema_id=dict(type="str"), |
| 433 |
template=dict(type="str"), |
| 434 |
template_id=dict(type="str"), |
| 435 |
), |
| 436 |
required_one_of=[ |
| 437 |
("schema", "schema_id"), |
| 438 |
("template", "template_id"), |
| 439 |
], |
| 440 |
mutually_exclusive=[ |
| 441 |
("schema", "schema_id"), |
| 442 |
("template", "template_id"), |
| 443 |
], |
| 444 |
aliases=["ref"], |
| 445 |
), |
| 446 |
), |
| 447 |
required_one_of=[ |
| 448 |
("reference", "uuid"), |
| 449 |
], |
| 450 |
mutually_exclusive=[ |
| 451 |
("reference", "uuid"), |
| 452 |
], |
| 453 |
) |
| 454 |
|
| 455 |
if aliases and isinstance(aliases, list): |
| 456 |
schema_template_object_references_spec["aliases"] = aliases |
| 457 |
|
| 458 |
return schema_template_object_references_spec |
| 459 |
|
| 460 |
|
| 461 |
def ndo_tags_annotations_spec(aliases=None): |
| 462 |
tags_annotations_spec = dict( |
| 463 |
type="list", |
| 464 |
elements="dict", |
| 465 |
options=dict( |
| 466 |
key=dict(type="str", no_log=False), |
| 467 |
value=dict(type="str"), |
| 468 |
), |
| 469 |
) |
| 470 |
|
| 471 |
if aliases and isinstance(aliases, list): |
| 472 |
tags_annotations_spec["aliases"] = aliases |
| 473 |
|
| 474 |
return tags_annotations_spec |
| 475 |
|
| 476 |
|
| 477 |
# Copied from ansible's module uri.py (url): https://github.com/ansible/ansible/blob/cdf62edc65f564fff6b7e575e084026fa7faa409/lib/ansible/modules/uri.py |
| 478 |
def write_file(module, url, dest, content, resp, tmpsrc=None): |
| 479 |
# create a tempfile with some test content |
| 480 |
|
| 481 |
if tmpsrc is None and content is not None: |
| 482 |
fd, tmpsrc = tempfile.mkstemp(dir=module.tmpdir) |
| 483 |
f = open(tmpsrc, "wb") |
| 484 |
try: |
| 485 |
f.write(content) |
| 486 |
except Exception as e: |
| 487 |
os.remove(tmpsrc) |
| 488 |
module.fail_json(msg="Failed to create temporary content file: {0}".format(to_native(e))) |
| 489 |
f.close() |
| 490 |
|
| 491 |
checksum_src = None |
| 492 |
checksum_dest = None |
| 493 |
|
| 494 |
# raise an error if there is no tmpsrc file |
| 495 |
if not os.path.exists(tmpsrc): |
| 496 |
os.remove(tmpsrc) |
| 497 |
module.fail_json(msg="Source '{0}' does not exist".format(tmpsrc)) |
| 498 |
if not os.access(tmpsrc, os.R_OK): |
| 499 |
os.remove(tmpsrc) |
| 500 |
module.fail_json(msg="Source '{0}' is not readable".format(tmpsrc)) |
| 501 |
checksum_src = module.sha1(tmpsrc) |
| 502 |
|
| 503 |
# check if there is no dest file |
| 504 |
if os.path.exists(dest): |
| 505 |
# raise an error if copy has no permission on dest |
| 506 |
if not os.access(dest, os.W_OK): |
| 507 |
os.remove(tmpsrc) |
| 508 |
module.fail_json(msg="Destination '{0}' not writable".format(dest)) |
| 509 |
if not os.access(dest, os.R_OK): |
| 510 |
os.remove(tmpsrc) |
| 511 |
module.fail_json(msg="Destination '{0}' not readable".format(dest)) |
| 512 |
checksum_dest = module.sha1(dest) |
| 513 |
else: |
| 514 |
if not os.access(os.path.dirname(dest), os.W_OK): |
| 515 |
os.remove(tmpsrc) |
| 516 |
module.fail_json(msg="Destination dir '{0}' not writable".format(os.path.dirname(dest))) |
| 517 |
|
| 518 |
if checksum_src != checksum_dest: |
| 519 |
try: |
| 520 |
shutil.copyfile(tmpsrc, dest) |
| 521 |
except Exception as e: |
| 522 |
os.remove(tmpsrc) |
| 523 |
module.fail_json(msg="failed to copy {0} to {1}: {2}".format(tmpsrc, dest, to_native(e))) |
| 524 |
|
| 525 |
os.remove(tmpsrc) |
| 526 |
|
| 527 |
|
| 528 |
def format_interface_descriptions(mso, interface_descriptions, node=None): |
| 529 |
if interface_descriptions: |
| 530 |
|
| 531 |
def format_range_interfaces(format_dict): |
| 532 |
ids = format_dict.get("interfaceID") |
| 533 |
if re.fullmatch(r"((\d+/)+\d+$)", ids): |
| 534 |
yield format_dict |
| 535 |
elif re.fullmatch(r"((\d+/)+\d+-\d+$)", ids): |
| 536 |
slots = ids.rsplit("/", 1)[0] |
| 537 |
range_start, range_stop = ids.rsplit("/", 1)[1].split("-") |
| 538 |
if int(range_stop) > int(range_start): |
| 539 |
for x in range(int(range_start), int(range_stop) + 1): |
| 540 |
copy_format_dict = deepcopy(format_dict) |
| 541 |
copy_format_dict.update(interfaceID="{0}/{1}".format(slots, x)) |
| 542 |
yield copy_format_dict |
| 543 |
else: |
| 544 |
mso.fail_json(msg="Range start is greater than or equal to range stop for range of IDs '{0}'".format(ids)) |
| 545 |
else: |
| 546 |
mso.fail_json(msg="Incorrect interface ID or range of IDs. Got '{0}'".format(ids)) |
| 547 |
|
| 548 |
return [ |
| 549 |
item |
| 550 |
for interface_description in interface_descriptions |
| 551 |
for item in format_range_interfaces( |
| 552 |
{ |
| 553 |
"nodeID": node if node is not None else interface_description.get("node"), |
| 554 |
"interfaceID": interface_description.get("interface_id", interface_description.get("interfaceID")), |
| 555 |
"description": interface_description.get("description"), |
| 556 |
} |
| 557 |
) |
| 558 |
] |
| 559 |
return [] |
| 560 |
|
| 561 |
|
| 562 |
class MSOModule(object): |
| 563 |
def __init__(self, module): |
| 564 |
self.module = module |
| 565 |
self.params = module.params |
| 566 |
self.result = dict(changed=False) |
| 567 |
self.headers = {"Content-Type": "text/json"} |
| 568 |
self.platform = "local" |
| 569 |
|
| 570 |
# normal output |
| 571 |
self.existing = dict() |
| 572 |
|
| 573 |
# mso_rest output |
| 574 |
self.jsondata = None |
| 575 |
self.error = dict(code=None, message=None, info=None) |
| 576 |
|
| 577 |
# info output |
| 578 |
self.previous = dict() |
| 579 |
self.proposed = dict() |
| 580 |
self.sent = dict() |
| 581 |
self.stdout = None |
| 582 |
self.patch_operation = None |
| 583 |
|
| 584 |
# debug output |
| 585 |
self.has_modified = False |
| 586 |
self.filter_string = "" |
| 587 |
self.method = None |
| 588 |
self.path = None |
| 589 |
self.response = None |
| 590 |
self.status = None |
| 591 |
self.url = None |
| 592 |
self.httpapi_logs = list() |
| 593 |
self.site_type = None # on-premise or cloud |
| 594 |
self.cloud_provider_type = None # aws or azure or gcp |
| 595 |
|
| 596 |
if self.module._debug: |
| 597 |
self.module.warn("Enable debug output because ANSIBLE_DEBUG was set.") |
| 598 |
self.params["output_level"] = "debug" |
| 599 |
|
| 600 |
if self.module._socket_path is None: |
| 601 |
if self.params.get("use_ssl") is None: |
| 602 |
self.params["use_ssl"] = True |
| 603 |
if self.params.get("use_proxy") is None: |
| 604 |
self.params["use_proxy"] = True |
| 605 |
if self.params.get("validate_certs") is None: |
| 606 |
self.params["validate_certs"] = True |
| 607 |
if self.params.get("timeout") is None: |
| 608 |
self.params["timeout"] = 30 |
| 609 |
|
| 610 |
# Ensure protocol is set |
| 611 |
self.params["protocol"] = "https" if self.params.get("use_ssl", True) else "http" |
| 612 |
|
| 613 |
# Set base_uri |
| 614 |
if self.params.get("port") is not None: |
| 615 |
self.base_only_uri = "{protocol}://{host}:{port}/".format(**self.params) |
| 616 |
self.baseuri = "{0}api/v1/".format(self.base_only_uri) |
| 617 |
else: |
| 618 |
self.base_only_uri = "{protocol}://{host}/".format(**self.params) |
| 619 |
self.baseuri = "{0}api/v1/".format(self.base_only_uri) |
| 620 |
|
| 621 |
if self.params.get("host") is None: |
| 622 |
self.fail_json(msg="Parameter 'host' is required when not using the HTTP API connection plugin") |
| 623 |
|
| 624 |
if self.params.get("password"): |
| 625 |
# Perform password-based authentication, log on using password |
| 626 |
self.login() |
| 627 |
else: |
| 628 |
self.fail_json(msg="Parameter 'password' is required for authentication") |
| 629 |
else: |
| 630 |
self.connection = Connection(self.module._socket_path) |
| 631 |
if self.connection.get_platform() == "cisco.nd": |
| 632 |
self.platform = "nd" |
| 633 |
elif self.connection.get_platform() == "cisco.mso": |
| 634 |
self.platform = "mso" |
| 635 |
else: |
| 636 |
self.fail_json(msg="Connection must be identified as platform 'cisco.nd' or 'cisco.mso'") |
| 637 |
|
| 638 |
def get_login_domain_id(self, domain): |
| 639 |
"""Get a domain and return its id""" |
| 640 |
if domain is None: |
| 641 |
return domain |
| 642 |
d = self.get_obj("auth/login-domains", key="domains", name=domain) |
| 643 |
if not d: |
| 644 |
self.fail_json(msg="Login domain '%s' is not a valid domain name." % domain) |
| 645 |
if "id" not in d: |
| 646 |
self.fail_json(msg="Login domain lookup failed for domain '%s': %s" % (domain, d)) |
| 647 |
return d["id"] |
| 648 |
|
| 649 |
def login(self): |
| 650 |
"""Log in to MSO""" |
| 651 |
|
| 652 |
# Perform login request |
| 653 |
if (self.params.get("login_domain") is not None) and (self.params.get("login_domain") != "Local"): |
| 654 |
domain_id = self.get_login_domain_id(self.params.get("login_domain")) |
| 655 |
payload = {"username": self.params.get("username", "admin"), "password": self.params.get("password"), "domainId": domain_id} |
| 656 |
else: |
| 657 |
payload = {"username": self.params.get("username", "admin"), "password": self.params.get("password")} |
| 658 |
self.url = urljoin(self.baseuri, "auth/login") |
| 659 |
resp, auth = fetch_url( |
| 660 |
self.module, |
| 661 |
self.url, |
| 662 |
data=json.dumps(payload), |
| 663 |
method="POST", |
| 664 |
headers=self.headers, |
| 665 |
timeout=self.params.get("timeout"), |
| 666 |
use_proxy=self.params.get("use_proxy"), |
| 667 |
) |
| 668 |
|
| 669 |
# Handle MSO response |
| 670 |
if auth.get("status") not in [200, 201]: |
| 671 |
self.response = auth.get("msg") |
| 672 |
self.status = auth.get("status") |
| 673 |
self.fail_json(msg="Authentication failed: {msg}".format(**auth)) |
| 674 |
|
| 675 |
payload = json.loads(resp.read()) |
| 676 |
|
| 677 |
self.headers["Authorization"] = "Bearer {token}".format(**payload) |
| 678 |
|
| 679 |
def response_json(self, rawoutput): |
| 680 |
"""Handle MSO JSON response output""" |
| 681 |
try: |
| 682 |
self.jsondata = json.loads(rawoutput) |
| 683 |
except Exception as e: |
| 684 |
# Expose RAW output for troubleshooting |
| 685 |
self.error = dict(code=-1, message="Unable to parse output as JSON, see 'raw' output. %s" % e) |
| 686 |
self.result["raw"] = rawoutput |
| 687 |
return |
| 688 |
|
| 689 |
# Handle possible MSO error information |
| 690 |
if self.status not in [200, 201, 202, 204]: |
| 691 |
self.error = self.jsondata |
| 692 |
|
| 693 |
def request_download(self, path, destination=None, method="GET", api_version="v1"): |
| 694 |
if self.platform != "nd": |
| 695 |
self.url = urljoin(self.baseuri, path) |
| 696 |
|
| 697 |
redirected = False |
| 698 |
redir_info = {} |
| 699 |
redirect = {} |
| 700 |
content = None |
| 701 |
data = None |
| 702 |
|
| 703 |
src = self.params.get("src") |
| 704 |
if src: |
| 705 |
try: |
| 706 |
self.headers.update({"Content-Length": os.stat(src).st_size}) |
| 707 |
data = open(src, "rb") |
| 708 |
except OSError: |
| 709 |
self.fail_json(msg="Unable to open source file %s" % src, elapsed=0) |
| 710 |
|
| 711 |
kwargs = {} |
| 712 |
if destination is not None and os.path.isdir(destination): |
| 713 |
# first check if we are redirected to a file download |
| 714 |
if self.platform == "nd": |
| 715 |
redir_info = self.connection.get_remote_file_io_stream( |
| 716 |
NDO_API_VERSION_PATH_FORMAT.format(api_version=api_version, path=path), self.module.tmpdir, method |
| 717 |
) |
| 718 |
# In place of Content-Disposition, NDO get_remote_file_io_stream returns content-disposition. |
| 719 |
content_disposition = redir_info.get("content-disposition") |
| 720 |
else: |
| 721 |
check, redir_info = fetch_url(self.module, self.url, headers=self.headers, method=method, timeout=self.params.get("timeout")) |
| 722 |
content_disposition = check.headers.get("Content-Disposition") |
| 723 |
|
| 724 |
if content_disposition: |
| 725 |
file_name = content_disposition.split("filename=")[1] |
| 726 |
else: |
| 727 |
self.fail_json(msg="Failed to fetch {0} backup information from MSO/NDO, response: {1}".format(self.params.get("backup"), redir_info)) |
| 728 |
|
| 729 |
# if we are redirected, update the url with the location header and update dest with the new url filename |
| 730 |
if redir_info["status"] in (301, 302, 303, 307): |
| 731 |
self.url = redir_info.get("location") |
| 732 |
redirected = True |
| 733 |
destination = os.path.join(destination, file_name) |
| 734 |
|
| 735 |
# if destination file already exist, only download if file newer |
| 736 |
if os.path.exists(destination): |
| 737 |
kwargs["last_mod_time"] = datetime.datetime.utcfromtimestamp(os.path.getmtime(destination)) |
| 738 |
|
| 739 |
if self.platform == "nd": |
| 740 |
if redir_info["status"] == 200 and redirected is False: |
| 741 |
info = redir_info |
| 742 |
else: |
| 743 |
info = self.connection.get_remote_file_io_stream("/mso/{0}".format(self.url.split("/mso/", 1)), self.module.tmpdir, method) |
| 744 |
else: |
| 745 |
resp, info = fetch_url( |
| 746 |
self.module, |
| 747 |
self.url, |
| 748 |
data=data, |
| 749 |
headers=self.headers, |
| 750 |
method=method, |
| 751 |
timeout=self.params.get("timeout"), |
| 752 |
unix_socket=self.params.get("unix_socket"), |
| 753 |
**kwargs |
| 754 |
) |
| 755 |
|
| 756 |
try: |
| 757 |
content = resp.read() |
| 758 |
except AttributeError: |
| 759 |
# there was no content, but the error read() may have been stored in the info as 'body' |
| 760 |
content = info.pop("body", "") |
| 761 |
|
| 762 |
if src: |
| 763 |
# Try to close the open file handle |
| 764 |
try: |
| 765 |
data.close() |
| 766 |
except Exception: |
| 767 |
pass |
| 768 |
|
| 769 |
redirect["redirected"] = redirected or info.get("url") != self.url |
| 770 |
redirect.update(redir_info) |
| 771 |
redirect.update(info) |
| 772 |
|
| 773 |
write_file(self.module, self.url, destination, content, redirect, info.get("tmpsrc")) |
| 774 |
|
| 775 |
return redirect, destination |
| 776 |
|
| 777 |
def request_upload(self, path, fields=None, method="POST", api_version="v1"): |
| 778 |
"""Generic HTTP MultiPart POST method for MSO uploads.""" |
| 779 |
self.path = path |
| 780 |
if self.platform != "nd": |
| 781 |
self.url = urljoin(self.baseuri, path) |
| 782 |
|
| 783 |
info = dict() |
| 784 |
|
| 785 |
if self.platform == "nd": |
| 786 |
try: |
| 787 |
if os.path.exists(self.params.get("backup")): |
| 788 |
info = self.connection.send_file_request( |
| 789 |
method, |
| 790 |
NDO_API_VERSION_PATH_FORMAT.format(api_version=api_version, path=path), |
| 791 |
file=self.params.get("backup"), |
| 792 |
remote_path=self.params.get("remote_path"), |
| 793 |
) |
| 794 |
else: |
| 795 |
self.fail_json(msg="Upload failed due to: No such file or directory, Backup file: '{0}'".format(self.params.get("backup"))) |
| 796 |
except Exception as error: |
| 797 |
self.fail_json("NDO upload failed due to: {0}".format(error)) |
| 798 |
else: |
| 799 |
if not HAS_MULTIPART_ENCODER: |
| 800 |
self.fail_json(msg="requests-toolbelt is required for the upload state of this module") |
| 801 |
|
| 802 |
mp_encoder = MultipartEncoder(fields=fields) |
| 803 |
self.headers["Content-Type"] = mp_encoder.content_type |
| 804 |
self.headers["Accept-Encoding"] = "gzip, deflate, br" |
| 805 |
|
| 806 |
resp, info = fetch_url( |
| 807 |
self.module, |
| 808 |
self.url, |
| 809 |
headers=self.headers, |
| 810 |
data=mp_encoder, |
| 811 |
method=method, |
| 812 |
timeout=self.params.get("timeout"), |
| 813 |
use_proxy=self.params.get("use_proxy"), |
| 814 |
) |
| 815 |
|
| 816 |
self.response = info.get("msg") |
| 817 |
self.status = info.get("status") |
| 818 |
|
| 819 |
# Get change status from HTTP headers |
| 820 |
if "modified" in info: |
| 821 |
self.has_modified = True |
| 822 |
if info.get("modified") == "false": |
| 823 |
self.result["changed"] = False |
| 824 |
elif info.get("modified") == "true": |
| 825 |
self.result["changed"] = True |
| 826 |
|
| 827 |
# 200: OK, 201: Created, 202: Accepted, 204: No Content |
| 828 |
if self.status in (200, 201, 202, 204): |
| 829 |
if self.platform == "nd": |
| 830 |
return info |
| 831 |
else: |
| 832 |
output = resp.read() |
| 833 |
if output: |
| 834 |
return json.loads(output) |
| 835 |
|
| 836 |
# 400: Bad Request, 401: Unauthorized, 403: Forbidden, |
| 837 |
# 405: Method Not Allowed, 406: Not Acceptable |
| 838 |
# 500: Internal Server Error, 501: Not Implemented |
| 839 |
elif self.status: |
| 840 |
if self.status >= 400: |
| 841 |
try: |
| 842 |
if self.platform == "nd": |
| 843 |
payload = info.get("body") |
| 844 |
else: |
| 845 |
payload = json.loads(resp.read()) |
| 846 |
except (ValueError, AttributeError): |
| 847 |
try: |
| 848 |
payload = json.loads(info.get("body")) |
| 849 |
except Exception: |
| 850 |
self.fail_json(msg="MSO Error:", info=info) |
| 851 |
if "code" in payload: |
| 852 |
self.fail_json(msg="MSO Error {code}: {message}".format(**payload), info=info, payload=payload) |
| 853 |
else: |
| 854 |
self.fail_json(msg="MSO Error:".format(**payload), info=info, payload=payload) |
| 855 |
else: |
| 856 |
self.fail_json(msg="Backup file upload failed due to: {0}".format(info)) |
| 857 |
return {} |
| 858 |
|
| 859 |
def request(self, path, method=None, data=None, qs=None, api_version="v1", ignore_errors=None): |
| 860 |
"""Generic HTTP method for MSO requests.""" |
| 861 |
self.path = path |
| 862 |
|
| 863 |
if method is not None: |
| 864 |
self.method = method |
| 865 |
|
| 866 |
# If we PATCH with empty operations, return |
| 867 |
if method == "PATCH" and not data: |
| 868 |
return {} |
| 869 |
else: |
| 870 |
self.patch_operation = data |
| 871 |
|
| 872 |
# if method in ['PATCH', 'PUT']: |
| 873 |
# if qs is not None: |
| 874 |
# qs['enableVersionCheck'] = 'true' |
| 875 |
# else: |
| 876 |
# qs = dict(enableVersionCheck='true') |
| 877 |
|
| 878 |
if method in ["PATCH"]: |
| 879 |
if qs is not None: |
| 880 |
qs["validate"] = "false" |
| 881 |
else: |
| 882 |
qs = dict(validate="false") |
| 883 |
|
| 884 |
resp = None |
| 885 |
if self.module._socket_path: |
| 886 |
self.connection.set_params(self.params) |
| 887 |
if api_version is not None: |
| 888 |
if self.platform == "nd": |
| 889 |
uri = NDO_API_VERSION_PATH_FORMAT.format(api_version=api_version, path=self.path) |
| 890 |
else: |
| 891 |
uri = "/api/{0}/{1}".format(api_version, self.path) |
| 892 |
else: |
| 893 |
uri = self.path |
| 894 |
|
| 895 |
if qs is not None: |
| 896 |
uri = uri + update_qs(qs) |
| 897 |
|
| 898 |
try: |
| 899 |
info = self.connection.send_request(method, uri, json.dumps(data)) |
| 900 |
self.url = info.get("url") |
| 901 |
self.httpapi_logs.extend(self.connection.pop_messages()) |
| 902 |
info.pop("date", None) |
| 903 |
except Exception as e: |
| 904 |
try: |
| 905 |
error_obj = json.loads(to_text(e)) |
| 906 |
except Exception: |
| 907 |
error_obj = dict( |
| 908 |
error=dict(code=-1, message="Unable to parse error output as JSON. Raw error message: {0}".format(e), exception=to_text(e)) |
| 909 |
) |
| 910 |
pass |
| 911 |
self.httpapi_logs.extend(self.connection.pop_messages()) |
| 912 |
self.fail_json(msg=error_obj["error"]["message"]) |
| 913 |
|
| 914 |
else: |
| 915 |
if api_version is not None: |
| 916 |
self.url = "{0}api/{1}/{2}".format(self.base_only_uri, api_version, self.path.lstrip("/")) |
| 917 |
else: |
| 918 |
self.url = "{0}{1}".format(self.base_only_uri, self.path.lstrip("/")) |
| 919 |
|
| 920 |
if qs is not None: |
| 921 |
self.url = self.url + update_qs(qs) |
| 922 |
resp, info = fetch_url( |
| 923 |
self.module, |
| 924 |
self.url, |
| 925 |
headers=self.headers, |
| 926 |
data=json.dumps(data), |
| 927 |
method=self.method, |
| 928 |
timeout=self.params.get("timeout"), |
| 929 |
use_proxy=self.params.get("use_proxy"), |
| 930 |
) |
| 931 |
|
| 932 |
self.response = info.get("msg") |
| 933 |
self.status = info.get("status", -1) |
| 934 |
|
| 935 |
# Get change status from HTTP headers |
| 936 |
if "modified" in info: |
| 937 |
self.has_modified = True |
| 938 |
if info.get("modified") == "false": |
| 939 |
self.result["changed"] = False |
| 940 |
elif info.get("modified") == "true": |
| 941 |
self.result["changed"] = True |
| 942 |
|
| 943 |
# 200: OK, 201: Created, 202: Accepted |
| 944 |
if self.status in (200, 201, 202): |
| 945 |
try: |
| 946 |
output = resp.read() |
| 947 |
if output: |
| 948 |
try: |
| 949 |
return json.loads(output) |
| 950 |
except Exception as e: |
| 951 |
self.error = dict(code=-1, message="Unable to parse output as JSON, see 'raw' output. {0}".format(e)) |
| 952 |
self.result["raw"] = output |
| 953 |
return |
| 954 |
except AttributeError: |
| 955 |
return info.get("body") |
| 956 |
|
| 957 |
# 204: No Content |
| 958 |
elif self.status == 204: |
| 959 |
return {} |
| 960 |
|
| 961 |
# 404: Not Found |
| 962 |
elif self.method == "DELETE" and self.status == 404: |
| 963 |
return {} |
| 964 |
|
| 965 |
# 400: Bad Request, 401: Unauthorized, 403: Forbidden, |
| 966 |
# 405: Method Not Allowed, 406: Not Acceptable |
| 967 |
# 500: Internal Server Error, 501: Not Implemented |
| 968 |
elif self.status >= 400: |
| 969 |
self.result["status"] = self.status |
| 970 |
body = info.get("body") |
| 971 |
if body is not None: |
| 972 |
try: |
| 973 |
if isinstance(body, dict): |
| 974 |
payload = body |
| 975 |
else: |
| 976 |
payload = json.loads(body) |
| 977 |
|
| 978 |
if ignore_errors: |
| 979 |
for error in ignore_errors: |
| 980 |
if error in payload.get("message", ""): |
| 981 |
return error |
| 982 |
except Exception as e: |
| 983 |
self.error = dict(code=-1, message="Unable to parse output as JSON, see 'raw' output. %s" % e) |
| 984 |
self.result["raw"] = body |
| 985 |
self.fail_json(msg="MSO Error:", data=data, info=info) |
| 986 |
self.error = payload |
| 987 |
if "code" in payload: |
| 988 |
self.fail_json(msg="MSO Error {code}: {message}".format(**payload), data=data, info=info, payload=payload) |
| 989 |
else: |
| 990 |
self.fail_json(msg="MSO Error:".format(**payload), data=data, info=info, payload=payload) |
| 991 |
else: |
| 992 |
# Connection error |
| 993 |
msg = "Connection failed for {0}. {1}".format(info.get("url"), info.get("msg")) |
| 994 |
self.error = msg |
| 995 |
self.fail_json(msg=msg) |
| 996 |
return {} |
| 997 |
|
| 998 |
def l3out_interface_request(self, mso_l3out_template, ops, ignore_errors, state, remove_operations): |
| 999 |
""" |
| 1000 |
Wrapper function to handle the L3Out interface requests and node error responses. |
| 1001 |
L3Out node configuration requires an interface to be present for that node. |
| 1002 |
When the response fails with an error that indicates the node configuration is invalid, this function will retry |
| 1003 |
the request including the removal node configuration. |
| 1004 |
The function will retry only once to avoid potential infinite loops. |
| 1005 |
:param mso_l3out_template: MSOTemplate instance for the L3Out template |
| 1006 |
:param ops: List of operations to send to the API |
| 1007 |
:param ignore_errors: List of error strings to ignore |
| 1008 |
:param state: Desired state of the L3Out interface (present, absent) |
| 1009 |
:param remove_operations: Dictionary of Remove Operations to remove the node configuration if the interface is absent |
| 1010 |
The key in this dictionary is set the error string that indicates which node configuration is invalid. |
| 1011 |
The value is set to the PATCH operation to remove the node configuration. |
| 1012 |
:return: Response from the MSO request |
| 1013 |
""" |
| 1014 |
|
| 1015 |
if state == "absent": |
| 1016 |
# When the last interface from a node is deleted the node configuration must also be removed |
| 1017 |
response = self.request(mso_l3out_template.template_path, method="PATCH", data=ops, ignore_errors=ignore_errors) |
| 1018 |
# When the response matches an error string from the ignore errors we need to remove the node configuration |
| 1019 |
if response in ignore_errors: |
| 1020 |
# Pop the operation from the remove_operations dictionary so it won't be used again |
| 1021 |
# For VPC configurations the remove operations could potentially be multiple |
| 1022 |
remove_op = remove_operations.pop(response) |
| 1023 |
# 1. Insert the remove operation at the beginning of the ops list when no node removal operation is present in ops |
| 1024 |
# 2. Insert the second node operation before the first node operation if index of the node is greater than the first node operation |
| 1025 |
# Example: if ops are: |
| 1026 |
# ["/l3outTemplate/l3outs/0/nodes/0", "/l3outTemplate/l3outs/0/sviInterfaces/0"] |
| 1027 |
# and the remove operation is: |
| 1028 |
# "/l3outTemplate/l3outs/0/nodes/1" |
| 1029 |
# then the ops will be updated to: |
| 1030 |
# ["/l3outTemplate/l3outs/0/nodes/1", "/l3outTemplate/l3outs/0/nodes/0", "/l3outTemplate/l3outs/0/sviInterfaces/0"] |
| 1031 |
# because "/l3outTemplate/l3outs/0/nodes/1" > "/l3outTemplate/l3outs/0/nodes/0" == True |
| 1032 |
# 3. Insert the second node operation after the first node operation if index of the node is smaller than the first node operation |
| 1033 |
# Example: if ops are: |
| 1034 |
# ["/l3outTemplate/l3outs/0/nodes/1", "/l3outTemplate/l3outs/0/sviInterfaces/0"] |
| 1035 |
# and the remove operation is: |
| 1036 |
# "/l3outTemplate/l3outs/0/nodes/0" |
| 1037 |
# then the ops will be updated to: |
| 1038 |
# ["/l3outTemplate/l3outs/0/nodes/1", "/l3outTemplate/l3outs/0/nodes/0", "/l3outTemplate/l3outs/0/sviInterfaces/0"] |
| 1039 |
# because "/l3outTemplate/l3outs/0/nodes/0" > "/l3outTemplate/l3outs/0/nodes/1" == False |
| 1040 |
# Scenario 3 is currently not possible because the API orders the node error by the node index. |
| 1041 |
# This logic is put into place in case the ordering of the nodes in the API changes in the future. |
| 1042 |
if len(ops) == 1 or remove_op.get("path", "") > ops[0].get("path", ""): |
| 1043 |
ops.insert(0, remove_op) |
| 1044 |
else: |
| 1045 |
ops.insert(1, remove_op) |
| 1046 |
|
| 1047 |
# Remove the error from the ignore_errors list so it won't be retried again |
| 1048 |
ignore_errors.remove(response) |
| 1049 |
|
| 1050 |
# Retry the request with the remove operation when there are still remove operations left |
| 1051 |
# If there are no remove operations left, the request will be executed without the remove operation |
| 1052 |
# and the response will be returned as is. |
| 1053 |
if len(remove_operations) != 0: |
| 1054 |
return self.l3out_interface_request(mso_l3out_template, ops, ignore_errors, state, remove_operations) |
| 1055 |
else: |
| 1056 |
return response |
| 1057 |
|
| 1058 |
return self.request(mso_l3out_template.template_path, method="PATCH", data=ops) |
| 1059 |
|
| 1060 |
def query_objs(self, path, key=None, api_version="v1", **kwargs): |
| 1061 |
"""Query the MSO REST API for objects in a path""" |
| 1062 |
found = [] |
| 1063 |
objs = self.request(path, api_version=api_version, method="GET") |
| 1064 |
|
| 1065 |
if not objs: |
| 1066 |
return found |
| 1067 |
|
| 1068 |
if key is None: |
| 1069 |
key = path |
| 1070 |
|
| 1071 |
if isinstance(objs, dict): |
| 1072 |
if key not in objs: |
| 1073 |
self.fail_json(msg="Key '{0}' missing from data".format(key), data=objs) |
| 1074 |
objs_list = objs.get(key) |
| 1075 |
else: |
| 1076 |
objs_list = objs |
| 1077 |
for obj in objs_list: |
| 1078 |
for kw_key, kw_value in kwargs.items(): |
| 1079 |
if kw_value is None: |
| 1080 |
continue |
| 1081 |
if isinstance(kw_value, dict): |
| 1082 |
obj_value = obj.get(kw_key) |
| 1083 |
if obj_value is not None and isinstance(obj_value, dict): |
| 1084 |
breakout = False |
| 1085 |
for kw_key_lvl2, kw_value_lvl2 in kw_value.items(): |
| 1086 |
if obj_value.get(kw_key_lvl2) != kw_value_lvl2: |
| 1087 |
breakout = True |
| 1088 |
break |
| 1089 |
if breakout: |
| 1090 |
break |
| 1091 |
else: |
| 1092 |
break |
| 1093 |
elif obj.get(kw_key) != kw_value: |
| 1094 |
break |
| 1095 |
else: |
| 1096 |
found.append(obj) |
| 1097 |
|
| 1098 |
return found |
| 1099 |
|
| 1100 |
def query_obj(self, path, api_version="v1", **kwargs): |
| 1101 |
"""Query the MSO REST API for the whole object at a path""" |
| 1102 |
obj = self.request(path, api_version=api_version, method="GET") |
| 1103 |
if obj == {}: |
| 1104 |
return {} |
| 1105 |
for kw_key, kw_value in kwargs.items(): |
| 1106 |
if kw_value is None: |
| 1107 |
continue |
| 1108 |
if isinstance(kw_value, dict): |
| 1109 |
obj_value = obj.get(kw_key) |
| 1110 |
if obj_value is not None and isinstance(obj_value, dict): |
| 1111 |
for kw_key_lvl2, kw_value_lvl2 in kw_value.items(): |
| 1112 |
if obj_value.get(kw_key_lvl2) != kw_value_lvl2: |
| 1113 |
return {} |
| 1114 |
elif obj.get(kw_key) != kw_value: |
| 1115 |
return {} |
| 1116 |
return obj |
| 1117 |
|
| 1118 |
def get_obj(self, path, api_version="v1", **kwargs): |
| 1119 |
"""Get a specific object from a set of MSO REST objects""" |
| 1120 |
objs = self.query_objs(path, api_version=api_version, **kwargs) |
| 1121 |
if len(objs) == 0: |
| 1122 |
return {} |
| 1123 |
if len(objs) > 1: |
| 1124 |
self.fail_json(msg="More than one object matches unique filter: {0}".format(kwargs)) |
| 1125 |
return objs[0] |
| 1126 |
|
| 1127 |
def lookup_schema(self, schema, ignore_not_found_error=False): |
| 1128 |
"""Look up schema and return its id""" |
| 1129 |
if schema is None: |
| 1130 |
return schema |
| 1131 |
|
| 1132 |
schema_summary = self.query_objs("schemas/list-identity", key="schemas", displayName=schema) |
| 1133 |
if not schema_summary and not ignore_not_found_error: |
| 1134 |
self.fail_json(msg="Provided schema '{0}' does not exist.".format(schema)) |
| 1135 |
elif (not schema_summary or not schema_summary[0].get("id")) and ignore_not_found_error: |
| 1136 |
self.module.warn("Provided schema '{0}' does not exist.".format(schema)) |
| 1137 |
return None |
| 1138 |
schema_id = schema_summary[0].get("id") |
| 1139 |
if not schema_id: |
| 1140 |
self.fail_json(msg="Schema lookup failed for schema '{0}': '{1}'".format(schema, schema_id)) |
| 1141 |
return schema_id |
| 1142 |
|
| 1143 |
def lookup_domain(self, domain, ignore_not_found_error=False): |
| 1144 |
"""Look up a domain and return its id""" |
| 1145 |
if domain is None: |
| 1146 |
return domain |
| 1147 |
|
| 1148 |
d = self.get_obj("auth/domains", key="domains", name=domain) |
| 1149 |
if not d and not ignore_not_found_error: |
| 1150 |
self.fail_json(msg="Domain '{0}' is not a valid domain name.".format(domain)) |
| 1151 |
elif (not d or "id" not in d) and ignore_not_found_error: |
| 1152 |
self.module.warn("Domain '{0}' is not a valid domain name.".format(domain)) |
| 1153 |
return None |
| 1154 |
if "id" not in d: |
| 1155 |
self.fail_json(msg="Domain lookup failed for domain '{0}': {1}".format(domain, d)) |
| 1156 |
return d.get("id") |
| 1157 |
|
| 1158 |
def lookup_roles(self, roles, ignore_not_found_error=False): |
| 1159 |
"""Look up roles and return their ids""" |
| 1160 |
if roles is None: |
| 1161 |
return roles |
| 1162 |
|
| 1163 |
ids = [] |
| 1164 |
for role in roles: |
| 1165 |
access_type = "readWrite" |
| 1166 |
try: |
| 1167 |
role = ast.literal_eval(role) |
| 1168 |
if isinstance(role, dict) and "name" in role: |
| 1169 |
name = role.get("name") |
| 1170 |
if role.get("access_type") == "read": |
| 1171 |
access_type = "readOnly" |
| 1172 |
except ValueError: |
| 1173 |
name = role |
| 1174 |
|
| 1175 |
r = self.get_obj("roles", name=name) |
| 1176 |
if not r and not ignore_not_found_error: |
| 1177 |
self.fail_json(msg="Role '{0}' is not a valid role name.".format(name)) |
| 1178 |
elif (not r or "id" not in r) and ignore_not_found_error: |
| 1179 |
self.module.warn("Role '{0}' is not a valid role name.".format(name)) |
| 1180 |
return ids |
| 1181 |
if "id" not in r: |
| 1182 |
self.fail_json(msg="Role lookup failed for role '{0}': {1}".format(name, r)) |
| 1183 |
ids.append(dict(roleId=r.get("id"), accessType=access_type)) |
| 1184 |
return ids |
| 1185 |
|
| 1186 |
def lookup_site_type(self, site_data): |
| 1187 |
"""Get site type(AWS, AZURE or physical)""" |
| 1188 |
site_type = site_data.get("platform") |
| 1189 |
if site_type == "cloud": |
| 1190 |
self.cloud_provider_type = site_data.get("cloudProviders")[0] |
| 1191 |
self.site_type = site_type |
| 1192 |
|
| 1193 |
def lookup_site(self, site, ignore_not_found_error=False): |
| 1194 |
"""Look up a site and return its id""" |
| 1195 |
if site is None: |
| 1196 |
return site |
| 1197 |
|
| 1198 |
s = self.get_obj("sites", name=site) |
| 1199 |
if not s and not ignore_not_found_error: |
| 1200 |
self.fail_json(msg="Site '{0}' is not a valid site name.".format(site)) |
| 1201 |
elif (not s or "id" not in s) and ignore_not_found_error: |
| 1202 |
self.module.warn("Site '{0}' is not a valid site name.".format(site)) |
| 1203 |
return None |
| 1204 |
if "id" not in s: |
| 1205 |
self.fail_json(msg="Site lookup failed for site '{0}': {1}".format(site, s)) |
| 1206 |
|
| 1207 |
self.lookup_site_type(s) |
| 1208 |
return s.get("id") |
| 1209 |
|
| 1210 |
def lookup_sites(self, sites, ignore_not_found_error=False): |
| 1211 |
"""Look up sites and return their ids""" |
| 1212 |
if sites is None: |
| 1213 |
return sites |
| 1214 |
|
| 1215 |
ids = [] |
| 1216 |
for site in sites: |
| 1217 |
s = self.get_obj("sites", name=site) |
| 1218 |
if not s and not ignore_not_found_error: |
| 1219 |
self.fail_json(msg="Site '{0}' is not a valid site name.".format(site)) |
| 1220 |
elif (not s or "id" not in s) and ignore_not_found_error: |
| 1221 |
self.module.warn("Site '{0}' is not a valid site name.".format(site)) |
| 1222 |
return ids |
| 1223 |
if "id" not in s: |
| 1224 |
self.fail_json(msg="Site lookup failed for site '{0}': {1}".format(site, s)) |
| 1225 |
ids.append(dict(siteId=s.get("id"), securityDomains=[])) |
| 1226 |
return ids |
| 1227 |
|
| 1228 |
def lookup_tenant(self, tenant, ignore_not_found_error=False): |
| 1229 |
"""Look up a tenant and return its id""" |
| 1230 |
if tenant is None: |
| 1231 |
return tenant |
| 1232 |
|
| 1233 |
t = self.get_obj("tenants", key="tenants", name=tenant) |
| 1234 |
if not t and not ignore_not_found_error: |
| 1235 |
self.fail_json(msg="Tenant '{0}' is not valid tenant name.".format(tenant)) |
| 1236 |
elif (not t or "id" not in t) and ignore_not_found_error: |
| 1237 |
self.module.warn("Tenant '{0}' is not valid tenant name.".format(tenant)) |
| 1238 |
return None |
| 1239 |
if "id" not in t: |
| 1240 |
self.fail_json(msg="Tenant lookup failed for tenant '{0}': {1}".format(tenant, t)) |
| 1241 |
return t.get("id") |
| 1242 |
|
| 1243 |
def lookup_remote_location(self, remote_location, ignore_not_found_error=False): |
| 1244 |
"""Look up a remote location and return its path and id""" |
| 1245 |
if remote_location is None: |
| 1246 |
return None |
| 1247 |
|
| 1248 |
remote = self.get_obj("platform/remote-locations", key="remoteLocations", name=remote_location) |
| 1249 |
if "id" not in remote and not ignore_not_found_error: |
| 1250 |
self.fail_json(msg="No remote location found for remote '{0}'".format(remote_location)) |
| 1251 |
elif "id" not in remote and ignore_not_found_error: |
| 1252 |
self.module.warn("No remote location found for remote '{0}'".format(remote_location)) |
| 1253 |
return dict() |
| 1254 |
remote_info = dict(id=remote.get("id"), path=remote.get("credential")["remotePath"]) |
| 1255 |
return remote_info |
| 1256 |
|
| 1257 |
def lookup_users(self, users, ignore_not_found_error=False): |
| 1258 |
"""Look up users and return their ids""" |
| 1259 |
# Ensure tenant has at least admin user |
| 1260 |
if users is None: |
| 1261 |
users = ["admin"] |
| 1262 |
elif "admin" not in users: |
| 1263 |
users.append("admin") |
| 1264 |
|
| 1265 |
ids = [] |
| 1266 |
if self.platform == "nd": |
| 1267 |
remote_users = self.nd_request("/nexus/infra/api/aaa/v4/remoteusers", method="GET", ignore_not_found_error=True) |
| 1268 |
local_users = self.nd_request("/nexus/infra/api/aaa/v4/localusers", method="GET", ignore_not_found_error=True) |
| 1269 |
|
| 1270 |
# To handle the issue in ND 4.0 related to querying local and remote users, new API endpoints have been introduced. |
| 1271 |
# These endpoints should be removed once the official ND API endpoints become operational. |
| 1272 |
if remote_users == {} and local_users == {}: |
| 1273 |
remote_users = self.nd_request("/api/config/class/remoteusers", method="GET") |
| 1274 |
local_users = self.nd_request("/api/config/class/localusers", method="GET") |
| 1275 |
|
| 1276 |
for user in users: |
| 1277 |
user_dict = dict() |
| 1278 |
if self.platform == "nd": |
| 1279 |
user_dict = self.get_user_from_list_of_users(user, local_users) |
| 1280 |
if user_dict is None: |
| 1281 |
user_dict = self.get_user_from_list_of_users(user, remote_users) |
| 1282 |
else: |
| 1283 |
user_dict = self.get_obj("users", username=user) |
| 1284 |
if not user_dict and not ignore_not_found_error: |
| 1285 |
self.fail_json(msg="User '{0}' is not a valid user name.".format(user)) |
| 1286 |
elif (not user_dict or "id" not in user_dict) and ignore_not_found_error: |
| 1287 |
self.module.warn("User '{0}' is not a valid user name.".format(user)) |
| 1288 |
return ids |
| 1289 |
if "id" not in user_dict: |
| 1290 |
if "userID" not in user_dict: |
| 1291 |
self.fail_json(msg="User lookup failed for user '{0}': {1}".format(user, user_dict)) |
| 1292 |
id = dict(userId=user_dict.get("userID")) |
| 1293 |
else: |
| 1294 |
id = dict(userId=user_dict.get("id")) |
| 1295 |
if id in ids: |
| 1296 |
self.fail_json(msg="User '{0}' is duplicate.".format(user)) |
| 1297 |
ids.append(id) |
| 1298 |
return ids |
| 1299 |
|
| 1300 |
def get_user_from_list_of_users(self, user_name, users, login_domain=""): |
| 1301 |
"""Get user from the ND users API response object""" |
| 1302 |
if isinstance(users, dict): |
| 1303 |
for user in users.get("items"): |
| 1304 |
if ( |
| 1305 |
user.get("spec") |
| 1306 |
and user.get("spec").get("loginID") == user_name |
| 1307 |
and ((login_domain == "" and user.get("spec").get("loginDomain") is None) or user.get("spec").get("loginDomain") == login_domain) |
| 1308 |
): |
| 1309 |
return user.get("spec") |
| 1310 |
else: |
| 1311 |
# Handling a list of user objects is a temporary workaround that should be removed. |
| 1312 |
# Once the ND official local and remote user API endpoints are operational. |
| 1313 |
for user in users: |
| 1314 |
if (user.get("loginid") == user_name or user.get("loginID") == user_name) and ( |
| 1315 |
(login_domain == "" and user.get("logindomain") is None) or user.get("logindomain") == login_domain |
| 1316 |
): |
| 1317 |
return user |
| 1318 |
return None |
| 1319 |
|
| 1320 |
def lookup_remote_users(self, remote_users, ignore_not_found_error=False): |
| 1321 |
ids = [] |
| 1322 |
if self.platform == "nd": |
| 1323 |
remote_users_data = self.nd_request("/nexus/infra/api/aaa/v4/remoteusers", method="GET", ignore_not_found_error=True) |
| 1324 |
|
| 1325 |
# To handle the issue in ND 4.0 related to querying local and remote users, new API endpoints have been introduced. |
| 1326 |
# These endpoints should be removed once the official ND API endpoints become operational. |
| 1327 |
if remote_users_data == {}: |
| 1328 |
remote_users_data = self.nd_request("/api/config/class/remoteusers", method="GET") |
| 1329 |
|
| 1330 |
for remote_user in remote_users: |
| 1331 |
user_dict = dict() |
| 1332 |
if self.platform == "nd": |
| 1333 |
user_dict = self.get_user_from_list_of_users(remote_user.get("name"), remote_users_data, remote_user.get("login_domain")) |
| 1334 |
if not user_dict and not ignore_not_found_error: |
| 1335 |
self.fail_json(msg="User '{0}' is not a valid user name.".format(remote_user.get("name"))) |
| 1336 |
elif (not user_dict or "id" not in user_dict) and ignore_not_found_error: |
| 1337 |
self.module.warn("User '{0}' is not a valid user name.".format(remote_user.get("name"))) |
| 1338 |
return ids |
| 1339 |
if "id" not in user_dict: |
| 1340 |
if "userID" not in user_dict: |
| 1341 |
self.fail_json(msg="User lookup failed for user '{0}': {1}".format(remote_user.get("name"), user_dict)) |
| 1342 |
id = dict(userId=user_dict.get("userID")) |
| 1343 |
else: |
| 1344 |
id = dict(userId=user_dict.get("id")) |
| 1345 |
if id in ids: |
| 1346 |
self.fail_json(msg="User '{0}' is duplicate.".format(remote_user.get("name"))) |
| 1347 |
ids.append(id) |
| 1348 |
return ids |
| 1349 |
|
| 1350 |
def create_label(self, label, label_type): |
| 1351 |
"""Create a new label""" |
| 1352 |
return self.request("labels", method="POST", data=dict(displayName=label, type=label_type)) |
| 1353 |
|
| 1354 |
def lookup_labels(self, labels, label_type, ignore_not_found_error=False): |
| 1355 |
"""Look up labels and return their ids (create if necessary)""" |
| 1356 |
if labels is None: |
| 1357 |
return None |
| 1358 |
|
| 1359 |
ids = [] |
| 1360 |
for label in labels: |
| 1361 |
label_obj = self.get_obj("labels", displayName=label) |
| 1362 |
if not label_obj: |
| 1363 |
label_obj = self.create_label(label, label_type) |
| 1364 |
if "id" not in label_obj and not ignore_not_found_error: |
| 1365 |
self.fail_json(msg="Label lookup failed for label '{0}': {1}".format(label, label_obj)) |
| 1366 |
elif "id" not in label_obj and ignore_not_found_error: |
| 1367 |
self.module.warn("Label lookup failed for label '{0}': {1}".format(label, label_obj)) |
| 1368 |
return ids |
| 1369 |
ids.append(label_obj.get("id")) |
| 1370 |
return ids |
| 1371 |
|
| 1372 |
def anp_ref(self, **data): |
| 1373 |
"""Create anpRef string""" |
| 1374 |
return "/schemas/{schema_id}/templates/{template}/anps/{anp}".format(**data) |
| 1375 |
|
| 1376 |
def epg_ref(self, **data): |
| 1377 |
"""Create epgRef string""" |
| 1378 |
return "/schemas/{schema_id}/templates/{template}/anps/{anp}/epgs/{epg}".format(**data) |
| 1379 |
|
| 1380 |
def bd_ref(self, **data): |
| 1381 |
"""Create bdRef string""" |
| 1382 |
return "/schemas/{schema_id}/templates/{template}/bds/{bd}".format(**data) |
| 1383 |
|
| 1384 |
def contract_ref(self, **data): |
| 1385 |
"""Create contractRef string""" |
| 1386 |
# Support the contract argspec |
| 1387 |
if "name" in data: |
| 1388 |
data["contract"] = data.get("name") |
| 1389 |
return "/schemas/{schema_id}/templates/{template}/contracts/{contract}".format(**data) |
| 1390 |
|
| 1391 |
def filter_ref(self, **data): |
| 1392 |
"""Create a filterRef string""" |
| 1393 |
return "/schemas/{schema_id}/templates/{template}/filters/{filter}".format(**data) |
| 1394 |
|
| 1395 |
def vrf_ref(self, **data): |
| 1396 |
"""Create vrfRef string""" |
| 1397 |
return "/schemas/{schema_id}/templates/{template}/vrfs/{vrf}".format(**data) |
| 1398 |
|
| 1399 |
def l3out_ref(self, **data): |
| 1400 |
"""Create l3outRef string""" |
| 1401 |
return "/schemas/{schema_id}/templates/{template}/l3outs/{l3out}".format(**data) |
| 1402 |
|
| 1403 |
def ext_epg_ref(self, **data): |
| 1404 |
"""Create extEpgRef string""" |
| 1405 |
return "/schemas/{schema_id}/templates/{template}/externalEpgs/{external_epg}".format(**data) |
| 1406 |
|
| 1407 |
def service_graph_ref(self, **data): |
| 1408 |
"""Create serviceGraphRef string""" |
| 1409 |
return "/schemas/{schema_id}/templates/{template}/serviceGraphs/{service_graph}".format(**data) |
| 1410 |
|
| 1411 |
def vrf_dict_from_ref(self, data): |
| 1412 |
vrf_ref_regex = re.compile(r"\/schemas\/(.*)\/templates\/(.*)\/vrfs\/(.*)") |
| 1413 |
vrf_dict = vrf_ref_regex.search(data) |
| 1414 |
return { |
| 1415 |
"vrfName": vrf_dict.group(3), |
| 1416 |
"schemaId": vrf_dict.group(1), |
| 1417 |
"templateName": vrf_dict.group(2), |
| 1418 |
} |
| 1419 |
|
| 1420 |
def dict_from_ref(self, data): |
| 1421 |
if data and data != "": |
| 1422 |
ref_regex = re.compile(r"\/schemas\/(.*)\/templates\/(.*?)\/(.*?)\/(.*)") |
| 1423 |
dic = ref_regex.search(data) |
| 1424 |
if dic is not None: |
| 1425 |
schema_id = dic.group(1) |
| 1426 |
template_name = dic.group(2) |
| 1427 |
category = dic.group(3) |
| 1428 |
name = dic.group(4) |
| 1429 |
uri_map = { |
| 1430 |
"vrfs": ["vrfName", "schemaId", "templateName"], |
| 1431 |
"bds": ["bdName", "schemaId", "templateName"], |
| 1432 |
"filters": ["filterName", "schemaId", "templateName"], |
| 1433 |
"contracts": ["contractName", "schemaId", "templateName"], |
| 1434 |
"l3outs": ["l3outName", "schemaId", "templateName"], |
| 1435 |
"anps": ["anpName", "schemaId", "templateName"], |
| 1436 |
"serviceGraphs": ["serviceGraphName", "schemaId", "templateName"], |
| 1437 |
"serviceNode": ["serviceNodeName", "schemaId", "templateName", "serviceGraphName"], |
| 1438 |
} |
| 1439 |
result = { |
| 1440 |
uri_map[category][1]: schema_id, |
| 1441 |
uri_map[category][2]: template_name, |
| 1442 |
} |
| 1443 |
|
| 1444 |
self.recursive_dict_from_ref_regex(name, result, uri_map[category][0]) |
| 1445 |
|
| 1446 |
return result |
| 1447 |
else: |
| 1448 |
ref_regex = re.compile(r"uni\/tn-(.*)\/out-(.*)") |
| 1449 |
dic = ref_regex.search(data) |
| 1450 |
if dic is not None: |
| 1451 |
return {"l3outName": dic.group(2), "tenant": dic.group(1)} |
| 1452 |
self.fail_json(msg="There was no group in search: {data}".format(data=data)) |
| 1453 |
|
| 1454 |
def recursive_dict_from_ref_regex(self, data, result, category): |
| 1455 |
continued_ref_regex = re.compile(r"(.*?)\/([a-zA-Z]+.*)") |
| 1456 |
section_ref_regex = re.compile(r"([a-zA-Z]+)\/(.*)") |
| 1457 |
dic_name = continued_ref_regex.search(data) |
| 1458 |
if dic_name is not None: |
| 1459 |
result[category] = dic_name.group(1) |
| 1460 |
next_section = dic_name.group(2) |
| 1461 |
dic_next_section = section_ref_regex.search(next_section) |
| 1462 |
if dic_next_section is not None: |
| 1463 |
next_name = dic_next_section.group(2) |
| 1464 |
self.recursive_dict_from_ref_regex(next_name, result, dic_next_section.group(1).rstrip("s") + "Name") |
| 1465 |
else: |
| 1466 |
result[category] = data |
| 1467 |
|
| 1468 |
def recursive_dict_from_ref(self, data): |
| 1469 |
for key in data: |
| 1470 |
if key.endswith("Ref"): |
| 1471 |
data[key] = self.dict_from_ref(data.get(key)) |
| 1472 |
if isinstance(data[key], list): |
| 1473 |
for item in data[key]: |
| 1474 |
self.recursive_dict_from_ref(item) |
| 1475 |
return data |
| 1476 |
|
| 1477 |
def make_reference(self, data, reftype, schema_id, template): |
| 1478 |
"""Create a reference from a dictionary""" |
| 1479 |
# Removes entry from payload |
| 1480 |
if data is None: |
| 1481 |
return None |
| 1482 |
|
| 1483 |
if data.get("schema") is not None: |
| 1484 |
schema_obj = self.get_obj("schemas", displayName=data.get("schema")) |
| 1485 |
if not schema_obj: |
| 1486 |
self.fail_json(msg="Referenced schema '{schema}' in {reftype}ref does not exist".format(reftype=reftype, **data)) |
| 1487 |
schema_id = schema_obj.get("id") |
| 1488 |
|
| 1489 |
if data.get("template") is not None: |
| 1490 |
template = data.get("template") |
| 1491 |
|
| 1492 |
refname = "%sName" % reftype |
| 1493 |
|
| 1494 |
return { |
| 1495 |
refname: data.get("name"), |
| 1496 |
"schemaId": schema_id, |
| 1497 |
"templateName": template, |
| 1498 |
} |
| 1499 |
|
| 1500 |
def make_subnets(self, data, is_bd_subnet=True): |
| 1501 |
"""Create a subnets list from input""" |
| 1502 |
if data is None: |
| 1503 |
return None |
| 1504 |
|
| 1505 |
subnets = [] |
| 1506 |
for subnet in data: |
| 1507 |
if "subnet" in subnet: |
| 1508 |
subnet["ip"] = subnet.get("subnet") |
| 1509 |
if subnet.get("description") is None: |
| 1510 |
subnet["description"] = subnet.get("subnet") |
| 1511 |
subnet_payload = dict( |
| 1512 |
ip=subnet.get("ip"), |
| 1513 |
description=str(subnet.get("description")), |
| 1514 |
scope=subnet.get("scope"), |
| 1515 |
shared=subnet.get("shared"), |
| 1516 |
noDefaultGateway=subnet.get("no_default_gateway"), |
| 1517 |
) |
| 1518 |
if is_bd_subnet: |
| 1519 |
subnet_payload.update(dict(querier=subnet.get("querier"), primary=subnet.get("primary"), virtual=subnet.get("virtual"))) |
| 1520 |
subnets.append(subnet_payload) |
| 1521 |
|
| 1522 |
return subnets |
| 1523 |
|
| 1524 |
def make_dhcp_label(self, data): |
| 1525 |
"""Create a DHCP policy from input""" |
| 1526 |
if data is None: |
| 1527 |
return None |
| 1528 |
if isinstance(data, list): |
| 1529 |
dhcps = [] |
| 1530 |
for dhcp in data: |
| 1531 |
if "dhcp_option_policy" in dhcp: |
| 1532 |
dhcp["dhcpOptionLabel"] = dhcp.get("dhcp_option_policy") |
| 1533 |
del dhcp["dhcp_option_policy"] |
| 1534 |
dhcps.append(dhcp) |
| 1535 |
return dhcps |
| 1536 |
if "version" in data: |
| 1537 |
data["version"] = int(data.get("version")) |
| 1538 |
if data and "dhcp_option_policy" in data: |
| 1539 |
dhcp_option_policy = data.get("dhcp_option_policy") |
| 1540 |
if dhcp_option_policy is not None and "version" in dhcp_option_policy: |
| 1541 |
dhcp_option_policy["version"] = int(dhcp_option_policy.get("version")) |
| 1542 |
data["dhcpOptionLabel"] = dhcp_option_policy |
| 1543 |
del data["dhcp_option_policy"] |
| 1544 |
return data |
| 1545 |
|
| 1546 |
def sanitize(self, updates, collate=False, required=None, unwanted=None): |
| 1547 |
"""Clean up unset keys from a request payload""" |
| 1548 |
if required is None: |
| 1549 |
required = [] |
| 1550 |
if unwanted is None: |
| 1551 |
unwanted = [] |
| 1552 |
self.proposed = deepcopy(self.existing) |
| 1553 |
self.sent = deepcopy(self.existing) |
| 1554 |
|
| 1555 |
if isinstance(self.existing, dict): |
| 1556 |
for key in self.existing: |
| 1557 |
# Remove References |
| 1558 |
if key.endswith("Ref"): |
| 1559 |
if key in required: |
| 1560 |
continue |
| 1561 |
self.proposed.pop(key, None) |
| 1562 |
self.sent.pop(key, None) |
| 1563 |
continue |
| 1564 |
|
| 1565 |
# Removed unwanted keys |
| 1566 |
elif key in unwanted: |
| 1567 |
self.proposed.pop(key, None) |
| 1568 |
self.sent.pop(key, None) |
| 1569 |
continue |
| 1570 |
|
| 1571 |
if isinstance(updates, dict): |
| 1572 |
# Clean up self.sent |
| 1573 |
for key in updates: |
| 1574 |
# Always retain 'id' |
| 1575 |
if key in required: |
| 1576 |
if key in self.existing or updates.get(key) is not None: |
| 1577 |
self.sent[key] = updates.get(key) |
| 1578 |
continue |
| 1579 |
|
| 1580 |
# Remove unspecified values |
| 1581 |
elif not collate and updates.get(key) is None: |
| 1582 |
if key in self.existing: |
| 1583 |
self.sent.pop(key, None) |
| 1584 |
continue |
| 1585 |
|
| 1586 |
# Remove identical values |
| 1587 |
elif not collate and updates.get(key) == self.existing.get(key): |
| 1588 |
self.sent.pop(key, None) |
| 1589 |
continue |
| 1590 |
|
| 1591 |
# Add everything else |
| 1592 |
if updates.get(key) is not None: |
| 1593 |
self.sent[key] = updates.get(key) |
| 1594 |
|
| 1595 |
# Update self.proposed |
| 1596 |
self.proposed.update(self.sent) |
| 1597 |
|
| 1598 |
elif updates is not None: |
| 1599 |
self.sent = updates |
| 1600 |
# Update self.proposed |
| 1601 |
self.proposed = self.sent |
| 1602 |
|
| 1603 |
def delete_keys_from_dict(self, dict_to_sanitize, keys): |
| 1604 |
# TODO investigate combine this method above sanitize method |
| 1605 |
copy = deepcopy(dict_to_sanitize) |
| 1606 |
for ( |
| 1607 |
k, |
| 1608 |
v, |
| 1609 |
) in copy.items(): |
| 1610 |
if k in keys: |
| 1611 |
del dict_to_sanitize[k] |
| 1612 |
elif isinstance(v, dict): |
| 1613 |
dict_to_sanitize[k] = self.delete_keys_from_dict(v, keys) |
| 1614 |
elif isinstance(v, list): |
| 1615 |
for index, item in enumerate(v): |
| 1616 |
if isinstance(item, dict): |
| 1617 |
dict_to_sanitize[k][index] = self.delete_keys_from_dict(item, keys) |
| 1618 |
return dict_to_sanitize |
| 1619 |
|
| 1620 |
def exit_json(self, **kwargs): |
| 1621 |
"""Custom written method to exit from module.""" |
| 1622 |
|
| 1623 |
if self.params.get("state") in ("absent", "present", "upload", "restore", "download", "move", "clone"): |
| 1624 |
if self.params.get("output_level") in ("debug", "info"): |
| 1625 |
self.result["previous"] = self.previous |
| 1626 |
# FIXME: Modified header only works for PATCH |
| 1627 |
if not self.has_modified and self.previous != self.existing: |
| 1628 |
self.result["changed"] = True |
| 1629 |
if self.stdout: |
| 1630 |
self.result["stdout"] = self.stdout |
| 1631 |
|
| 1632 |
# Return the gory details when we need it |
| 1633 |
if self.params.get("output_level") == "debug": |
| 1634 |
self.result["method"] = self.method |
| 1635 |
self.result["response"] = self.response |
| 1636 |
self.result["status"] = self.status |
| 1637 |
self.result["url"] = self.url |
| 1638 |
self.result["httpapi_logs"] = self.httpapi_logs |
| 1639 |
self.result["socket"] = self.module._socket_path |
| 1640 |
|
| 1641 |
if self.params.get("state") in ("absent", "present"): |
| 1642 |
self.result["sent"] = self.sent |
| 1643 |
self.result["proposed"] = self.proposed |
| 1644 |
|
| 1645 |
if self.method == "PATCH": |
| 1646 |
self.result["patch_operation"] = self.patch_operation |
| 1647 |
|
| 1648 |
self.result["current"] = self.existing |
| 1649 |
|
| 1650 |
if self.module._diff and self.result.get("changed") is True: |
| 1651 |
self.result["diff"] = dict( |
| 1652 |
before=self.previous, |
| 1653 |
after=self.existing, |
| 1654 |
) |
| 1655 |
|
| 1656 |
self.result.update(**kwargs) |
| 1657 |
self.module.exit_json(**self.result) |
| 1658 |
|
| 1659 |
def fail_json(self, msg, **kwargs): |
| 1660 |
"""Custom written method to return info on failure.""" |
| 1661 |
|
| 1662 |
if self.params.get("state") in ("absent", "present"): |
| 1663 |
if self.params.get("output_level") in ("debug", "info"): |
| 1664 |
self.result["previous"] = self.previous |
| 1665 |
# FIXME: Modified header only works for PATCH |
| 1666 |
if not self.has_modified and self.previous != self.existing: |
| 1667 |
self.result["changed"] = True |
| 1668 |
if self.stdout: |
| 1669 |
self.result["stdout"] = self.stdout |
| 1670 |
|
| 1671 |
# Return the gory details when we need it |
| 1672 |
if self.params.get("output_level") == "debug": |
| 1673 |
if self.url is not None: |
| 1674 |
self.result["method"] = self.method |
| 1675 |
self.result["response"] = self.response |
| 1676 |
self.result["status"] = self.status |
| 1677 |
self.result["url"] = self.url |
| 1678 |
self.result["httpapi_logs"] = self.httpapi_logs |
| 1679 |
self.result["socket"] = self.module._socket_path |
| 1680 |
|
| 1681 |
if self.params.get("state") in ("absent", "present"): |
| 1682 |
self.result["sent"] = self.sent |
| 1683 |
self.result["proposed"] = self.proposed |
| 1684 |
|
| 1685 |
if self.method == "PATCH": |
| 1686 |
self.result["patch_operation"] = self.patch_operation |
| 1687 |
|
| 1688 |
self.result["current"] = self.existing |
| 1689 |
|
| 1690 |
self.result.update(**kwargs) |
| 1691 |
self.module.fail_json(msg=msg, **self.result) |
| 1692 |
|
| 1693 |
def check_changed(self): |
| 1694 |
"""Check if changed by comparing new values from existing""" |
| 1695 |
existing = self.existing |
| 1696 |
if "password" in existing: |
| 1697 |
existing["password"] = self.sent.get("password") |
| 1698 |
|
| 1699 |
existing = self.remove_keys_from_dict_when_value_empty(existing) |
| 1700 |
self.stdout = json.dumps(existing) |
| 1701 |
|
| 1702 |
return not issubset(self.sent, existing) |
| 1703 |
|
| 1704 |
def update_service_graph_obj(self, service_graph_obj): |
| 1705 |
"""update filter with more information""" |
| 1706 |
service_graph_obj["serviceGraphRef"] = self.dict_from_ref(service_graph_obj.get("serviceGraphRef")) |
| 1707 |
for service_node in service_graph_obj["serviceNodesRelationship"]: |
| 1708 |
service_node.get("consumerConnector")["bdRef"] = self.dict_from_ref(service_node.get("consumerConnector").get("bdRef")) |
| 1709 |
service_node.get("providerConnector")["bdRef"] = self.dict_from_ref(service_node.get("providerConnector").get("bdRef")) |
| 1710 |
service_node["serviceNodeRef"] = self.dict_from_ref(service_node.get("serviceNodeRef")) |
| 1711 |
if service_graph_obj.get("serviceGraphContractRelationRef"): |
| 1712 |
del service_graph_obj["serviceGraphContractRelationRef"] |
| 1713 |
|
| 1714 |
def update_filter_obj(self, contract_obj, filter_obj, filter_type, contract_display_name=None, update_filter_ref=True): |
| 1715 |
"""update filter with more information""" |
| 1716 |
if update_filter_ref: |
| 1717 |
filter_obj["filterRef"] = self.dict_from_ref(filter_obj.get("filterRef")) |
| 1718 |
if contract_display_name: |
| 1719 |
filter_obj["displayName"] = contract_display_name |
| 1720 |
else: |
| 1721 |
filter_obj["displayName"] = contract_obj.get("displayName") |
| 1722 |
filter_obj["filterType"] = filter_type |
| 1723 |
filter_obj["contractScope"] = contract_obj.get("scope") |
| 1724 |
filter_obj["contractFilterType"] = contract_obj.get("filterType") |
| 1725 |
# Conditional statement 'description == ""' is needed to set empty string. |
| 1726 |
if contract_obj.get("description") or contract_obj.get("description") == "": |
| 1727 |
filter_obj["description"] = contract_obj.get("description") |
| 1728 |
# Conditional statement is needed to determine if "prio" exist in contract object. |
| 1729 |
# Same reason as described mso_schema_template_contract_filter.py. |
| 1730 |
if contract_obj.get("prio"): |
| 1731 |
filter_obj["prio"] = contract_obj.get("prio") |
| 1732 |
|
| 1733 |
def query_schema(self, schema): |
| 1734 |
schema_id = self.lookup_schema(schema) |
| 1735 |
schema_path = "schemas/{0}".format(schema_id) |
| 1736 |
schema_obj = self.query_obj(schema_path, displayName=schema) |
| 1737 |
if not schema_obj: |
| 1738 |
self.module.fail_json(msg="Schema '{0}' is not a valid schema name.".format(schema)) |
| 1739 |
return schema_id, schema_path, schema_obj |
| 1740 |
|
| 1741 |
def query_schema_by_id(self, schema_id): |
| 1742 |
schema_path = "schemas/{0}".format(schema_id) |
| 1743 |
schema_obj = self.query_obj(schema_path) |
| 1744 |
if not schema_obj: |
| 1745 |
self.module.fail_json(msg="Schema '{0}' is not a valid schema ID.".format(schema_id)) |
| 1746 |
return schema_id, schema_path, schema_obj |
| 1747 |
|
| 1748 |
def query_service_node_types(self): |
| 1749 |
node_objs = self.query_objs("schemas/service-node-types", key="serviceNodeTypes") |
| 1750 |
if not node_objs: |
| 1751 |
self.module.fail_json(msg="Service node types do not exist") |
| 1752 |
return node_objs |
| 1753 |
|
| 1754 |
def lookup_service_node_device(self, site_id, tenant, device_name=None, service_node_type=None, ignore_not_found_error=False): |
| 1755 |
if self.site_type == "cloud": |
| 1756 |
tenant = "{0}/{1}".format(tenant, self.site_type) |
| 1757 |
|
| 1758 |
if service_node_type is None: |
| 1759 |
node_devices = self.query_objs("sites/{0}/aci/tenants/{1}/devices".format(site_id, tenant), key="devices") |
| 1760 |
else: |
| 1761 |
node_devices = self.query_objs("sites/{0}/aci/tenants/{1}/devices?deviceType={2}".format(site_id, tenant, service_node_type), key="devices") |
| 1762 |
if device_name is not None: |
| 1763 |
for device in node_devices: |
| 1764 |
if device_name == device.get("name"): |
| 1765 |
return device |
| 1766 |
if ignore_not_found_error: |
| 1767 |
self.module.warn("Provided device '{0}' of type '{1}' does not exist.".format(device_name, service_node_type)) |
| 1768 |
return node_devices |
| 1769 |
else: |
| 1770 |
self.module.fail_json(msg="Provided device '{0}' of type '{1}' does not exist.".format(device_name, service_node_type)) |
| 1771 |
return node_devices |
| 1772 |
|
| 1773 |
# Workaround function due to inconsistency in attributes REQUEST/RESPONSE API |
| 1774 |
# Fix for MSO Error 400: Bad Request: (0)(0)(0)(0)/deploymentImmediacy error.path.missing |
| 1775 |
def find_dicts_with_target_key(self, target_dict, target, replace, result=None): |
| 1776 |
if result is None: |
| 1777 |
result = [] |
| 1778 |
|
| 1779 |
for key, value in target_dict.items(): |
| 1780 |
if key == target: |
| 1781 |
result.append(target_dict) |
| 1782 |
if isinstance(value, dict): |
| 1783 |
self.find_dicts_with_target_key(value, target, replace, result) |
| 1784 |
if isinstance(value, list): |
| 1785 |
for entry in value: |
| 1786 |
if isinstance(entry, dict): |
| 1787 |
self.find_dicts_with_target_key(entry, target, replace, result) |
| 1788 |
|
| 1789 |
return result |
| 1790 |
|
| 1791 |
# Workaround function due to inconsistency in attributes REQUEST/RESPONSE API |
| 1792 |
# Fix for MSO Error 400: Bad Request: (0)(0)(0)(0)/deploymentImmediacy error.path.missing |
| 1793 |
def replace_keys_in_dict(self, target, replace, target_dict=None): |
| 1794 |
if target_dict is None: |
| 1795 |
target_dict = self.existing |
| 1796 |
|
| 1797 |
key_list = self.find_dicts_with_target_key(target_dict, target, replace) |
| 1798 |
for item in key_list: |
| 1799 |
item[replace] = item.get(target) |
| 1800 |
del item[target] |
| 1801 |
|
| 1802 |
# Workaround function to remove null/None fields returned by API RESPONSE |
| 1803 |
def remove_keys_from_dict_when_value_empty(self, target_dict, modified_target=None): |
| 1804 |
if modified_target is None: |
| 1805 |
modified_target = deepcopy(target_dict) |
| 1806 |
|
| 1807 |
for key, value in target_dict.items(): |
| 1808 |
if value is None: |
| 1809 |
del modified_target[key] |
| 1810 |
elif isinstance(value, dict): |
| 1811 |
self.remove_keys_from_dict_when_value_empty(value, modified_target[key]) |
| 1812 |
elif isinstance(value, list): |
| 1813 |
for entry_index, entry in enumerate(value): |
| 1814 |
if isinstance(entry, dict): |
| 1815 |
self.remove_keys_from_dict_when_value_empty(entry, modified_target[key][entry_index]) |
| 1816 |
|
| 1817 |
return modified_target |
| 1818 |
|
| 1819 |
def validate_schema(self, schema_id): |
| 1820 |
return self.request("schemas/{id}/validate".format(id=schema_id), method="GET") |
| 1821 |
|
| 1822 |
def input_validation(self, attr_name, attr_value, required_attributes, target_object, object_position=None, object_name=None): |
| 1823 |
if attr_name in (None, "") or attr_value in (None, ""): |
| 1824 |
self.module.fail_json(msg="The attribute and value must be set") |
| 1825 |
|
| 1826 |
empty_attributes = [attribute for attribute in required_attributes if target_object.get(attribute) in (None, "", [], {}, 0)] |
| 1827 |
|
| 1828 |
if object_position is not None and object_name is not None and empty_attributes: |
| 1829 |
self.module.fail_json( |
| 1830 |
msg="When the '{0}' is '{1}', the {2} attributes must be set at the object position: {3} and the object name: {4}".format( |
| 1831 |
attr_name, attr_value, empty_attributes, object_position, object_name |
| 1832 |
) |
| 1833 |
) |
| 1834 |
elif object_position is not None and object_name is None and empty_attributes: |
| 1835 |
self.module.fail_json( |
| 1836 |
msg="When the '{0}' is '{1}', the {2} attributes must be set at the object position: {3}".format( |
| 1837 |
attr_name, attr_value, empty_attributes, object_position |
| 1838 |
) |
| 1839 |
) |
| 1840 |
elif object_position is None and object_name is not None and empty_attributes: |
| 1841 |
self.module.fail_json( |
| 1842 |
msg="When the '{0}' is '{1}', the {2} attributes must be set and the object name: {3}".format( |
| 1843 |
attr_name, attr_value, empty_attributes, object_name |
| 1844 |
) |
| 1845 |
) |
| 1846 |
elif empty_attributes: |
| 1847 |
self.module.fail_json(msg="When the '{0}' is '{1}', the {2} attributes must be set".format(attr_name, attr_value, empty_attributes)) |
| 1848 |
|
| 1849 |
# Temporarily introduced method to handle nd specific query without introducing a dependency on the nd collection in code |
| 1850 |
# Copied method from the nd collection: https://github.com/CiscoDevNet/ansible-nd/blob/master/plugins/module_utils/nd.py#L221 |
| 1851 |
# TODO: Refactor the code for bundled nd collection |
| 1852 |
def nd_request(self, path, method=None, data=None, file=None, qs=None, prefix="", file_key="file", output_format="json", ignore_not_found_error=False): |
| 1853 |
"""Generic HTTP method for ND requests.""" |
| 1854 |
self.path = path |
| 1855 |
|
| 1856 |
if method is not None: |
| 1857 |
self.method = method |
| 1858 |
|
| 1859 |
# If we PATCH with empty operations, return |
| 1860 |
if method == "PATCH" and not data: |
| 1861 |
return {} |
| 1862 |
|
| 1863 |
conn = Connection(self.module._socket_path) |
| 1864 |
conn.set_params(self.params) |
| 1865 |
uri = self.path |
| 1866 |
if prefix != "": |
| 1867 |
uri = "{0}/{1}".format(prefix, self.path) |
| 1868 |
if qs is not None: |
| 1869 |
uri = uri + update_qs(qs) |
| 1870 |
try: |
| 1871 |
if file is not None: |
| 1872 |
info = conn.send_file_request(method, uri, file, data, None, file_key) |
| 1873 |
else: |
| 1874 |
if data: |
| 1875 |
info = conn.send_request(method, uri, json.dumps(data)) |
| 1876 |
else: |
| 1877 |
info = conn.send_request(method, uri) |
| 1878 |
self.result["data"] = data |
| 1879 |
|
| 1880 |
self.url = info.get("url") |
| 1881 |
self.httpapi_logs.extend(conn.pop_messages()) |
| 1882 |
info.pop("date", None) |
| 1883 |
except Exception as e: |
| 1884 |
try: |
| 1885 |
error_obj = json.loads(to_text(e)) |
| 1886 |
except Exception: |
| 1887 |
error_obj = dict(error=dict(code=-1, message="Unable to parse error output as JSON. Raw error message: {0}".format(e), exception=to_text(e))) |
| 1888 |
pass |
| 1889 |
self.fail_json(msg=error_obj["error"]["message"]) |
| 1890 |
|
| 1891 |
self.response = info.get("msg") |
| 1892 |
self.status = info.get("status", -1) |
| 1893 |
|
| 1894 |
self.result["socket"] = self.module._socket_path |
| 1895 |
|
| 1896 |
# Get change status from HTTP headers |
| 1897 |
if "modified" in info: |
| 1898 |
self.has_modified = True |
| 1899 |
if info.get("modified") == "false": |
| 1900 |
self.result["changed"] = False |
| 1901 |
elif info.get("modified") == "true": |
| 1902 |
self.result["changed"] = True |
| 1903 |
|
| 1904 |
# 200: OK, 201: Created, 202: Accepted, 204: No Content |
| 1905 |
if self.status in (200, 201, 202, 204): |
| 1906 |
if output_format == "raw": |
| 1907 |
return info.get("raw") |
| 1908 |
return info.get("body") |
| 1909 |
|
| 1910 |
# 404: Not Found |
| 1911 |
elif self.method == "DELETE" and self.status == 404: |
| 1912 |
return {} |
| 1913 |
|
| 1914 |
# 400: Bad Request, 401: Unauthorized, 403: Forbidden, |
| 1915 |
# 405: Method Not Allowed, 406: Not Acceptable |
| 1916 |
# 500: Internal Server Error, 501: Not Implemented |
| 1917 |
elif self.status >= 400: |
| 1918 |
self.result["status"] = self.status |
| 1919 |
body = info.get("body") |
| 1920 |
if body is not None: |
| 1921 |
try: |
| 1922 |
if isinstance(body, dict): |
| 1923 |
payload = body |
| 1924 |
else: |
| 1925 |
payload = json.loads(body) |
| 1926 |
except Exception as e: |
| 1927 |
self.error = dict(code=-1, message="Unable to parse output as JSON, see 'raw' output. {0}".format(e)) |
| 1928 |
self.result["raw"] = body |
| 1929 |
self.fail_json(msg="ND Error: {0}".format(self.error.get("message")), data=data, info=info) |
| 1930 |
self.error = payload |
| 1931 |
if "code" in payload: |
| 1932 |
self.fail_json(msg="ND Error {code}: {message}".format(**payload), data=data, info=info, payload=payload) |
| 1933 |
elif "messages" in payload and len(payload.get("messages")) > 0: |
| 1934 |
self.fail_json(msg="ND Error {code} ({severity}): {message}".format(**payload["messages"][0]), data=data, info=info, payload=payload) |
| 1935 |
else: |
| 1936 |
if ignore_not_found_error: |
| 1937 |
return {} |
| 1938 |
self.fail_json(msg="ND Error: Unknown error no error code in decoded payload".format(**payload), data=data, info=info, payload=payload) |
| 1939 |
elif not ignore_not_found_error: |
| 1940 |
self.result["raw"] = info.get("raw") |
| 1941 |
# Connection error |
| 1942 |
msg = "Connection failed for {0}. {1}".format(info.get("url"), info.get("msg")) |
| 1943 |
self.error = msg |
| 1944 |
self.fail_json(msg=msg) |
| 1945 |
return {} |
| 1946 |
|
| 1947 |
def verify_time_format(self, date_time): |
| 1948 |
if date_time != "now" or date_time != "infinite": |
| 1949 |
try: |
| 1950 |
formatted_date_time = datetime.datetime.strptime(date_time, "%Y-%m-%d %H:%M:%S") |
| 1951 |
return str(formatted_date_time) |
| 1952 |
except ValueError: |
| 1953 |
return self.fail_json(msg="ERROR: The time must be in 'YYYY-MM-DD HH:MM:SS' format.") |
| 1954 |
|
| 1955 |
def get_site_interface_details(self, site_id=None, uuid=None, node=None, port=None, port_channel_uuid=None, virtual_port_channel_uuid=None): |
| 1956 |
if port_channel_uuid: |
| 1957 |
path = "/pcsummary/site/{0}?uuid={1}".format(site_id, port_channel_uuid) |
| 1958 |
elif virtual_port_channel_uuid: |
| 1959 |
path = "/vpcsummary/site/{0}?uuid={1}".format(site_id, virtual_port_channel_uuid) |
| 1960 |
elif uuid: |
| 1961 |
path = "/sitephysifsummary/site/{0}?uuid={1}".format(site_id, uuid) |
| 1962 |
elif node: |
| 1963 |
path = "/sitephysifsummary/site/{0}?node={1}".format(site_id, node) |
| 1964 |
|
| 1965 |
site_data = self.request(path, method="GET") |
| 1966 |
|
| 1967 |
if port_channel_uuid: |
| 1968 |
if site_data.get("spec", {}).get("pcs"): |
| 1969 |
return site_data.get("spec", {}).get("pcs")[0] |
| 1970 |
self.fail_json(msg="The site port channel interface not found. Site ID: {0} and UUID: {1}".format(site_id, port_channel_uuid)) |
| 1971 |
elif virtual_port_channel_uuid: |
| 1972 |
if site_data.get("spec", {}).get("vpcs"): |
| 1973 |
return site_data.get("spec", {}).get("vpcs")[0] |
| 1974 |
self.fail_json(msg="The site virtual port channel interface not found. Site ID: {0} and UUID: {1}".format(site_id, virtual_port_channel_uuid)) |
| 1975 |
elif uuid: |
| 1976 |
if site_data.get("spec", {}).get("monitoringTemplateInterfaces"): |
| 1977 |
return site_data.get("spec", {}).get("monitoringTemplateInterfaces", [])[0] |
| 1978 |
else: |
| 1979 |
self.fail_json(msg="The site port interface not found. Site ID: {0} and UUID: {1}".format(site_id, uuid)) |
| 1980 |
elif node and port: |
| 1981 |
for interface in site_data.get("spec", {}).get("interfaces", []): |
| 1982 |
# To ensure consistency between the API response data and the input data by converting the node to a string |
| 1983 |
if interface.get("port") == port and str(interface.get("node")) == str(node): |
| 1984 |
return interface |
| 1985 |
self.fail_json(msg="The site port interface not found. Site ID: {0}, Node: {1} and Path: {2}".format(site_id, node, port)) |
| 1986 |
elif node: |
| 1987 |
pod_ids = list(set([interface.get("pod") for interface in site_data.get("spec", {}).get("interfaces", [])])) |
| 1988 |
if len(pod_ids) == 1: |
| 1989 |
# All physical interfaces of a node should belong to the same POD. |
| 1990 |
return pod_ids[0] |
| 1991 |
elif len(pod_ids) == 0: |
| 1992 |
self.fail_json(msg="The site and node not found. Site ID: {0} and Node: {1}".format(site_id, node)) |
| 1993 |
elif len(pod_ids) > 1: |
| 1994 |
# This scenario should never be possible but is added in case of faulty return data. |
| 1995 |
self.fail_json(msg="The site and node are found with multiple POD IDs. Site ID: {0}, Node: {1}, POD IDs: {2}".format(site_id, node, pod_ids)) |
| 1996 |
|
| 1997 |
return {} |
| 1998 |
|
| 1999 |
def check_template_when_name_is_provided(self, parameter): |
| 2000 |
if parameter and parameter.get("name") and not (parameter.get("template") or parameter.get("template_id")): |
| 2001 |
self.fail_json(msg="Either 'template' or 'template_id' associated with '{}' must be provided".format(parameter.get("name"))) |
| 2002 |
|
| 2003 |
|
| 2004 |
def service_node_ref_str_to_dict(serviceNodeRefStr): |
| 2005 |
serviceNodeRefTokens = serviceNodeRefStr.split("/") |
| 2006 |
return dict( |
| 2007 |
schemaId=serviceNodeRefTokens[2], |
| 2008 |
serviceGraphName=serviceNodeRefTokens[6], |
| 2009 |
serviceNodeName=serviceNodeRefTokens[8], |
| 2010 |
templateName=serviceNodeRefTokens[4], |
| 2011 |
) |
| 2012 |
|
| 2013 |
|
| 2014 |
def mso_schema_site_contract_service_graph_spec(): |
| 2015 |
return dict( |
| 2016 |
cluster_interface_device=dict(type="str", required=True, aliases=["cluster_device", "device", "device_name"]), |
| 2017 |
provider_connector_cluster_interface=dict( |
| 2018 |
type="str", required=True, aliases=["provider_cluster_interface", "provider_interface", "provider_interface_name"] |
| 2019 |
), |
| 2020 |
provider_connector_redirect_policy_tenant=dict(type="str", aliases=["provider_redirect_policy_tenant", "provider_tenant"]), |
| 2021 |
provider_connector_redirect_policy=dict(type="str", aliases=["provider_redirect_policy", "provider_policy"]), |
| 2022 |
consumer_connector_cluster_interface=dict( |
| 2023 |
type="str", required=True, aliases=["consumer_cluster_interface", "consumer_interface", "consumer_interface_name"] |
| 2024 |
), |
| 2025 |
consumer_connector_redirect_policy_tenant=dict(type="str", aliases=["consumer_redirect_policy_tenant", "consumer_tenant"]), |
| 2026 |
consumer_connector_redirect_policy=dict(type="str", aliases=["consumer_redirect_policy", "consumer_policy"]), |
| 2027 |
consumer_subnet_ips=dict(type="list", elements="str"), |
| 2028 |
) |
| 2029 |
|
| 2030 |
|
| 2031 |
def listener_ssl_certificates_spec(): |
| 2032 |
return dict( |
| 2033 |
name=dict(type="str", required=True), |
| 2034 |
certificate_store=dict(type="str", choices=["default", "iam", "acm"], required=True), |
| 2035 |
) |
| 2036 |
|
| 2037 |
|
| 2038 |
def listener_rules_provider_epg_ref_spec(): |
| 2039 |
return dict( |
| 2040 |
schema=dict(type="str"), |
| 2041 |
template=dict(type="str"), |
| 2042 |
anp_name=dict(type="str", required=True, aliases=["anp"]), |
| 2043 |
epg_name=dict(type="str", required=True, aliases=["epg"]), |
| 2044 |
) |
| 2045 |
|
| 2046 |
|
| 2047 |
def listener_rules_health_check_spec(): |
| 2048 |
return dict( |
| 2049 |
port=dict(type="int"), |
| 2050 |
protocol=dict(type="str", choices=LISTENER_PROTOCOLS), |
| 2051 |
path=dict(type="str"), |
| 2052 |
interval=dict(type="int"), |
| 2053 |
timeout=dict(type="int"), |
| 2054 |
unhealthy_threshold=dict(type="int"), |
| 2055 |
use_host_from_rule=dict(type="bool"), |
| 2056 |
success_code=dict(type="str"), |
| 2057 |
host=dict(type="str"), |
| 2058 |
) |
| 2059 |
|
| 2060 |
|
| 2061 |
def listener_rules_spec(): |
| 2062 |
return dict( |
| 2063 |
name=dict(type="str", required=True), |
| 2064 |
floating_ip=dict(type="str"), |
| 2065 |
priority=dict(type="int", required=True), |
| 2066 |
host=dict(type="str"), |
| 2067 |
path=dict(type="str"), |
| 2068 |
action=dict(type="str"), |
| 2069 |
action_type=dict(type="str", required=True, choices=list(LISTENER_ACTION_TYPE_MAP)), |
| 2070 |
content_type=dict(type="str", choices=list(LISTENER_CONTENT_TYPE_MAP)), |
| 2071 |
port=dict(type="int"), |
| 2072 |
protocol=dict(type="str", choices=LISTENER_PROTOCOLS), |
| 2073 |
provider_epg=dict( |
| 2074 |
type="dict", |
| 2075 |
options=listener_rules_provider_epg_ref_spec(), |
| 2076 |
), |
| 2077 |
url_type=dict(type="str", choices=["original", "custom"]), |
| 2078 |
custom_url=dict(type="str"), |
| 2079 |
redirect_host_name=dict(type="str"), |
| 2080 |
redirect_path=dict(type="str"), |
| 2081 |
redirect_query=dict(type="str"), |
| 2082 |
response_code=dict(type="str"), |
| 2083 |
response_body=dict(type="str"), |
| 2084 |
redirect_protocol=dict(type="str", choices=LISTENER_PROTOCOLS), |
| 2085 |
redirect_port=dict(type="int"), |
| 2086 |
redirect_code=dict(type="str", choices=list(LISTENER_REDIRECT_CODE_MAP)), |
| 2087 |
health_check=dict( |
| 2088 |
type="dict", |
| 2089 |
options=listener_rules_health_check_spec(), |
| 2090 |
), |
| 2091 |
target_ip_type=dict(type="str", choices=["unspecified", "primary", "secondary"]), |
| 2092 |
) |
| 2093 |
|
| 2094 |
|
| 2095 |
def epg_object_reference_spec(aliases=None): |
| 2096 |
epg_reference_spec = dict( |
| 2097 |
type="dict", |
| 2098 |
options=dict( |
| 2099 |
name=dict(type="str", required=True), |
| 2100 |
template=dict(type="str"), |
| 2101 |
template_id=dict(type="str"), |
| 2102 |
schema=dict(type="str"), |
| 2103 |
schema_id=dict(type="str"), |
| 2104 |
anp=dict(type="str"), |
| 2105 |
anp_uuid=dict(type="str"), |
| 2106 |
), |
| 2107 |
required_one_of=[ |
| 2108 |
["template", "template_id"], |
| 2109 |
["schema", "schema_id"], |
| 2110 |
["anp", "anp_uuid"], |
| 2111 |
], |
| 2112 |
mutually_exclusive=[ |
| 2113 |
("schema", "schema_id"), |
| 2114 |
("template", "template_id"), |
| 2115 |
("anp", "anp_uuid"), |
| 2116 |
], |
| 2117 |
) |
| 2118 |
if aliases: |
| 2119 |
epg_reference_spec["aliases"] = aliases |
| 2120 |
return epg_reference_spec |