diff --git a/plugins/module_utils/common/exceptions.py b/plugins/module_utils/common/exceptions.py index 16e31ac6..0c53c2c2 100644 --- a/plugins/module_utils/common/exceptions.py +++ b/plugins/module_utils/common/exceptions.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2026, Allen Robel (@arobel) +# Copyright: (c) 2026, Gaspard Micol (@gmicol) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) """ @@ -16,10 +15,6 @@ # fmt: on # isort: on -# pylint: disable=invalid-name -__metaclass__ = type -# pylint: enable=invalid-name - from typing import Any, Optional from ansible_collections.cisco.nd.plugins.module_utils.common.pydantic_compat import ( @@ -144,3 +139,11 @@ def to_dict(self) -> dict[str, Any]: - None """ return self.error_data.model_dump(exclude_none=True) + + +class NDStateMachineError(Exception): + """ + Raised when NDStateMachine is failing. + """ + + pass diff --git a/plugins/module_utils/common/log.py b/plugins/module_utils/common/log.py index 29182539..f43d9018 100644 --- a/plugins/module_utils/common/log.py +++ b/plugins/module_utils/common/log.py @@ -1,15 +1,9 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2026, Allen Robel (@arobel) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function -# pylint: disable=invalid-name -__metaclass__ = type -# pylint: enable=invalid-name - import json import logging from enum import Enum diff --git a/plugins/module_utils/common/pydantic_compat.py b/plugins/module_utils/common/pydantic_compat.py index e1550a18..b26559d2 100644 --- a/plugins/module_utils/common/pydantic_compat.py +++ b/plugins/module_utils/common/pydantic_compat.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2026, Allen Robel (@arobel) +# Copyright: (c) 2026, Gaspard Micol (@gmicol) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) @@ -34,10 +33,6 @@ # fmt: on # isort: on -# pylint: disable=invalid-name -__metaclass__ = type -# pylint: enable=invalid-name - import traceback from typing import TYPE_CHECKING, Any, Callable, Union @@ -51,11 +46,16 @@ Field, PydanticExperimentalWarning, StrictBool, + SecretStr, ValidationError, field_serializer, + model_serializer, field_validator, model_validator, validator, + computed_field, + FieldSerializationInfo, + SerializationInfo, ) HAS_PYDANTIC = True # pylint: disable=invalid-name @@ -71,11 +71,16 @@ Field, PydanticExperimentalWarning, StrictBool, + SecretStr, ValidationError, field_serializer, + model_serializer, field_validator, model_validator, validator, + computed_field, + FieldSerializationInfo, + SerializationInfo, ) except ImportError: HAS_PYDANTIC = False # pylint: disable=invalid-name @@ -127,6 +132,15 @@ def decorator(func): return decorator + # Fallback: model_serializer decorator that does nothing + def model_serializer(*args, **kwargs): # pylint: disable=unused-argument + """Pydantic model_serializer fallback when pydantic is not available.""" + + def decorator(func): + return func + + return decorator + # Fallback: field_validator decorator that does nothing def field_validator(*args, **kwargs) -> Callable[..., Any]: # pylint: disable=unused-argument,invalid-name """Pydantic field_validator fallback when pydantic is not available.""" @@ -136,6 +150,15 @@ def decorator(func): return decorator + # Fallback: computed_field decorator that does nothing + def computed_field(*args, **kwargs): # pylint: disable=unused-argument + """Pydantic computed_field fallback when pydantic is not available.""" + + def decorator(func): + return func + + return decorator + # Fallback: AfterValidator that returns the function unchanged def AfterValidator(func): # pylint: disable=invalid-name """Pydantic AfterValidator fallback when pydantic is not available.""" @@ -152,6 +175,9 @@ def BeforeValidator(func): # pylint: disable=invalid-name # Fallback: StrictBool StrictBool = bool + # Fallback: SecretStr + SecretStr = str + # Fallback: ValidationError class ValidationError(Exception): """ @@ -183,6 +209,20 @@ def decorator(func): return decorator + # Fallback: FieldSerializationInfo placeholder class that does nothing + class FieldSerializationInfo: + """Pydantic FieldSerializationInfo fallback when pydantic is not available.""" + + def __init__(self, **kwargs): + pass + + # Fallback: SerializationInfo placeholder class that does nothing + class SerializationInfo: + """Pydantic SerializationInfo fallback when pydantic is not available.""" + + def __init__(self, **kwargs): + pass + else: HAS_PYDANTIC = True # pylint: disable=invalid-name PYDANTIC_IMPORT_ERROR = None # pylint: disable=invalid-name @@ -234,10 +274,15 @@ def main(): "PYDANTIC_IMPORT_ERROR", "PydanticExperimentalWarning", "StrictBool", + "SecretStr", "ValidationError", "field_serializer", + "model_serializer", "field_validator", "model_validator", "require_pydantic", "validator", + "computed_field", + "FieldSerializationInfo", + "SerializationInfo", ] diff --git a/plugins/module_utils/constants.py b/plugins/module_utils/constants.py index 10de9edf..440ea369 100644 --- a/plugins/module_utils/constants.py +++ b/plugins/module_utils/constants.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2022, Akini Ross (@akinross) # Copyright: (c) 2024, Gaspard Micol (@gmicol) @@ -7,7 +5,45 @@ from __future__ import absolute_import, division, print_function -__metaclass__ = type +from typing import Dict +from types import MappingProxyType +from copy import deepcopy + + +class NDConstantMapping: + def __init__(self, data: Dict): + self.data = data + self.new_dict = deepcopy(data) + for k, v in data.items(): + self.new_dict[v] = k + self.new_dict = MappingProxyType(self.new_dict) + + def get_dict(self): + return self.new_dict + + def get_original_data(self): + return list(self.data.keys()) + + +from typing import Dict +from types import MappingProxyType +from copy import deepcopy + + +class NDConstantMapping(Dict): + def __init__(self, data: Dict): + self.data = data + self.new_dict = deepcopy(data) + for k, v in data.items(): + self.new_dict[v] = k + self.new_dict = MappingProxyType(self.new_dict) + + def get_dict(self): + return self.new_dict + + def get_original_data(self): + return list(self.data.keys()) + OBJECT_TYPES = { "tenant": "OST_TENANT", @@ -157,6 +193,11 @@ "restart", "delete", "update", + "merged", + "replaced", + "overridden", + "deleted", + "gathered", ) INTERFACE_FLOW_RULES_TYPES_MAPPING = {"port_channel": "PORTCHANNEL", "physical": "PHYSICAL", "l3out_sub_interface": "L3_SUBIF", "l3out_svi": "SVI"} diff --git a/plugins/module_utils/endpoints/base.py b/plugins/module_utils/endpoints/base.py index 3ccdff1c..f2f16dbc 100644 --- a/plugins/module_utils/endpoints/base.py +++ b/plugins/module_utils/endpoints/base.py @@ -1,4 +1,5 @@ # Copyright: (c) 2026, Allen Robel (@arobel) +# Copyright: (c) 2026, Gaspard Micol (@gmicol) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) """ @@ -22,6 +23,7 @@ Field, ) from ansible_collections.cisco.nd.plugins.module_utils.enums import HttpVerbEnum +from ansible_collections.cisco.nd.plugins.module_utils.types import IdentifierKey class NDEndpointBaseModel(BaseModel, ABC): @@ -129,3 +131,7 @@ def verb(self) -> HttpVerbEnum: None """ + + # NOTE: function to set endpoints attribute fields from identifiers -> acts as the bridge between Models and Endpoints for API Request Orchestration + def set_identifiers(self, identifier: IdentifierKey = None): + pass \ No newline at end of file diff --git a/plugins/module_utils/endpoints/enums.py b/plugins/module_utils/endpoints/enums.py new file mode 100644 index 00000000..92ae5783 --- /dev/null +++ b/plugins/module_utils/endpoints/enums.py @@ -0,0 +1,47 @@ +# Copyright: (c) 2026, Allen Robel (@allenrobel) +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +""" +Enums used in endpoints. +""" + +from __future__ import absolute_import, division, print_function + +from enum import Enum + + +class VerbEnum(str, Enum): + """ + # Summary + + Enum for HTTP verb values used in endpoints. + + ## Members + + - GET: Represents the HTTP GET method. + - POST: Represents the HTTP POST method. + - PUT: Represents the HTTP PUT method. + - DELETE: Represents the HTTP DELETE method. + """ + + GET = "GET" + POST = "POST" + PUT = "PUT" + DELETE = "DELETE" + + +class BooleanStringEnum(str, Enum): + """ + # Summary + + Enum for boolean string values used in query parameters. + + ## Members + + - TRUE: Represents the string "true". + - FALSE: Represents the string "false". + """ + + TRUE = "true" + FALSE = "false" diff --git a/plugins/module_utils/endpoints/mixins.py b/plugins/module_utils/endpoints/mixins.py index 47695611..e7f0620c 100644 --- a/plugins/module_utils/endpoints/mixins.py +++ b/plugins/module_utils/endpoints/mixins.py @@ -1,4 +1,5 @@ -# Copyright: (c) 2026, Allen Robel (@arobel) +# Copyright: (c) 2026, Allen Robel (@allenrobel) +# Copyright: (c) 2026, Gaspard Micol (@gmicol) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) """ @@ -10,7 +11,6 @@ from __future__ import absolute_import, annotations, division, print_function - from typing import Optional from ansible_collections.cisco.nd.plugins.module_utils.enums import BooleanStringEnum diff --git a/plugins/module_utils/endpoints/query_params.py b/plugins/module_utils/endpoints/query_params.py index 5bf8ff08..2cddd97d 100644 --- a/plugins/module_utils/endpoints/query_params.py +++ b/plugins/module_utils/endpoints/query_params.py @@ -11,12 +11,10 @@ from __future__ import absolute_import, annotations, division, print_function - from enum import Enum from typing import Optional, Protocol from urllib.parse import quote - from ansible_collections.cisco.nd.plugins.module_utils.common.pydantic_compat import ( BaseModel, Field, diff --git a/plugins/module_utils/endpoints/v1/infra/aaa_local_users.py b/plugins/module_utils/endpoints/v1/infra/aaa_local_users.py new file mode 100644 index 00000000..ea3b1f4b --- /dev/null +++ b/plugins/module_utils/endpoints/v1/infra/aaa_local_users.py @@ -0,0 +1,201 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) +# Copyright: (c) 2026, Allen Robel (@arobel) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +""" +ND Infra AAA Local Users endpoint models. + +This module contains endpoint definitions for AAA Local Users operations in the ND Infra API. +""" + +from __future__ import absolute_import, annotations, division, print_function + +from typing import Literal +from ansible_collections.cisco.nd.plugins.module_utils.common.pydantic_compat import Field +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.base import NDEndpointBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.mixins import LoginIdMixin +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.v1.infra.base_path import BasePath + +from ansible_collections.cisco.nd.plugins.module_utils.enums import HttpVerbEnum +from ansible_collections.cisco.nd.plugins.module_utils.types import IdentifierKey + + +class _EpInfraAaaLocalUsersBase(LoginIdMixin, NDEndpointBaseModel): + """ + Base class for ND Infra AAA Local Users endpoints. + + Provides common functionality for all HTTP methods on the /api/v1/infra/aaa/localUsers endpoint. + """ + + @property + def path(self) -> str: + """ + # Summary + + Build the /api/v1/infra/aaa/localUsers endpoint path. + + ## Returns + + - Complete endpoint path string, optionally including login_id + """ + if self.login_id is not None: + return BasePath.path("aaa", "localUsers", self.login_id) + return BasePath.path("aaa", "localUsers") + + def set_identifiers(self, identifier: IdentifierKey = None): + self.login_id = identifier + + +class EpInfraAaaLocalUsersGet(_EpInfraAaaLocalUsersBase): + """ + # Summary + + ND Infra AAA Local Users GET Endpoint + + ## Description + + Endpoint to retrieve local users from the ND Infra AAA service. + Optionally retrieve a specific local user by login_id. + + ## Path + + - /api/v1/infra/aaa/localUsers + - /api/v1/infra/aaa/localUsers/{login_id} + + ## Verb + + - GET + + ## Usage + + ```python + # Get all local users + request = EpInfraAaaLocalUsersGet() + path = request.path + verb = request.verb + + # Get specific local user + request = EpInfraAaaLocalUsersGet() + request.login_id = "admin" + path = request.path + verb = request.verb + ``` + """ + + class_name: Literal["EpInfraAaaLocalUsersGet"] = Field(default="EpInfraAaaLocalUsersGet", frozen=True, description="Class name for backward compatibility") + + @property + def verb(self) -> HttpVerbEnum: + """Return the HTTP verb for this endpoint.""" + return HttpVerbEnum.GET + + +class EpInfraAaaLocalUsersPost(_EpInfraAaaLocalUsersBase): + """ + # Summary + + ND Infra AAA Local Users POST Endpoint + + ## Description + + Endpoint to create a local user in the ND Infra AAA service. + + ## Path + + - /api/v1/infra/aaa/localUsers + + ## Verb + + - POST + + ## Usage + + ```python + request = EpInfraAaaLocalUsersPost() + path = request.path + verb = request.verb + ``` + """ + + class_name: Literal["EpInfraAaaLocalUsersPost"] = Field( + default="EpInfraAaaLocalUsersPost", frozen=True, description="Class name for backward compatibility" + ) + + @property + def verb(self) -> HttpVerbEnum: + """Return the HTTP verb for this endpoint.""" + return HttpVerbEnum.POST + + +class EpInfraAaaLocalUsersPut(_EpInfraAaaLocalUsersBase): + """ + # Summary + + ND Infra AAA Local Users PUT Endpoint + + ## Description + + Endpoint to update a local user in the ND Infra AAA service. + + ## Path + + - /api/v1/infra/aaa/localUsers/{login_id} + + ## Verb + + - PUT + + ## Usage + + ```python + request = EpInfraAaaLocalUsersPut() + request.login_id = "admin" + path = request.path + verb = request.verb + ``` + """ + + class_name: Literal["EpInfraAaaLocalUsersPut"] = Field(default="EpInfraAaaLocalUsersPut", frozen=True, description="Class name for backward compatibility") + + @property + def verb(self) -> HttpVerbEnum: + """Return the HTTP verb for this endpoint.""" + return HttpVerbEnum.PUT + + +class EpInfraAaaLocalUsersDelete(_EpInfraAaaLocalUsersBase): + """ + # Summary + + ND Infra AAA Local Users DELETE Endpoint + + ## Description + + Endpoint to delete a local user from the ND Infra AAA service. + + ## Path + + - /api/v1/infra/aaa/localUsers/{login_id} + + ## Verb + + - DELETE + + ## Usage + + ```python + request = EpInfraAaaLocalUsersDelete() + request.login_id = "admin" + path = request.path + verb = request.verb + ``` + """ + + class_name: Literal["EpInfraAaaLocalUsersDelete"] = Field( + default="EpInfraAaaLocalUsersDelete", frozen=True, description="Class name for backward compatibility" + ) + + @property + def verb(self) -> HttpVerbEnum: + """Return the HTTP verb for this endpoint.""" + return HttpVerbEnum.DELETE diff --git a/plugins/module_utils/endpoints/v1/infra/base_path.py b/plugins/module_utils/endpoints/v1/infra/base_path.py index f0612025..0db15ae9 100644 --- a/plugins/module_utils/endpoints/v1/infra/base_path.py +++ b/plugins/module_utils/endpoints/v1/infra/base_path.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2026, Allen Robel (@arobel) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) diff --git a/plugins/module_utils/endpoints/v1/infra/login.py b/plugins/module_utils/endpoints/v1/infra/login.py index 70968615..6fff9159 100644 --- a/plugins/module_utils/endpoints/v1/infra/login.py +++ b/plugins/module_utils/endpoints/v1/infra/login.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2026, Allen Robel (@arobel) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) diff --git a/plugins/module_utils/endpoints/v1/manage/base_path.py b/plugins/module_utils/endpoints/v1/manage/base_path.py index 5f043ced..52bb4e56 100644 --- a/plugins/module_utils/endpoints/v1/manage/base_path.py +++ b/plugins/module_utils/endpoints/v1/manage/base_path.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2026, Allen Robel (@arobel) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) diff --git a/plugins/module_utils/endpoints/v1/manage/manage_fabrics.py b/plugins/module_utils/endpoints/v1/manage/manage_fabrics.py new file mode 100644 index 00000000..5cb08213 --- /dev/null +++ b/plugins/module_utils/endpoints/v1/manage/manage_fabrics.py @@ -0,0 +1,525 @@ +# -*- coding: utf-8 -*- + +# Copyright: (c) 2026, Mike Wiebe (@mwiebe) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +""" +ND Manage Fabrics endpoint models. + +This module contains endpoint definitions for fabric-related operations +in the ND Manage API. + +## Endpoints + +- `EpApiV1ManageFabricsGet` - Get a specific fabric by name + (GET /api/v1/manage/fabrics/{fabric_name}) +- `EpApiV1ManageFabricsListGet` - List all fabrics with optional filtering + (GET /api/v1/manage/fabrics) +- `EpApiV1ManageFabricsPost` - Create a new fabric + (POST /api/v1/manage/fabrics) +- `EpApiV1ManageFabricsPut` - Update a specific fabric + (PUT /api/v1/manage/fabrics/{fabric_name}) +- `EpApiV1ManageFabricsDelete` - Delete a specific fabric + (DELETE /api/v1/manage/fabrics/{fabric_name}) +- `EpApiV1ManageFabricsSummaryGet` - Get summary for a specific fabric + (GET /api/v1/manage/fabrics/{fabric_name}/summary) +""" + +from __future__ import absolute_import, annotations, division, print_function + +# from plugins.module_utils.endpoints.base import NDBaseEndpoint + +# pylint: disable=invalid-name +__metaclass__ = type +# pylint: enable=inFinal, valid-name + +from typing import ClassVar, Literal, Optional, Final + +from ansible_collections.cisco.nd.plugins.module_utils.enums import HttpVerbEnum +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.v1.manage.base_path import BasePath +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.mixins import FabricNameMixin +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.base import NDEndpointBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.query_params import EndpointQueryParams +from ansible_collections.cisco.nd.plugins.module_utils.common.pydantic_compat import BaseModel, ConfigDict, Field +from ansible_collections.cisco.nd.plugins.module_utils.types import IdentifierKey + + +class FabricsEndpointParams(EndpointQueryParams): + """ + # Summary + + Endpoint-specific query parameters for the fabrics endpoint. + + ## Parameters + + - cluster_name: Name of the target Nexus Dashboard cluster to execute this API, + in a multi-cluster deployment (optional) + + ## Usage + + ```python + params = FabricsEndpointParams(cluster_name="cluster1") + query_string = params.to_query_string() + # Returns: "clusterName=cluster1" + ``` + """ + + cluster_name: Optional[str] = Field( + default=None, + min_length=1, + description="Name of the target Nexus Dashboard cluster to execute this API, in a multi-cluster deployment", + ) + + +class _EpManageFabricsBase(FabricNameMixin, NDEndpointBaseModel): + """ + Base class for ND Manage Fabrics endpoints. + + Provides common functionality for all HTTP methods on the + /api/v1/manage/fabrics endpoint. + + Subclasses may override: + - ``_require_fabric_name``: set to ``False`` for collection-level endpoints + (list, create) that do not include a fabric name in the path. + - ``_path_suffix``: set to a non-empty string to append an extra segment + after the fabric name (e.g. ``"summary"``). Only used when + ``_require_fabric_name`` is ``True``. + """ + + _require_fabric_name: ClassVar[bool] = True + _path_suffix: ClassVar[Optional[str]] = None + + endpoint_params: EndpointQueryParams = Field( + default_factory=EndpointQueryParams, description="Endpoint-specific query parameters" + ) + + def set_identifiers(self, identifier: IdentifierKey = None): + self.fabric_name = identifier + + @property + def path(self) -> str: + """ + # Summary + + Build the endpoint path with optional fabric name, path suffix, and + query string. + + ## Returns + + - Complete endpoint path string + + ## Raises + + - `ValueError` if `fabric_name` is required but not set + """ + if self._require_fabric_name and self.fabric_name is None: + raise ValueError( + f"{type(self).__name__}.path: fabric_name must be set before accessing path." + ) + segments = ["fabrics"] + if self.fabric_name is not None: + segments.append(self.fabric_name) + if self._path_suffix: + segments.append(self._path_suffix) + base_path = BasePath.path(*segments) + query_string = self.endpoint_params.to_query_string() + if query_string: + return f"{base_path}?{query_string}" + return base_path + +class EpManageFabricsGet(_EpManageFabricsBase): + """ + # Summary + + ND Manage Fabrics GET Endpoint + + ## Description + + Endpoint to retrieve details for a specific named fabric from the ND Manage service. + The fabric name is a required path parameter. Optionally filter by cluster name + using the clusterName query parameter in multi-cluster deployments. + + ## Path + + - /api/v1/manage/fabrics/{fabric_name} + - /api/v1/manage/fabrics/{fabric_name}?clusterName=cluster1 + + ## Verb + + - GET + + ## Raises + + - `ValueError` if `fabric_name` is not set when accessing `path` + + ## Usage + + ```python + # Get details for a specific fabric + request = EpApiV1ManageFabricsGet() + request.fabric_name = "my-fabric" + path = request.path + verb = request.verb + # Path will be: /api/v1/manage/fabrics/my-fabric + + # Get fabric details targeting a specific cluster in a multi-cluster deployment + request = EpApiV1ManageFabricsGet() + request.fabric_name = "my-fabric" + request.endpoint_params.cluster_name = "cluster1" + path = request.path + verb = request.verb + # Path will be: /api/v1/manage/fabrics/my-fabric?clusterName=cluster1 + ``` + """ + + class_name: Literal["EpApiV1ManageFabricsGet"] = Field( + default="EpApiV1ManageFabricsGet", description="Class name for backward compatibility" + ) + + endpoint_params: FabricsEndpointParams = Field( + default_factory=FabricsEndpointParams, description="Endpoint-specific query parameters" + ) + + @property + def verb(self) -> HttpVerbEnum: + """Return the HTTP verb for this endpoint.""" + return HttpVerbEnum.GET + + +class FabricsListEndpointParams(EndpointQueryParams): + """ + # Summary + + Query parameters for the ``GET /api/v1/manage/fabrics`` list endpoint. + + ## Parameters + + - cluster_name: Name of the target Nexus Dashboard cluster (multi-cluster deployments) + - category: Filter by fabric category (``"fabric"`` or ``"fabricGroup"``) + - filter: Lucene-format filter string + - max: Maximum number of records to return + - offset: Number of records to skip for pagination + - sort: Sort field with optional ``:desc`` suffix + + ## Usage + + ```python + params = FabricsListEndpointParams(category="fabric", max=10, offset=0) + query_string = params.to_query_string() + # Returns: "category=fabric&max=10&offset=0" + ``` + """ + + cluster_name: Optional[str] = Field( + default=None, + min_length=1, + description="Name of the target Nexus Dashboard cluster to execute this API, in a multi-cluster deployment", + ) + + category: Optional[str] = Field( + default=None, + description="Filter by category of fabric (fabric or fabricGroup)", + ) + + filter: Optional[str] = Field( + default=None, + description="Lucene format filter - Filter the response based on this filter field", + ) + + max: Optional[int] = Field( + default=None, + ge=1, + description="Number of records to return", + ) + + offset: Optional[int] = Field( + default=None, + ge=0, + description="Number of records to skip for pagination", + ) + + sort: Optional[str] = Field( + default=None, + description="Sort the records by the declared fields in either ascending (default) or descending (:desc) order", + ) + + +class EpManageFabricsListGet(_EpManageFabricsBase): + """ + # Summary + + ND Manage Fabrics List GET Endpoint + + ## Description + + Endpoint to list all fabrics from the ND Manage service. + Supports optional query parameters for filtering, pagination, and sorting. + + ## Path + + - ``/api/v1/manage/fabrics`` + - ``/api/v1/manage/fabrics?category=fabric&max=10`` + + ## Verb + + - GET + + ## Raises + + - None + + ## Usage + + ```python + # List all fabrics + ep = EpApiV1ManageFabricsListGet() + path = ep.path + verb = ep.verb + # Path: /api/v1/manage/fabrics + + # List fabrics with filtering and pagination + ep = EpApiV1ManageFabricsListGet() + ep.endpoint_params.category = "fabric" + ep.endpoint_params.max = 10 + path = ep.path + # Path: /api/v1/manage/fabrics?category=fabric&max=10 + ``` + """ + + _require_fabric_name: ClassVar[bool] = False + + class_name: Literal["EpApiV1ManageFabricsListGet"] = Field( + default="EpApiV1ManageFabricsListGet", description="Class name for backward compatibility" + ) + + endpoint_params: FabricsListEndpointParams = Field( + default_factory=FabricsListEndpointParams, description="Endpoint-specific query parameters" + ) + + @property + def verb(self) -> HttpVerbEnum: + """Return the HTTP verb for this endpoint.""" + return HttpVerbEnum.GET + + +class EpManageFabricsPost(_EpManageFabricsBase): + """ + # Summary + + ND Manage Fabrics POST Endpoint + + ## Description + + Endpoint to create a new fabric via the ND Manage service. + The request body must conform to the ``baseFabric`` schema (discriminated + by ``category``). For standard fabrics the category is ``"fabric"`` and + the body includes ``name`` plus fabric-specific properties such as + ``location``, ``licenseTier``, ``telemetryCollection``, etc. + + ## Path + + - ``/api/v1/manage/fabrics`` + - ``/api/v1/manage/fabrics?clusterName=cluster1`` + + ## Verb + + - POST + + ## Request Body (application/json) + + ``baseFabric`` schema — for a standard fabric use ``category: "fabric"`` + with at minimum: + + - ``name`` (str, required): Name of the fabric + - ``category`` (str, required): ``"fabric"`` + + ## Raises + + - None + + ## Usage + + ```python + ep = EpApiV1ManageFabricsPost() + rest_send.path = ep.path + rest_send.verb = ep.verb + rest_send.payload = { + "name": "my-fabric", + "category": "fabric", + "telemetryCollection": True, + "telemetryCollectionType": "inBand", + } + ``` + """ + + _require_fabric_name: ClassVar[bool] = False + + class_name: Literal["EpApiV1ManageFabricsPost"] = Field( + default="EpApiV1ManageFabricsPost", description="Class name for backward compatibility" + ) + + endpoint_params: FabricsEndpointParams = Field( + default_factory=FabricsEndpointParams, description="Endpoint-specific query parameters" + ) + + @property + def verb(self) -> HttpVerbEnum: + """Return the HTTP verb for this endpoint.""" + return HttpVerbEnum.POST + + +class EpManageFabricsPut(_EpManageFabricsBase): + """ + # Summary + + ND Manage Fabrics PUT Endpoint + + ## Description + + Endpoint to update an existing fabric via the ND Manage service. + The fabric name is a required path parameter. The request body must + conform to the ``baseFabric`` schema (same shape as POST/create). + + ## Path + + - ``/api/v1/manage/fabrics/{fabric_name}`` + - ``/api/v1/manage/fabrics/{fabric_name}?clusterName=cluster1`` + + ## Verb + + - PUT + + ## Request Body (application/json) + + ``baseFabric`` schema — same as create (POST). + + ## Raises + + - `ValueError` if `fabric_name` is not set when accessing `path` + + ## Usage + + ```python + ep = EpApiV1ManageFabricsPut() + ep.fabric_name = "my-fabric" + rest_send.path = ep.path + rest_send.verb = ep.verb + rest_send.payload = { + "name": "my-fabric", + "category": "fabric", + "telemetryCollection": False, + } + ``` + """ + + class_name: Literal["EpApiV1ManageFabricsPut"] = Field( + default="EpApiV1ManageFabricsPut", description="Class name for backward compatibility" + ) + + endpoint_params: FabricsEndpointParams = Field( + default_factory=FabricsEndpointParams, description="Endpoint-specific query parameters" + ) + + @property + def verb(self) -> HttpVerbEnum: + """Return the HTTP verb for this endpoint.""" + return HttpVerbEnum.PUT + + +class EpManageFabricsDelete(_EpManageFabricsBase): + """ + # Summary + + ND Manage Fabrics DELETE Endpoint + + ## Description + + Endpoint to delete a specific fabric from the ND Manage service. + The fabric name is a required path parameter. + + ## Path + + - ``/api/v1/manage/fabrics/{fabric_name}`` + - ``/api/v1/manage/fabrics/{fabric_name}?clusterName=cluster1`` + + ## Verb + + - DELETE + + ## Raises + + - `ValueError` if `fabric_name` is not set when accessing `path` + + ## Usage + + ```python + ep = EpApiV1ManageFabricsDelete() + ep.fabric_name = "my-fabric" + rest_send.path = ep.path + rest_send.verb = ep.verb + ``` + """ + + class_name: Literal["EpApiV1ManageFabricsDelete"] = Field( + default="EpApiV1ManageFabricsDelete", description="Class name for backward compatibility" + ) + + endpoint_params: FabricsEndpointParams = Field( + default_factory=FabricsEndpointParams, description="Endpoint-specific query parameters" + ) + + @property + def verb(self) -> HttpVerbEnum: + """Return the HTTP verb for this endpoint.""" + return HttpVerbEnum.DELETE + + +class EpManageFabricsSummaryGet(_EpManageFabricsBase): + """ + # Summary + + ND Manage Fabrics Summary GET Endpoint + + ## Description + + Endpoint to retrieve summary information for a specific fabric from + the ND Manage service. The fabric name is a required path parameter. + + ## Path + + - ``/api/v1/manage/fabrics/{fabric_name}/summary`` + - ``/api/v1/manage/fabrics/{fabric_name}/summary?clusterName=cluster1`` + + ## Verb + + - GET + + ## Raises + + - `ValueError` if `fabric_name` is not set when accessing `path` + + ## Usage + + ```python + ep = EpApiV1ManageFabricsSummaryGet() + ep.fabric_name = "my-fabric" + path = ep.path + verb = ep.verb + # Path: /api/v1/manage/fabrics/my-fabric/summary + ``` + """ + + class_name: Literal["EpApiV1ManageFabricsSummaryGet"] = Field( + default="EpApiV1ManageFabricsSummaryGet", description="Class name for backward compatibility" + ) + + _path_suffix: ClassVar[Optional[str]] = "summary" + + endpoint_params: FabricsEndpointParams = Field( + default_factory=FabricsEndpointParams, description="Endpoint-specific query parameters" + ) + + @property + def verb(self) -> HttpVerbEnum: + """Return the HTTP verb for this endpoint.""" + return HttpVerbEnum.GET diff --git a/plugins/module_utils/enums.py b/plugins/module_utils/enums.py index 55d1f1ac..83f1f76d 100644 --- a/plugins/module_utils/enums.py +++ b/plugins/module_utils/enums.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # pylint: disable=wrong-import-position # pylint: disable=missing-module-docstring # Copyright: (c) 2026, Allen Robel (@allenrobel) @@ -21,10 +20,6 @@ # fmt: on # isort: on -# pylint: disable=invalid-name -__metaclass__ = type -# pylint: enable=invalid-name - from enum import Enum diff --git a/plugins/module_utils/models/base.py b/plugins/module_utils/models/base.py new file mode 100644 index 00000000..a62a12b1 --- /dev/null +++ b/plugins/module_utils/models/base.py @@ -0,0 +1,225 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +from abc import ABC +from ansible_collections.cisco.nd.plugins.module_utils.common.pydantic_compat import BaseModel, ConfigDict +from typing import List, Dict, Any, ClassVar, Set, Tuple, Union, Literal, Optional +from ansible_collections.cisco.nd.plugins.module_utils.utils import issubset + + +class NDBaseModel(BaseModel, ABC): + """ + Base model for all Nexus Dashboard API objects. + + Class-level configuration attributes: + identifiers: List of field names used to uniquely identify this object. + identifier_strategy: How identifiers are interpreted. + exclude_from_diff: Fields excluded from diff comparisons. + unwanted_keys: Keys to strip from API responses before processing. + payload_nested_fields: Mapping of {payload_key: [field_names]} for fields + that should be grouped under a nested key in payload mode but remain + flat in config mode. + payload_exclude_fields: Fields to exclude from payload output + (e.g., because they are restructured into nested keys). + config_exclude_fields: Fields to exclude from config output + (e.g., computed payload-only structures). + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + use_enum_values=True, + validate_assignment=True, + populate_by_name=True, + arbitrary_types_allowed=True, + extra="ignore", + ) + + # --- Identifier Configuration --- + + identifiers: ClassVar[Optional[List[str]]] = None + identifier_strategy: ClassVar[Optional[Literal["single", "composite", "hierarchical", "singleton"]]] = "singleton" + + # --- Serialization Configuration --- + + exclude_from_diff: ClassVar[Set[str]] = set() + unwanted_keys: ClassVar[List] = [] + + # Declarative nested-field grouping for payload mode + # e.g., {"passwordPolicy": ["reuse_limitation", "time_interval_limitation"]} + # means: in payload mode, remove these fields from top level and nest them + # under "passwordPolicy" with their alias names. + payload_nested_fields: ClassVar[Dict[str, List[str]]] = {} + + # Fields to explicitly exclude per mode + payload_exclude_fields: ClassVar[Set[str]] = set() + config_exclude_fields: ClassVar[Set[str]] = set() + + # --- Subclass Validation --- + + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + + # Skip enforcement for nested models + if cls.__name__ == "NDNestedModel" or any(base.__name__ == "NDNestedModel" for base in cls.__mro__): + return + + if not hasattr(cls, "identifiers") or cls.identifiers is None: + raise ValueError(f"Class {cls.__name__} must define 'identifiers'. " f"Example: identifiers: ClassVar[Optional[List[str]]] = ['login_id']") + if not hasattr(cls, "identifier_strategy") or cls.identifier_strategy is None: + raise ValueError(f"Class {cls.__name__} must define 'identifier_strategy'. " f"Example: identifier_strategy: ClassVar[...] = 'single'") + + # --- Core Serialization --- + + def _build_payload_nested(self, data: Dict[str, Any]) -> Dict[str, Any]: + """ + Apply payload_nested_fields: pull specified fields out of the top-level + dict and group them under their declared parent key. + """ + if not self.payload_nested_fields: + return data + + result = dict(data) + + for nested_key, field_names in self.payload_nested_fields.items(): + nested_dict = {} + for field_name in field_names: + # Resolve the alias for this field + field_info = self.__class__.model_fields.get(field_name) + if field_info is None: + continue + + alias = field_info.alias or field_name + + # Pull value from the serialized data (which uses aliases in payload mode) + if alias in result: + nested_dict[alias] = result.pop(alias) + + if nested_dict: + result[nested_key] = nested_dict + + return result + + def to_payload(self, **kwargs) -> Dict[str, Any]: + """Convert model to API payload format (aliased keys, nested structures).""" + data = self.model_dump( + by_alias=True, + exclude_none=True, + mode="json", + context={"mode": "payload"}, + exclude=self.payload_exclude_fields or None, + **kwargs, + ) + return self._build_payload_nested(data) + + def to_config(self, **kwargs) -> Dict[str, Any]: + """Convert model to Ansible config format (Python field names, flat structure).""" + return self.model_dump( + by_alias=False, + exclude_none=True, + context={"mode": "config"}, + exclude=self.config_exclude_fields or None, + **kwargs, + ) + + # --- Core Deserialization --- + + @classmethod + def from_response(cls, response: Dict[str, Any], **kwargs) -> "NDBaseModel": + """Create model instance from API response dict.""" + return cls.model_validate(response, by_alias=True, **kwargs) + + @classmethod + def from_config(cls, ansible_config: Dict[str, Any], **kwargs) -> "NDBaseModel": + """Create model instance from Ansible config dict.""" + return cls.model_validate(ansible_config, by_name=True, **kwargs) + + # --- Identifier Access --- + + def get_identifier_value(self) -> Optional[Union[str, int, Tuple[Any, ...]]]: + """ + Extract identifier value(s) based on the configured strategy. + + Returns: + - single: The field value + - composite: Tuple of all field values + - hierarchical: Tuple of (field_name, value) for first non-None field + - singleton: None + """ + strategy = self.identifier_strategy + + if strategy == "singleton": + return None + + if not self.identifiers: + raise ValueError(f"{self.__class__.__name__} has strategy '{strategy}' but no identifiers defined.") + + if strategy == "single": + value = getattr(self, self.identifiers[0], None) + if value is None: + raise ValueError(f"Single identifier field '{self.identifiers[0]}' is None") + return value + + elif strategy == "composite": + values = [] + missing = [] + for field in self.identifiers: + value = getattr(self, field, None) + if value is None: + missing.append(field) + values.append(value) + if missing: + raise ValueError(f"Composite identifier fields {missing} are None. " f"All required: {self.identifiers}") + return tuple(values) + + elif strategy == "hierarchical": + for field in self.identifiers: + value = getattr(self, field, None) + if value is not None: + return (field, value) + raise ValueError(f"No non-None value in hierarchical fields {self.identifiers}") + + else: + raise ValueError(f"Unknown identifier strategy: {strategy}") + + # --- Diff & Merge --- + + def to_diff_dict(self, **kwargs) -> Dict[str, Any]: + """Export for diff comparison, excluding sensitive fields.""" + return self.model_dump( + by_alias=True, + exclude_none=True, + exclude=self.exclude_from_diff or None, + mode="json", + **kwargs, + ) + + def get_diff(self, other: "NDBaseModel") -> bool: + """Diff comparison.""" + self_data = self.to_diff_dict() + other_data = other.to_diff_dict() + return issubset(other_data, self_data) + + def merge(self, other: "NDBaseModel") -> "NDBaseModel": + """ + Merge another model's non-None values into this instance. + Recursively merges nested NDBaseModel fields. + + Returns self for chaining. + """ + if not isinstance(other, type(self)): + raise TypeError(f"Cannot merge {type(other).__name__} into {type(self).__name__}. " f"Both must be the same type.") + + for field_name, value in other: + if value is None: + continue + + current = getattr(self, field_name) + if isinstance(current, NDBaseModel) and isinstance(value, NDBaseModel): + current.merge(value) + else: + setattr(self, field_name, value) + + return self diff --git a/plugins/module_utils/models/local_user/local_user.py b/plugins/module_utils/models/local_user/local_user.py new file mode 100644 index 00000000..6d4960f3 --- /dev/null +++ b/plugins/module_utils/models/local_user/local_user.py @@ -0,0 +1,228 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +from typing import List, Dict, Any, Optional, ClassVar, Literal +from ansible_collections.cisco.nd.plugins.module_utils.common.pydantic_compat import ( + Field, + SecretStr, + model_serializer, + field_serializer, + field_validator, + model_validator, + FieldSerializationInfo, + SerializationInfo, +) +from ansible_collections.cisco.nd.plugins.module_utils.models.base import NDBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.models.nested import NDNestedModel +from ansible_collections.cisco.nd.plugins.module_utils.constants import NDConstantMapping + +USER_ROLES_MAPPING = NDConstantMapping( + { + "fabric_admin": "fabric-admin", + "observer": "observer", + "super_admin": "super-admin", + "support_engineer": "support-engineer", + "approver": "approver", + "designer": "designer", + } +) + + +class LocalUserSecurityDomainModel(NDNestedModel): + """ + Security domain with assigned roles for a local user. + + Canonical form (config): {"name": "all", "roles": ["observer", "support_engineer"]} + API payload form: {"all": {"roles": ["observer", "support-engineer"]}} + """ + + name: str = Field(alias="name") + roles: Optional[List[str]] = Field(default=None, alias="roles") + + @model_serializer() + def serialize(self, info: SerializationInfo) -> Any: + mode = (info.context or {}).get("mode", "payload") + + if mode == "config": + result = {"name": self.name} + if self.roles is not None: + result["roles"] = list(self.roles) + return result + + # Payload mode: nested dict with API role names + api_roles = [USER_ROLES_MAPPING.get_dict().get(role, role) for role in (self.roles or [])] + return {self.name: {"roles": api_roles}} + + +class LocalUserModel(NDBaseModel): + """ + Local user configuration for Nexus Dashboard. + + Identifier: login_id (single) + + Serialization notes: + - In payload mode, `reuse_limitation` and `time_interval_limitation` + are nested under `passwordPolicy` (handled by base class via + `payload_nested_fields`). + - In config mode, they remain as flat top-level fields. + - `security_domains` serializes as a nested dict in payload mode + and a flat list of dicts in config mode. + """ + + # --- Identifier Configuration --- + + identifiers: ClassVar[Optional[List[str]]] = ["login_id"] + identifier_strategy: ClassVar[Optional[Literal["single", "composite", "hierarchical", "singleton"]]] = "single" + + # --- Serialization Configuration --- + + exclude_from_diff: ClassVar[set] = {"user_password"} + unwanted_keys: ClassVar[List] = [ + ["passwordPolicy", "passwordChangeTime"], + ["userID"], + ] + + # In payload mode, nest these fields under "passwordPolicy" + payload_nested_fields: ClassVar[Dict[str, List[str]]] = { + "passwordPolicy": ["reuse_limitation", "time_interval_limitation"], + } + + # --- Fields --- + + login_id: str = Field(alias="loginID") + email: Optional[str] = Field(default=None, alias="email") + first_name: Optional[str] = Field(default=None, alias="firstName") + last_name: Optional[str] = Field(default=None, alias="lastName") + user_password: Optional[SecretStr] = Field(default=None, alias="password") + reuse_limitation: Optional[int] = Field(default=None, alias="reuseLimitation") + time_interval_limitation: Optional[int] = Field(default=None, alias="timeIntervalLimitation") + security_domains: Optional[List[LocalUserSecurityDomainModel]] = Field(default=None, alias="rbac") + remote_id_claim: Optional[str] = Field(default=None, alias="remoteIDClaim") + remote_user_authorization: Optional[bool] = Field(default=None, alias="xLaunch") + + # --- Serializers --- + + @field_serializer("user_password") + def serialize_password(self, value: Optional[SecretStr]) -> Optional[str]: + return value.get_secret_value() if value else None + + @field_serializer("security_domains") + def serialize_security_domains( + self, + value: Optional[List[LocalUserSecurityDomainModel]], + info: FieldSerializationInfo, + ) -> Any: + if not value: + return None + + mode = (info.context or {}).get("mode", "payload") + + if mode == "config": + return [domain.model_dump(context=info.context) for domain in value] + + # Payload mode: merge all domain dicts into {"domains": {...}} + domains_dict = {} + for domain in value: + domains_dict.update(domain.model_dump(context=info.context)) + return {"domains": domains_dict} + + # --- Validators (Deserialization) --- + + @model_validator(mode="before") + @classmethod + def flatten_password_policy(cls, data: Any) -> Any: + """ + Flatten nested passwordPolicy from API response into top-level fields. + This is the inverse of the payload_nested_fields nesting. + """ + if not isinstance(data, dict): + return data + + policy = data.pop("passwordPolicy", None) + if isinstance(policy, dict): + if "reuseLimitation" in policy: + data.setdefault("reuseLimitation", policy["reuseLimitation"]) + if "timeIntervalLimitation" in policy: + data.setdefault("timeIntervalLimitation", policy["timeIntervalLimitation"]) + + return data + + @field_validator("security_domains", mode="before") + @classmethod + def normalize_security_domains(cls, value: Any) -> Optional[List[Dict]]: + """ + Accept security_domains in either format: + - List of dicts (Ansible config): [{"name": "all", "roles": [...]}] + - Nested dict (API response): {"domains": {"all": {"roles": [...]}}} + Always normalizes to the list-of-dicts form for model storage. + """ + if value is None: + return None + + # Already normalized (from Ansible config) + if isinstance(value, list): + return value + + # API response format + if isinstance(value, dict) and "domains" in value: + reverse_mapping = {v: k for k, v in USER_ROLES_MAPPING.get_dict().items()} + return [ + { + "name": domain_name, + "roles": [reverse_mapping.get(role, role) for role in domain_data.get("roles", [])], + } + for domain_name, domain_data in value["domains"].items() + ] + + return value + + # --- Argument Spec --- + + @classmethod + def get_argument_spec(cls) -> Dict: + return dict( + config=dict( + type="list", + elements="dict", + required=True, + options=dict( + email=dict(type="str"), + login_id=dict(type="str", required=True), + first_name=dict(type="str"), + last_name=dict(type="str"), + user_password=dict(type="str", no_log=True), + reuse_limitation=dict(type="int"), + time_interval_limitation=dict(type="int"), + security_domains=dict( + type="list", + elements="dict", + options=dict( + name=dict( + type="str", + required=True, + aliases=[ + "security_domain_name", + "domain_name", + ], + ), + roles=dict( + type="list", + elements="str", + choices=USER_ROLES_MAPPING.get_original_data(), + ), + ), + aliases=["domains"], + ), + remote_id_claim=dict(type="str"), + remote_user_authorization=dict(type="bool"), + ), + ), + state=dict( + type="str", + default="merged", + choices=["merged", "replaced", "overridden", "deleted"], + ), + ) diff --git a/plugins/module_utils/models/manage_fabric/enums.py b/plugins/module_utils/models/manage_fabric/enums.py new file mode 100644 index 00000000..4004b2fb --- /dev/null +++ b/plugins/module_utils/models/manage_fabric/enums.py @@ -0,0 +1,251 @@ +# -*- coding: utf-8 -*- +# pylint: disable=wrong-import-position +# pylint: disable=missing-module-docstring +# Copyright: (c) 2026, Mike Wiebe (@mwiebe) +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) +""" +# Summary + +Enum definitions for Nexus Dashboard Ansible modules. + +## Enums + +- HttpVerbEnum: Enum for HTTP verb values used in endpoints. +- OperationType: Enum for operation types used by Results to determine if changes have occurred. +""" + +from __future__ import absolute_import, annotations, division, print_function + +# pylint: disable=invalid-name +__metaclass__ = type +# pylint: enable=invalid-name + +from enum import Enum + +class FabricTypeEnum(str, Enum): + """ + # Summary + + Enumeration of supported fabric types for discriminated union. + + ## Values + + - `VXLAN_IBGP` - VXLAN fabric with iBGP overlay + - `VXLAN_EBGP` - VXLAN fabric with eBGP overlay + """ + + VXLAN_IBGP = "vxlanIbgp" + VXLAN_EBGP = "vxlanEbgp" + VXLAN_EXTERNAL = "vxlanExternal" + + +class AlertSuspendEnum(str, Enum): + """ + # Summary + + Enumeration for alert suspension states. + + ## Values + + - `ENABLED` - Alerts are enabled + - `DISABLED` - Alerts are disabled + """ + + ENABLED = "enabled" + DISABLED = "disabled" + + +class LicenseTierEnum(str, Enum): + """ + # Summary + + Enumeration for license tier options. + + ## Values + + - `ESSENTIALS` - Essentials license tier + - `PREMIER` - Premier license tier + """ + + ESSENTIALS = "essentials" + PREMIER = "premier" + + +class ReplicationModeEnum(str, Enum): + """ + # Summary + + Enumeration for replication modes. + + ## Values + + - `MULTICAST` - Multicast replication + - `INGRESS` - Ingress replication + """ + + MULTICAST = "multicast" + INGRESS = "ingress" + + +class OverlayModeEnum(str, Enum): + """ + # Summary + + Enumeration for overlay modes. + + ## Values + + - `CLI` - CLI based configuration + - `CONFIG_PROFILE` - Configuration profile based + """ + + CLI = "cli" + CONFIG_PROFILE = "config-profile" + + +class LinkStateRoutingProtocolEnum(str, Enum): + """ + # Summary + + Enumeration for underlay routing protocols. + + ## Values + + - `OSPF` - Open Shortest Path First + - `ISIS` - Intermediate System to Intermediate System + """ + + OSPF = "ospf" + ISIS = "isis" + + +class CoppPolicyEnum(str, Enum): + """ + # Summary + + Enumeration for CoPP policy options. + """ + + DENSE = "dense" + LENIENT = "lenient" + MODERATE = "moderate" + STRICT = "strict" + MANUAL = "manual" + + +class FabricInterfaceTypeEnum(str, Enum): + """ + # Summary + + Enumeration for fabric interface types. + """ + + P2P = "p2p" + UNNUMBERED = "unNumbered" + + +class GreenfieldDebugFlagEnum(str, Enum): + """ + # Summary + + Enumeration for greenfield debug flag. + """ + + ENABLE = "enable" + DISABLE = "disable" + + +class IsisLevelEnum(str, Enum): + """ + # Summary + + Enumeration for IS-IS levels. + """ + + LEVEL_1 = "level-1" + LEVEL_2 = "level-2" + + +class SecurityGroupStatusEnum(str, Enum): + """ + # Summary + + Enumeration for security group status. + """ + + ENABLED = "enabled" + ENABLED_STRICT = "enabledStrict" + ENABLED_LOOSE = "enabledLoose" + ENABLE_PENDING = "enablePending" + ENABLE_PENDING_STRICT = "enablePendingStrict" + ENABLE_PENDING_LOOSE = "enablePendingLoose" + DISABLE_PENDING = "disablePending" + DISABLED = "disabled" + + +class StpRootOptionEnum(str, Enum): + """ + # Summary + + Enumeration for STP root options. + """ + + RPVST_PLUS = "rpvst+" + MST = "mst" + UNMANAGED = "unmanaged" + + +class VpcPeerKeepAliveOptionEnum(str, Enum): + """ + # Summary + + Enumeration for vPC peer keep-alive options. + """ + + LOOPBACK = "loopback" + MANAGEMENT = "management" + + +class DhcpProtocolVersionEnum(str, Enum): + """ + # Summary + + Enumeration for DHCP protocol version options. + """ + + DHCPV4 = "dhcpv4" + DHCPV6 = "dhcpv6" + + +class PowerRedundancyModeEnum(str, Enum): + """ + # Summary + + Enumeration for power redundancy mode options. + """ + + REDUNDANT = "redundant" + COMBINED = "combined" + INPUT_SRC_REDUNDANT = "inputSrcRedundant" + + +class BgpAsModeEnum(str, Enum): + """ + # Summary + + Enumeration for eBGP BGP AS mode options. + """ + + MULTI_AS = "multiAS" + SAME_TIER_AS = "sameTierAS" + + +class FirstHopRedundancyProtocolEnum(str, Enum): + """ + # Summary + + Enumeration for first-hop redundancy protocol options. + """ + + HSRP = "hsrp" + VRRP = "vrrp" diff --git a/plugins/module_utils/models/manage_fabric/manage_fabric_ebgp.py b/plugins/module_utils/models/manage_fabric/manage_fabric_ebgp.py new file mode 100644 index 00000000..8894941c --- /dev/null +++ b/plugins/module_utils/models/manage_fabric/manage_fabric_ebgp.py @@ -0,0 +1,838 @@ +# -*- coding: utf-8 -*- + +# Copyright: (c) 2026, Mike Wiebe (@mwiebe) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +# pylint: disable=invalid-name +__metaclass__ = type +# pylint: enable=invalid-name + +import re +from typing import List, Dict, Any, Optional, ClassVar, Literal + +from ansible_collections.cisco.nd.plugins.module_utils.models.base import NDBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.models.nested import NDNestedModel +from ansible_collections.cisco.nd.plugins.module_utils.common.pydantic_compat import ( + BaseModel, + ConfigDict, + Field, + field_validator, + model_validator, +) +from ansible_collections.cisco.nd.plugins.module_utils.models.manage_fabric.enums import ( + FabricTypeEnum, + AlertSuspendEnum, + LicenseTierEnum, + OverlayModeEnum, + ReplicationModeEnum, + CoppPolicyEnum, + GreenfieldDebugFlagEnum, + VpcPeerKeepAliveOptionEnum, + BgpAsModeEnum, + FirstHopRedundancyProtocolEnum, +) +# Re-use shared nested models from the iBGP module +from ansible_collections.cisco.nd.plugins.module_utils.models.manage_fabric.manage_fabric_ibgp import ( + LocationModel, + NetflowExporterModel, + NetflowRecordModel, + NetflowMonitorModel, + NetflowSettingsModel, + BootstrapSubnetModel, + TelemetryFlowCollectionModel, + TelemetryMicroburstModel, + TelemetryAnalysisSettingsModel, + TelemetryEnergyManagementModel, + TelemetryNasExportSettingsModel, + TelemetryNasModel, + TelemetrySettingsModel, + ExternalStreamingSettingsModel, +) + + +""" +# Comprehensive Pydantic models for eBGP VXLAN fabric management via Nexus Dashboard + +This module provides Pydantic models for creating, updating, and deleting +eBGP VXLAN fabrics through the Nexus Dashboard Fabric Controller (NDFC) API. + +## Models Overview + +- `VxlanEbgpManagementModel` - eBGP VXLAN specific management settings +- `FabricEbgpModel` - Complete fabric creation model for eBGP fabrics +- `FabricEbgpDeleteModel` - Fabric deletion model + +## Usage + +```python +# Create a new eBGP VXLAN fabric +fabric_data = { + "name": "MyEbgpFabric", + "management": { + "type": "vxlanEbgp", + "bgpAsnAutoAllocation": True, + "bgpAsnRange": "65000-65535" + } +} +fabric = FabricEbgpModel(**fabric_data) +``` +""" + +# Regex from OpenAPI schema: bgpAsn accepts plain integers (1-4294967295) and +# dotted four-byte ASN notation (1-65535).(0-65535) +_BGP_ASN_RE = re.compile( + r"^(([1-9]{1}[0-9]{0,8}|[1-3]{1}[0-9]{1,9}|[4]{1}([0-1]{1}[0-9]{8}|[2]{1}([0-8]{1}[0-9]{7}|[9]{1}([0-3]{1}[0-9]{6}|[4]{1}([0-8]{1}[0-9]{5}|[9]{1}([0-5]{1}[0-9]{4}|[6]{1}([0-6]{1}[0-9]{3}|[7]{1}([0-1]{1}[0-9]{2}|[2]{1}([0-8]{1}[0-9]{1}|[9]{1}[0-5]{1})))))))))|([1-5]\d{4}|[1-9]\d{0,3}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])(\.([1-5]\d{4}|[1-9]\d{0,3}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]|0))?)$" +) + + +class VxlanEbgpManagementModel(NDNestedModel): + """ + # Summary + + Comprehensive eBGP VXLAN fabric management configuration. + + This model contains all settings specific to eBGP VXLAN fabric types including + overlay configuration, BGP AS allocation, multicast settings, and advanced features. + + ## Raises + + - `ValueError` - If BGP ASN, VLAN ranges, or IP ranges are invalid + - `TypeError` - If required string fields are not provided + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + # Fabric Type (required for discriminated union) + type: Literal[FabricTypeEnum.VXLAN_EBGP] = Field(description="Fabric management type", default=FabricTypeEnum.VXLAN_EBGP) + + # Core eBGP Configuration + bgp_asn: Optional[str] = Field( + alias="bgpAsn", + description="BGP Autonomous System Number 1-4294967295 | 1-65535[.0-65535]. Optional when bgpAsnAutoAllocation is True.", + default=None + ) + site_id: Optional[str] = Field(alias="siteId", description="Site identifier for the fabric. Defaults to Fabric ASN.", default="") + bgp_as_mode: BgpAsModeEnum = Field( + alias="bgpAsMode", + description="BGP AS mode: multiAS assigns unique AS per leaf tier, sameTierAS assigns same AS within a tier", + default=BgpAsModeEnum.MULTI_AS + ) + bgp_asn_auto_allocation: bool = Field( + alias="bgpAsnAutoAllocation", + description="Enable automatic BGP ASN allocation from bgpAsnRange", + default=True + ) + bgp_asn_range: Optional[str] = Field( + alias="bgpAsnRange", + description="BGP ASN range for automatic allocation (e.g., '65000-65535')", + default=None + ) + bgp_allow_as_in_num: int = Field( + alias="bgpAllowAsInNum", + description="Number of times BGP allows AS-path that contains local AS", + default=1 + ) + bgp_max_path: int = Field(alias="bgpMaxPath", description="Maximum number of BGP equal-cost paths", default=4) + bgp_underlay_failure_protect: bool = Field( + alias="bgpUnderlayFailureProtect", + description="Enable BGP underlay failure protection", + default=False + ) + auto_configure_ebgp_evpn_peering: bool = Field( + alias="autoConfigureEbgpEvpnPeering", + description="Automatically configure eBGP EVPN peering between spine and leaf", + default=True + ) + allow_leaf_same_as: bool = Field( + alias="allowLeafSameAs", + description="Allow leaf switches to have the same BGP AS number", + default=False + ) + assign_ipv4_to_loopback0: bool = Field( + alias="assignIpv4ToLoopback0", + description="Assign IPv4 address to loopback0 interface", + default=True + ) + evpn: bool = Field(description="Enable EVPN control plane", default=True) + route_map_tag: int = Field(alias="routeMapTag", description="Route map tag for redistribution", default=12345) + disable_route_map_tag: bool = Field( + alias="disableRouteMapTag", + description="Disable route map tag usage", + default=False + ) + leaf_bgp_as: Optional[str] = Field( + alias="leafBgpAs", + description="BGP AS number for leaf switches (used with sameTierAS mode)", + default=None + ) + border_bgp_as: Optional[str] = Field( + alias="borderBgpAs", + description="BGP AS number for border switches", + default=None + ) + super_spine_bgp_as: Optional[str] = Field( + alias="superSpineBgpAs", + description="BGP AS number for super-spine switches", + default=None + ) + + # Propagated from FabricEbgpModel + name: Optional[str] = Field(description="Fabric name", min_length=1, max_length=64, default="") + + # Network Addressing + bgp_loopback_id: int = Field(alias="bgpLoopbackId", description="BGP loopback interface ID", ge=0, le=1023, default=0) + bgp_loopback_ip_range: str = Field(alias="bgpLoopbackIpRange", description="BGP loopback IP range", default="10.2.0.0/22") + bgp_loopback_ipv6_range: str = Field(alias="bgpLoopbackIpv6Range", description="BGP loopback IPv6 range", default="fd00::a02:0/119") + nve_loopback_id: int = Field(alias="nveLoopbackId", description="NVE loopback interface ID", ge=0, le=1023, default=1) + nve_loopback_ip_range: str = Field(alias="nveLoopbackIpRange", description="NVE loopback IP range", default="10.3.0.0/22") + nve_loopback_ipv6_range: str = Field(alias="nveLoopbackIpv6Range", description="NVE loopback IPv6 range", default="fd00::a03:0/118") + anycast_loopback_id: int = Field(alias="anycastLoopbackId", description="Anycast loopback ID", default=10) + anycast_rendezvous_point_ip_range: str = Field( + alias="anycastRendezvousPointIpRange", + description="Anycast RP IP range", + default="10.254.254.0/24" + ) + ipv6_anycast_rendezvous_point_ip_range: str = Field( + alias="ipv6AnycastRendezvousPointIpRange", + description="IPv6 anycast RP IP range", + default="fd00::254:254:0/118" + ) + intra_fabric_subnet_range: str = Field( + alias="intraFabricSubnetRange", + description="Intra-fabric subnet range", + default="10.4.0.0/16" + ) + + # VLAN and VNI Ranges + l2_vni_range: str = Field(alias="l2VniRange", description="Layer 2 VNI range", default="30000-49000") + l3_vni_range: str = Field(alias="l3VniRange", description="Layer 3 VNI range", default="50000-59000") + network_vlan_range: str = Field(alias="networkVlanRange", description="Network VLAN range", default="2300-2999") + vrf_vlan_range: str = Field(alias="vrfVlanRange", description="VRF VLAN range", default="2000-2299") + + # Overlay Configuration + overlay_mode: OverlayModeEnum = Field(alias="overlayMode", description="Overlay configuration mode", default=OverlayModeEnum.CLI) + replication_mode: ReplicationModeEnum = Field( + alias="replicationMode", + description="Multicast replication mode", + default=ReplicationModeEnum.MULTICAST + ) + multicast_group_subnet: str = Field(alias="multicastGroupSubnet", description="Multicast group subnet", default="239.1.1.0/25") + auto_generate_multicast_group_address: bool = Field( + alias="autoGenerateMulticastGroupAddress", + description="Auto-generate multicast group addresses", + default=False + ) + underlay_multicast_group_address_limit: int = Field( + alias="underlayMulticastGroupAddressLimit", + description="Underlay multicast group address limit", + ge=1, + le=255, + default=128 + ) + tenant_routed_multicast: bool = Field(alias="tenantRoutedMulticast", description="Enable tenant routed multicast", default=False) + tenant_routed_multicast_ipv6: bool = Field( + alias="tenantRoutedMulticastIpv6", + description="Enable tenant routed multicast IPv6", + default=False + ) + first_hop_redundancy_protocol: FirstHopRedundancyProtocolEnum = Field( + alias="firstHopRedundancyProtocol", + description="First-hop redundancy protocol for tenant networks", + default=FirstHopRedundancyProtocolEnum.HSRP + ) + + # Multicast / Rendezvous Point + rendezvous_point_count: int = Field( + alias="rendezvousPointCount", + description="Number of spines acting as Rendezvous-Points", + default=2 + ) + rendezvous_point_loopback_id: int = Field(alias="rendezvousPointLoopbackId", description="RP loopback ID", default=254) + rendezvous_point_mode: str = Field(alias="rendezvousPointMode", description="Multicast RP mode", default="asm") + phantom_rendezvous_point_loopback_id1: int = Field(alias="phantomRendezvousPointLoopbackId1", description="Phantom RP loopback ID 1", default=2) + phantom_rendezvous_point_loopback_id2: int = Field(alias="phantomRendezvousPointLoopbackId2", description="Phantom RP loopback ID 2", default=3) + phantom_rendezvous_point_loopback_id3: int = Field(alias="phantomRendezvousPointLoopbackId3", description="Phantom RP loopback ID 3", default=4) + phantom_rendezvous_point_loopback_id4: int = Field(alias="phantomRendezvousPointLoopbackId4", description="Phantom RP loopback ID 4", default=5) + l3vni_multicast_group: str = Field(alias="l3vniMulticastGroup", description="Default L3 VNI multicast group IPv4 address", default="239.1.1.0") + l3_vni_ipv6_multicast_group: str = Field(alias="l3VniIpv6MulticastGroup", description="Default L3 VNI multicast group IPv6 address", default="ff1e::") + ipv6_multicast_group_subnet: str = Field(alias="ipv6MulticastGroupSubnet", description="IPv6 multicast group subnet", default="ff1e::/121") + mvpn_vrf_route_import_id: bool = Field(alias="mvpnVrfRouteImportId", description="Enable MVPN VRF route import ID", default=True) + mvpn_vrf_route_import_id_range: Optional[str] = Field( + alias="mvpnVrfRouteImportIdRange", + description="MVPN VRF route import ID range", + default=None + ) + vrf_route_import_id_reallocation: bool = Field( + alias="vrfRouteImportIdReallocation", + description="Enable VRF route import ID reallocation", + default=False + ) + + # Advanced Features + anycast_gateway_mac: str = Field( + alias="anycastGatewayMac", + description="Anycast gateway MAC address", + default="2020.0000.00aa" + ) + target_subnet_mask: int = Field(alias="targetSubnetMask", description="Target subnet mask", ge=24, le=31, default=30) + fabric_mtu: int = Field(alias="fabricMtu", description="Fabric MTU size", ge=1500, le=9216, default=9216) + l2_host_interface_mtu: int = Field(alias="l2HostInterfaceMtu", description="L2 host interface MTU", ge=1500, le=9216, default=9216) + l3_vni_no_vlan_default_option: bool = Field( + alias="l3VniNoVlanDefaultOption", + description="L3 VNI configuration without VLAN", + default=False + ) + underlay_ipv6: bool = Field(alias="underlayIpv6", description="Enable IPv6 underlay", default=False) + static_underlay_ip_allocation: bool = Field( + alias="staticUnderlayIpAllocation", + description="Disable dynamic underlay IP address allocation", + default=False + ) + anycast_border_gateway_advertise_physical_ip: bool = Field( + alias="anycastBorderGatewayAdvertisePhysicalIp", + description="Advertise Anycast Border Gateway PIP as VTEP", + default=False + ) + + # VPC Configuration + vpc_domain_id_range: str = Field(alias="vpcDomainIdRange", description="vPC domain ID range", default="1-1000") + vpc_peer_link_vlan: str = Field(alias="vpcPeerLinkVlan", description="vPC peer link VLAN", default="3600") + vpc_peer_link_enable_native_vlan: bool = Field( + alias="vpcPeerLinkEnableNativeVlan", + description="Enable native VLAN on vPC peer link", + default=False + ) + vpc_peer_keep_alive_option: VpcPeerKeepAliveOptionEnum = Field( + alias="vpcPeerKeepAliveOption", + description="vPC peer keep-alive option", + default=VpcPeerKeepAliveOptionEnum.MANAGEMENT + ) + vpc_auto_recovery_timer: int = Field( + alias="vpcAutoRecoveryTimer", + description="vPC auto recovery timer", + ge=240, + le=3600, + default=360 + ) + vpc_delay_restore_timer: int = Field( + alias="vpcDelayRestoreTimer", + description="vPC delay restore timer", + ge=1, + le=3600, + default=150 + ) + vpc_peer_link_port_channel_id: str = Field(alias="vpcPeerLinkPortChannelId", description="vPC peer link port-channel ID", default="500") + vpc_ipv6_neighbor_discovery_sync: bool = Field( + alias="vpcIpv6NeighborDiscoverySync", + description="Enable vPC IPv6 ND sync", + default=True + ) + vpc_layer3_peer_router: bool = Field(alias="vpcLayer3PeerRouter", description="Enable vPC layer-3 peer router", default=True) + vpc_tor_delay_restore_timer: int = Field(alias="vpcTorDelayRestoreTimer", description="vPC TOR delay restore timer", default=30) + fabric_vpc_domain_id: bool = Field(alias="fabricVpcDomainId", description="Enable fabric vPC domain ID", default=False) + shared_vpc_domain_id: int = Field(alias="sharedVpcDomainId", description="Shared vPC domain ID", default=1) + fabric_vpc_qos: bool = Field(alias="fabricVpcQos", description="Enable fabric vPC QoS", default=False) + fabric_vpc_qos_policy_name: str = Field( + alias="fabricVpcQosPolicyName", + description="Fabric vPC QoS policy name", + default="spine_qos_for_fabric_vpc_peering" + ) + enable_peer_switch: bool = Field(alias="enablePeerSwitch", description="Enable vPC peer-switch feature on ToR switches", default=False) + + # Per-VRF Loopback + per_vrf_loopback_auto_provision: bool = Field( + alias="perVrfLoopbackAutoProvision", + description="Auto provision IPv4 loopback on VRF attachment", + default=False + ) + per_vrf_loopback_ip_range: str = Field( + alias="perVrfLoopbackIpRange", + description="Per-VRF loopback IPv4 prefix pool", + default="10.5.0.0/22" + ) + per_vrf_loopback_auto_provision_ipv6: bool = Field( + alias="perVrfLoopbackAutoProvisionIpv6", + description="Auto provision IPv6 loopback on VRF attachment", + default=False + ) + per_vrf_loopback_ipv6_range: str = Field( + alias="perVrfLoopbackIpv6Range", + description="Per-VRF loopback IPv6 prefix pool", + default="fd00::a05:0/112" + ) + + # Templates + vrf_template: str = Field(alias="vrfTemplate", description="VRF template", default="Default_VRF_Universal") + network_template: str = Field(alias="networkTemplate", description="Network template", default="Default_Network_Universal") + vrf_extension_template: str = Field( + alias="vrfExtensionTemplate", + description="VRF extension template", + default="Default_VRF_Extension_Universal" + ) + network_extension_template: str = Field( + alias="networkExtensionTemplate", + description="Network extension template", + default="Default_Network_Extension_Universal" + ) + + # Optional Advanced Settings + performance_monitoring: bool = Field(alias="performanceMonitoring", description="Enable performance monitoring", default=False) + tenant_dhcp: bool = Field(alias="tenantDhcp", description="Enable tenant DHCP", default=True) + advertise_physical_ip: bool = Field(alias="advertisePhysicalIp", description="Advertise physical IP as VTEP", default=False) + advertise_physical_ip_on_border: bool = Field( + alias="advertisePhysicalIpOnBorder", + description="Advertise physical IP on border switches only", + default=True + ) + + # Protocol Settings — BGP + bgp_authentication: bool = Field(alias="bgpAuthentication", description="Enable BGP authentication", default=False) + bgp_authentication_key_type: str = Field( + alias="bgpAuthenticationKeyType", + description="BGP authentication key type", + default="3des" + ) + bgp_authentication_key: str = Field(alias="bgpAuthenticationKey", description="BGP authentication key", default="") + + # Protocol Settings — BFD + bfd: bool = Field(description="Enable BFD", default=False) + bfd_ibgp: bool = Field(alias="bfdIbgp", description="Enable BFD for iBGP", default=False) + bfd_authentication: bool = Field(alias="bfdAuthentication", description="Enable BFD authentication", default=False) + bfd_authentication_key_id: int = Field(alias="bfdAuthenticationKeyId", description="BFD authentication key ID", default=100) + bfd_authentication_key: str = Field(alias="bfdAuthenticationKey", description="BFD authentication key", default="") + + # Protocol Settings — PIM + pim_hello_authentication: bool = Field(alias="pimHelloAuthentication", description="Enable PIM hello authentication", default=False) + pim_hello_authentication_key: str = Field(alias="pimHelloAuthenticationKey", description="PIM hello authentication key", default="") + + # Management Settings + nxapi: bool = Field(description="Enable NX-API", default=False) + nxapi_http: bool = Field(alias="nxapiHttp", description="Enable NX-API HTTP", default=False) + nxapi_https_port: int = Field(alias="nxapiHttpsPort", description="NX-API HTTPS port", ge=1, le=65535, default=443) + nxapi_http_port: int = Field(alias="nxapiHttpPort", description="NX-API HTTP port", ge=1, le=65535, default=80) + + # Bootstrap / Day-0 / DHCP + day0_bootstrap: bool = Field(alias="day0Bootstrap", description="Enable day-0 bootstrap", default=False) + bootstrap_subnet_collection: List[BootstrapSubnetModel] = Field( + alias="bootstrapSubnetCollection", + description="Bootstrap subnet collection", + default_factory=list + ) + local_dhcp_server: bool = Field(alias="localDhcpServer", description="Enable local DHCP server", default=False) + dhcp_protocol_version: str = Field(alias="dhcpProtocolVersion", description="DHCP protocol version", default="dhcpv4") + dhcp_start_address: str = Field(alias="dhcpStartAddress", description="DHCP start address", default="") + dhcp_end_address: str = Field(alias="dhcpEndAddress", description="DHCP end address", default="") + management_gateway: str = Field(alias="managementGateway", description="Management gateway", default="") + management_ipv4_prefix: int = Field(alias="managementIpv4Prefix", description="Management IPv4 prefix length", default=24) + management_ipv6_prefix: int = Field(alias="managementIpv6Prefix", description="Management IPv6 prefix length", default=64) + + # Netflow Settings + netflow_settings: NetflowSettingsModel = Field( + alias="netflowSettings", + description="Netflow configuration", + default_factory=NetflowSettingsModel + ) + + # Backup / Restore + real_time_backup: Optional[bool] = Field(alias="realTimeBackup", description="Enable real-time backup", default=None) + scheduled_backup: Optional[bool] = Field(alias="scheduledBackup", description="Enable scheduled backup", default=None) + scheduled_backup_time: str = Field(alias="scheduledBackupTime", description="Scheduled backup time", default="") + + # VRF Lite / Sub-Interface + sub_interface_dot1q_range: str = Field(alias="subInterfaceDot1qRange", description="Sub-interface 802.1q range", default="2-511") + vrf_lite_auto_config: str = Field(alias="vrfLiteAutoConfig", description="VRF lite auto-config mode", default="manual") + vrf_lite_subnet_range: str = Field(alias="vrfLiteSubnetRange", description="VRF lite subnet range", default="10.33.0.0/16") + vrf_lite_subnet_target_mask: int = Field(alias="vrfLiteSubnetTargetMask", description="VRF lite subnet target mask", default=30) + auto_unique_vrf_lite_ip_prefix: bool = Field( + alias="autoUniqueVrfLiteIpPrefix", + description="Auto unique VRF lite IP prefix", + default=False + ) + + # Leaf / TOR + leaf_tor_id_range: bool = Field(alias="leafTorIdRange", description="Enable leaf/TOR ID range", default=False) + leaf_tor_vpc_port_channel_id_range: str = Field( + alias="leafTorVpcPortChannelIdRange", + description="Leaf/TOR vPC port-channel ID range", + default="1-499" + ) + allow_vlan_on_leaf_tor_pairing: str = Field( + alias="allowVlanOnLeafTorPairing", + description="Set trunk allowed VLAN on leaf-TOR pairing port-channels", + default="none" + ) + + # DNS / NTP / Syslog Collections + ntp_server_collection: List[str] = Field(default_factory=lambda: ["string"], alias="ntpServerCollection") + ntp_server_vrf_collection: List[str] = Field(default_factory=lambda: ["string"], alias="ntpServerVrfCollection") + dns_collection: List[str] = Field(default_factory=lambda: ["5.192.28.174"], alias="dnsCollection") + dns_vrf_collection: List[str] = Field(default_factory=lambda: ["string"], alias="dnsVrfCollection") + syslog_server_collection: List[str] = Field(default_factory=lambda: ["string"], alias="syslogServerCollection") + syslog_server_vrf_collection: List[str] = Field(default_factory=lambda: ["string"], alias="syslogServerVrfCollection") + syslog_severity_collection: List[int] = Field(default_factory=lambda: [7], alias="syslogSeverityCollection") + + # Extra Config / Pre-Interface Config / AAA / Banner + banner: str = Field(description="Fabric banner text", default="") + extra_config_leaf: str = Field(alias="extraConfigLeaf", description="Extra leaf config", default="") + extra_config_spine: str = Field(alias="extraConfigSpine", description="Extra spine config", default="") + extra_config_tor: str = Field(alias="extraConfigTor", description="Extra TOR config", default="") + extra_config_intra_fabric_links: str = Field( + alias="extraConfigIntraFabricLinks", + description="Extra intra-fabric links config", + default="" + ) + extra_config_aaa: str = Field(alias="extraConfigAaa", description="Extra AAA config", default="") + extra_config_nxos_bootstrap: str = Field(alias="extraConfigNxosBootstrap", description="Extra NX-OS bootstrap config", default="") + aaa: bool = Field(description="Enable AAA", default=False) + pre_interface_config_leaf: str = Field(alias="preInterfaceConfigLeaf", description="Pre-interface leaf config", default="") + pre_interface_config_spine: str = Field(alias="preInterfaceConfigSpine", description="Pre-interface spine config", default="") + pre_interface_config_tor: str = Field(alias="preInterfaceConfigTor", description="Pre-interface TOR config", default="") + + # System / Compliance / OAM / Misc + greenfield_debug_flag: GreenfieldDebugFlagEnum = Field( + alias="greenfieldDebugFlag", + description="Greenfield debug flag", + default=GreenfieldDebugFlagEnum.DISABLE + ) + interface_statistics_load_interval: int = Field( + alias="interfaceStatisticsLoadInterval", + description="Interface statistics load interval in seconds", + default=10 + ) + nve_hold_down_timer: int = Field(alias="nveHoldDownTimer", description="NVE source interface hold-down timer in seconds", default=180) + next_generation_oam: bool = Field(alias="nextGenerationOAM", description="Enable next-generation OAM", default=True) + ngoam_south_bound_loop_detect: bool = Field( + alias="ngoamSouthBoundLoopDetect", + description="Enable NGOAM south bound loop detection", + default=False + ) + ngoam_south_bound_loop_detect_probe_interval: int = Field( + alias="ngoamSouthBoundLoopDetectProbeInterval", + description="NGOAM south bound loop detect probe interval in seconds", + default=300 + ) + ngoam_south_bound_loop_detect_recovery_interval: int = Field( + alias="ngoamSouthBoundLoopDetectRecoveryInterval", + description="NGOAM south bound loop detect recovery interval in seconds", + default=600 + ) + strict_config_compliance_mode: bool = Field( + alias="strictConfigComplianceMode", + description="Enable strict config compliance mode", + default=False + ) + advanced_ssh_option: bool = Field(alias="advancedSshOption", description="Enable advanced SSH option", default=False) + copp_policy: CoppPolicyEnum = Field(alias="coppPolicy", description="CoPP policy", default=CoppPolicyEnum.STRICT) + power_redundancy_mode: str = Field(alias="powerRedundancyMode", description="Power redundancy mode", default="redundant") + heartbeat_interval: int = Field(alias="heartbeatInterval", description="XConnect heartbeat interval", default=190) + snmp_trap: bool = Field(alias="snmpTrap", description="Enable SNMP traps", default=True) + cdp: bool = Field(description="Enable CDP", default=False) + real_time_interface_statistics_collection: bool = Field( + alias="realTimeInterfaceStatisticsCollection", + description="Enable real-time interface statistics collection", + default=False + ) + tcam_allocation: bool = Field(alias="tcamAllocation", description="Enable TCAM allocation", default=True) + allow_smart_switch_onboarding: bool = Field( + alias="allowSmartSwitchOnboarding", + description="Allow smart switch onboarding", + default=False + ) + + # Queuing / QoS + default_queuing_policy: bool = Field(alias="defaultQueuingPolicy", description="Enable default queuing policy", default=False) + default_queuing_policy_cloudscale: str = Field( + alias="defaultQueuingPolicyCloudscale", + description="Default queuing policy for cloudscale switches", + default="queuing_policy_default_8q_cloudscale" + ) + default_queuing_policy_r_series: str = Field( + alias="defaultQueuingPolicyRSeries", + description="Default queuing policy for R-Series switches", + default="queuing_policy_default_r_series" + ) + default_queuing_policy_other: str = Field( + alias="defaultQueuingPolicyOther", + description="Default queuing policy for other switches", + default="queuing_policy_default_other" + ) + aiml_qos: bool = Field(alias="aimlQos", description="Enable AI/ML QoS", default=False) + aiml_qos_policy: str = Field(alias="aimlQosPolicy", description="AI/ML QoS policy", default="400G") + roce_v2: str = Field(alias="roceV2", description="RoCEv2 DSCP value", default="26") + cnp: str = Field(description="CNP DSCP value", default="48") + wred_min: int = Field(alias="wredMin", description="WRED minimum threshold in kbytes", default=950) + wred_max: int = Field(alias="wredMax", description="WRED maximum threshold in kbytes", default=3000) + wred_drop_probability: int = Field(alias="wredDropProbability", description="WRED drop probability %", default=7) + wred_weight: int = Field(alias="wredWeight", description="WRED weight", default=0) + bandwidth_remaining: int = Field(alias="bandwidthRemaining", description="Bandwidth remaining % for AI traffic queues", default=50) + dlb: bool = Field(description="Enable dynamic load balancing", default=False) + dlb_mode: str = Field(alias="dlbMode", description="DLB mode", default="flowlet") + dlb_mixed_mode_default: str = Field(alias="dlbMixedModeDefault", description="DLB mixed mode default", default="ecmp") + flowlet_aging: Optional[int] = Field(alias="flowletAging", description="Flowlet aging timer in microseconds", default=None) + flowlet_dscp: str = Field(alias="flowletDscp", description="Flowlet DSCP value", default="") + per_packet_dscp: str = Field(alias="perPacketDscp", description="Per-packet DSCP value", default="") + ai_load_sharing: bool = Field(alias="aiLoadSharing", description="Enable AI load sharing", default=False) + priority_flow_control_watch_interval: Optional[int] = Field( + alias="priorityFlowControlWatchInterval", + description="Priority flow control watch interval in milliseconds", + default=None + ) + + # PTP + ptp: bool = Field(description="Enable PTP", default=False) + ptp_loopback_id: int = Field(alias="ptpLoopbackId", description="PTP loopback ID", default=0) + ptp_domain_id: int = Field(alias="ptpDomainId", description="PTP domain ID", default=0) + + # Private VLAN + private_vlan: bool = Field(alias="privateVlan", description="Enable private VLAN", default=False) + default_private_vlan_secondary_network_template: str = Field( + alias="defaultPrivateVlanSecondaryNetworkTemplate", + description="Default private VLAN secondary network template", + default="Pvlan_Secondary_Network" + ) + + # MACsec + macsec: bool = Field(description="Enable MACsec", default=False) + macsec_cipher_suite: str = Field( + alias="macsecCipherSuite", + description="MACsec cipher suite", + default="GCM-AES-XPN-256" + ) + macsec_key_string: str = Field(alias="macsecKeyString", description="MACsec primary key string", default="") + macsec_algorithm: str = Field(alias="macsecAlgorithm", description="MACsec primary cryptographic algorithm", default="AES_128_CMAC") + macsec_fallback_key_string: str = Field(alias="macsecFallbackKeyString", description="MACsec fallback key string", default="") + macsec_fallback_algorithm: str = Field( + alias="macsecFallbackAlgorithm", + description="MACsec fallback cryptographic algorithm", + default="AES_128_CMAC" + ) + macsec_report_timer: int = Field(alias="macsecReportTimer", description="MACsec report timer in minutes", default=5) + + # Hypershield / Connectivity + connectivity_domain_name: Optional[str] = Field( + alias="connectivityDomainName", + description="Domain name to connect to Hypershield", + default=None + ) + hypershield_connectivity_proxy_server: Optional[str] = Field( + alias="hypershieldConnectivityProxyServer", + description="IPv4 address, IPv6 address, or DNS name of the proxy server for Hypershield communication", + default=None + ) + hypershield_connectivity_proxy_server_port: Optional[int] = Field( + alias="hypershieldConnectivityProxyServerPort", + description="Proxy port number for communication with Hypershield", + default=None + ) + hypershield_connectivity_source_intf: Optional[str] = Field( + alias="hypershieldConnectivitySourceIntf", + description="Loopback interface on smart switch for communication with Hypershield", + default=None + ) + + @field_validator("bgp_asn") + @classmethod + def validate_bgp_asn(cls, value: Optional[str]) -> Optional[str]: + """ + # Summary + + Validate BGP ASN format and range when provided. + + ## Raises + + - `ValueError` - If value does not match the expected ASN format + """ + if value is None: + return value + if not _BGP_ASN_RE.match(value): + raise ValueError( + f"Invalid BGP ASN '{value}'. " + "Expected a plain integer (1-4294967295) or dotted notation (1-65535.0-65535)." + ) + return value + + @field_validator("site_id") + @classmethod + def validate_site_id(cls, value: str) -> str: + """ + # Summary + + Validate site ID format. + + ## Raises + + - `ValueError` - If site ID is not numeric or outside valid range + """ + if value == "": + return value + if not value.isdigit(): + raise ValueError(f"Site ID must be numeric, got: {value}") + site_id_int = int(value) + if not (1 <= site_id_int <= 281474976710655): + raise ValueError(f"Site ID must be between 1 and 281474976710655, got: {site_id_int}") + return value + + @field_validator("anycast_gateway_mac") + @classmethod + def validate_mac_address(cls, value: str) -> str: + """ + # Summary + + Validate MAC address format. + + ## Raises + + - `ValueError` - If MAC address format is invalid + """ + mac_pattern = re.compile(r'^([0-9a-fA-F]{4}\.){2}[0-9a-fA-F]{4}$') + if not mac_pattern.match(value): + raise ValueError(f"Invalid MAC address format, expected xxxx.xxxx.xxxx, got: {value}") + return value.lower() + + +class FabricEbgpModel(NDBaseModel): + """ + # Summary + + Complete model for creating a new eBGP VXLAN fabric. + + ## Raises + + - `ValueError` - If required fields are missing or invalid + - `TypeError` - If field types don't match expected types + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + identifiers: ClassVar[Optional[List[str]]] = ["name"] + identifier_strategy: ClassVar[Optional[Literal["single", "composite", "hierarchical", "singleton"]]] = "single" + + # Basic Fabric Properties + category: Literal["fabric"] = Field(description="Resource category", default="fabric") + name: str = Field(description="Fabric name", min_length=1, max_length=64) + location: Optional[LocationModel] = Field(description="Geographic location of the fabric", default=None) + + # License and Operations + license_tier: LicenseTierEnum = Field(alias="licenseTier", description="License tier", default=LicenseTierEnum.PREMIER) + alert_suspend: AlertSuspendEnum = Field(alias="alertSuspend", description="Alert suspension state", default=AlertSuspendEnum.DISABLED) + telemetry_collection: bool = Field(alias="telemetryCollection", description="Enable telemetry collection", default=False) + telemetry_collection_type: str = Field(alias="telemetryCollectionType", description="Telemetry collection type", default="outOfBand") + telemetry_streaming_protocol: str = Field(alias="telemetryStreamingProtocol", description="Telemetry streaming protocol", default="ipv4") + telemetry_source_interface: str = Field(alias="telemetrySourceInterface", description="Telemetry source interface", default="") + telemetry_source_vrf: str = Field(alias="telemetrySourceVrf", description="Telemetry source VRF", default="") + security_domain: str = Field(alias="securityDomain", description="Security domain", default="all") + + # Core Management Configuration + management: Optional[VxlanEbgpManagementModel] = Field(description="eBGP VXLAN management configuration", default=None) + + # Optional Advanced Settings + telemetry_settings: Optional[TelemetrySettingsModel] = Field( + alias="telemetrySettings", + description="Telemetry configuration", + default=None + ) + external_streaming_settings: ExternalStreamingSettingsModel = Field( + alias="externalStreamingSettings", + description="External streaming settings", + default_factory=ExternalStreamingSettingsModel + ) + + @field_validator("name") + @classmethod + def validate_fabric_name(cls, value: str) -> str: + """ + # Summary + + Validate fabric name format and characters. + + ## Raises + + - `ValueError` - If name contains invalid characters or format + """ + if not re.match(r'^[a-zA-Z0-9_-]+$', value): + raise ValueError(f"Fabric name can only contain letters, numbers, underscores, and hyphens, got: {value}") + return value + + @model_validator(mode='after') + def validate_fabric_consistency(self) -> 'FabricEbgpModel': + """ + # Summary + + Validate consistency between fabric settings and management configuration. + + ## Raises + + - `ValueError` - If fabric settings are inconsistent + """ + if self.management is not None and self.management.type != FabricTypeEnum.VXLAN_EBGP: + raise ValueError(f"Management type must be {FabricTypeEnum.VXLAN_EBGP}") + + # Propagate fabric name to management model + if self.management is not None: + self.management.name = self.name + + # Propagate BGP ASN to site_id if both are set and site_id is empty + if self.management is not None and self.management.site_id == "" and self.management.bgp_asn is not None: + bgp_asn = self.management.bgp_asn + if "." in bgp_asn: + high, low = bgp_asn.split(".") + self.management.site_id = str(int(high) * 65536 + int(low)) + else: + self.management.site_id = bgp_asn + + # Auto-create default telemetry settings if collection is enabled + if self.telemetry_collection and self.telemetry_settings is None: + self.telemetry_settings = TelemetrySettingsModel() + + return self + + def to_diff_dict(self, **kwargs) -> Dict[str, Any]: + """Export for diff comparison, excluding fields that ND overrides for eBGP fabrics.""" + d = super().to_diff_dict(**kwargs) + # ND always returns nxapiHttp=True for eBGP fabrics regardless of the configured value, + # so exclude it from diff comparison to prevent a persistent false-positive diff. + if "management" in d: + d["management"].pop("nxapiHttp", None) + return d + + @classmethod + def get_argument_spec(cls) -> Dict: + return dict( + state={ + "type": "str", + "default": "merged", + "choices": ["merged", "replaced", "deleted", "overridden", "query"], + }, + config={"required": False, "type": "list", "elements": "dict"}, + ) + + +# Export all models for external use +__all__ = [ + "VxlanEbgpManagementModel", + "FabricEbgpModel", + "FabricEbgpDeleteModel", + "FabricTypeEnum", + "AlertSuspendEnum", + "LicenseTierEnum", + "ReplicationModeEnum", + "OverlayModeEnum", + "BgpAsModeEnum", + "FirstHopRedundancyProtocolEnum", + "VpcPeerKeepAliveOptionEnum", + "CoppPolicyEnum", + "GreenfieldDebugFlagEnum", +] diff --git a/plugins/module_utils/models/manage_fabric/manage_fabric_external.py b/plugins/module_utils/models/manage_fabric/manage_fabric_external.py new file mode 100644 index 00000000..e6f2d0a6 --- /dev/null +++ b/plugins/module_utils/models/manage_fabric/manage_fabric_external.py @@ -0,0 +1,522 @@ +# -*- coding: utf-8 -*- + +# Copyright: (c) 2026, Mike Wiebe (@mwiebe) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +# pylint: disable=invalid-name +__metaclass__ = type +# pylint: enable=invalid-name + +import re +from typing import List, Dict, Any, Optional, ClassVar, Literal + +from ansible_collections.cisco.nd.plugins.module_utils.models.base import NDBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.models.nested import NDNestedModel +from ansible_collections.cisco.nd.plugins.module_utils.common.pydantic_compat import ( + BaseModel, + ConfigDict, + Field, + field_validator, + model_validator, +) +from ansible_collections.cisco.nd.plugins.module_utils.models.manage_fabric.enums import ( + FabricTypeEnum, + AlertSuspendEnum, + LicenseTierEnum, + CoppPolicyEnum, + DhcpProtocolVersionEnum, + PowerRedundancyModeEnum, +) +# Re-use shared nested models from the iBGP module +from ansible_collections.cisco.nd.plugins.module_utils.models.manage_fabric.manage_fabric_ibgp import ( + LocationModel, + NetflowSettingsModel, + BootstrapSubnetModel, + TelemetrySettingsModel, + ExternalStreamingSettingsModel, +) + + +""" +# Comprehensive Pydantic models for External VXLAN fabric management via Nexus Dashboard + +This module provides Pydantic models for creating, updating, and deleting +External VXLAN fabrics (border/edge router fabrics) through the Nexus Dashboard +Fabric Controller (NDFC) API. + +## Models Overview + +- `VxlanExternalManagementModel` - External VXLAN fabric-specific management settings +- `FabricExternalModel` - Complete fabric creation model for External fabrics +- `FabricExternalDeleteModel` - Fabric deletion model + +## Usage + +```python +# Create a new External VXLAN fabric +fabric_data = { + "name": "MyExternalFabric", + "management": { + "type": "vxlanExternal", + "bgpAsn": "65001", + } +} +fabric = FabricExternalModel(**fabric_data) +``` +""" + +# Regex from OpenAPI schema: bgpAsn accepts plain integers (1-4294967295) and +# dotted four-byte ASN notation (1-65535).(0-65535) +_BGP_ASN_RE = re.compile( + r"^(([1-9]{1}[0-9]{0,8}|[1-3]{1}[0-9]{1,9}|[4]{1}([0-1]{1}[0-9]{8}|[2]{1}([0-8]{1}[0-9]{7}|[9]{1}([0-3]{1}[0-9]{6}|[4]{1}([0-8]{1}[0-9]{5}|[9]{1}([0-5]{1}[0-9]{4}|[6]{1}([0-6]{1}[0-9]{3}|[7]{1}([0-1]{1}[0-9]{2}|[2]{1}([0-8]{1}[0-9]{1}|[9]{1}[0-5]{1})))))))))|([1-5]\d{4}|[1-9]\d{0,3}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])(\.([1-5]\d{4}|[1-9]\d{0,3}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]|0))?)$" +) + + +class VxlanExternalManagementModel(NDNestedModel): + """ + # Summary + + Comprehensive External VXLAN fabric management configuration. + + This model contains all settings for External VXLAN fabric types, used for + border/edge router fabrics that connect to external networks. + + ## Raises + + - `ValueError` - If BGP ASN or other field validations fail + - `TypeError` - If required string fields are not provided + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + # Fabric Type (required for discriminated union) + type: Literal[FabricTypeEnum.VXLAN_EXTERNAL] = Field( + description="Fabric management type", + default=FabricTypeEnum.VXLAN_EXTERNAL + ) + + # Propagated from FabricExternalModel + name: Optional[str] = Field(description="Fabric name", min_length=1, max_length=64, default="") + + # Core BGP Configuration + bgp_asn: str = Field( + alias="bgpAsn", + description="Autonomous system number 1-4294967295 | 1-65535[.0-65535]", + ) + create_bgp_config: bool = Field( + alias="createBgpConfig", + description="Generate BGP configuration for core and edge routers", + default=True + ) + + # Fabric Behavior + monitored_mode: bool = Field( + alias="monitoredMode", + description="If enabled, fabric is only monitored. No configuration will be deployed", + default=False + ) + mpls_handoff: bool = Field( + alias="mplsHandoff", + description="Enable MPLS Handoff", + default=False + ) + mpls_loopback_identifier: Optional[int] = Field( + alias="mplsLoopbackIdentifier", + description="Underlay MPLS Loopback Identifier", + default=None + ) + mpls_loopback_ip_range: str = Field( + alias="mplsLoopbackIpRange", + description="MPLS Loopback IP Address Range", + default="10.102.0.0/25" + ) + sub_interface_dot1q_range: str = Field( + alias="subInterfaceDot1qRange", + description="Per aggregation dot1q range for VRF-Lite connectivity (minimum: 2, maximum: 4093)", + default="2-511" + ) + inband_management: bool = Field( + alias="inbandManagement", + description="Import switches with reachability over the switch front-panel ports", + default=False + ) + allow_same_loopback_ip_on_switches: bool = Field( + alias="allowSameLoopbackIpOnSwitches", + description="Allow the same loopback IP address to be configured on multiple switches", + default=False + ) + allow_smart_switch_onboarding: bool = Field( + alias="allowSmartSwitchOnboarding", + description="Enable onboarding of smart switches to Hypershield for firewall service", + default=False + ) + + # Bootstrap / Day-0 / DHCP + day0_bootstrap: bool = Field( + alias="day0Bootstrap", + description="Support day 0 touchless switch bringup", + default=False + ) + day0_plug_and_play: bool = Field( + alias="day0PlugAndPlay", + description="Enable Plug n Play for Catalyst 9000 switches", + default=False + ) + inband_day0_bootstrap: bool = Field( + alias="inbandDay0Bootstrap", + description="Support day 0 touchless switch bringup via inband management", + default=False + ) + bootstrap_subnet_collection: List[BootstrapSubnetModel] = Field( + alias="bootstrapSubnetCollection", + description="List of IPv4 or IPv6 subnets to be used for bootstrap", + default_factory=list + ) + local_dhcp_server: bool = Field( + alias="localDhcpServer", + description="Automatic IP Assignment For POAP from Local DHCP Server", + default=False + ) + dhcp_protocol_version: DhcpProtocolVersionEnum = Field( + alias="dhcpProtocolVersion", + description="IP protocol version for Local DHCP Server", + default=DhcpProtocolVersionEnum.DHCPV4 + ) + dhcp_start_address: str = Field( + alias="dhcpStartAddress", + description="DHCP Scope Start Address For Switch POAP", + default="" + ) + dhcp_end_address: str = Field( + alias="dhcpEndAddress", + description="DHCP Scope End Address For Switch POAP", + default="" + ) + domain_name: str = Field( + alias="domainName", + description="Domain name for DHCP server PnP block", + default="" + ) + management_gateway: str = Field( + alias="managementGateway", + description="Default Gateway For Management VRF On The Switch", + default="" + ) + management_ipv4_prefix: int = Field( + alias="managementIpv4Prefix", + description="Switch Mgmt IP Subnet Prefix if ipv4", + default=24 + ) + management_ipv6_prefix: int = Field( + alias="managementIpv6Prefix", + description="Switch Management IP Subnet Prefix if ipv6", + default=64 + ) + + # DNS Collections + dns_collection: List[str] = Field( + alias="dnsCollection", + description="List of IPv4 and IPv6 DNS addresses", + default_factory=list + ) + dns_vrf_collection: List[str] = Field( + alias="dnsVrfCollection", + description="DNS Server VRFs. One VRF for all DNS servers or a list of VRFs, one per DNS server", + default_factory=list + ) + + # Extra Configuration + extra_config_aaa: str = Field( + alias="extraConfigAaa", + description="Additional CLIs for AAA Configuration", + default="" + ) + extra_config_fabric: str = Field( + alias="extraConfigFabric", + description="Additional CLIs for all switches", + default="" + ) + extra_config_nxos_bootstrap: str = Field( + alias="extraConfigNxosBootstrap", + description="Additional CLIs required during device bootup/login e.g. AAA/Radius (NX-OS)", + default="" + ) + extra_config_xe_bootstrap: str = Field( + alias="extraConfigXeBootstrap", + description="Additional CLIs required during device bootup/login e.g. AAA/Radius (IOS-XE)", + default="" + ) + + # Management Protocol Settings + nxapi: bool = Field( + description="Enable NX-API over HTTPS", + default=False + ) + nxapi_http: bool = Field( + alias="nxapiHttp", + description="Enable NX-API over HTTP", + default=False + ) + nxapi_http_port: int = Field( + alias="nxapiHttpPort", + description="HTTP port for NX-API", + default=80 + ) + nxapi_https_port: int = Field( + alias="nxapiHttpsPort", + description="HTTPS port for NX-API", + default=443 + ) + cdp: bool = Field( + description="Enable CDP on management interface", + default=False + ) + aaa: bool = Field( + description="Include AAA configs from Advanced tab during device bootup", + default=False + ) + advanced_ssh_option: bool = Field( + alias="advancedSshOption", + description="Enable only, when IP Authorization is enabled in the AAA Server", + default=False + ) + snmp_trap: bool = Field( + alias="snmpTrap", + description="Configure Nexus Dashboard as a receiver for SNMP traps", + default=True + ) + copp_policy: CoppPolicyEnum = Field( + alias="coppPolicy", + description="Fabric wide CoPP policy. Customized CoPP policy should be provided when 'manual'", + default=CoppPolicyEnum.MANUAL + ) + power_redundancy_mode: PowerRedundancyModeEnum = Field( + alias="powerRedundancyMode", + description="Default Power Supply Mode for NX-OS Switches", + default=PowerRedundancyModeEnum.REDUNDANT + ) + interface_statistics_load_interval: int = Field( + alias="interfaceStatisticsLoadInterval", + description="Interface Statistics Load Interval Time in seconds", + default=10 + ) + performance_monitoring: bool = Field( + alias="performanceMonitoring", + description="If enabled, switch metrics are collected through periodic SNMP polling", + default=False + ) + real_time_interface_statistics_collection: bool = Field( + alias="realTimeInterfaceStatisticsCollection", + description="Enable Real Time Interface Statistics Collection. Valid for NX-OS only", + default=False + ) + + # PTP Settings + ptp: bool = Field( + description="Enable Precision Time Protocol (PTP)", + default=False + ) + ptp_domain_id: int = Field( + alias="ptpDomainId", + description="Multiple Independent PTP Clocking Subdomains on a Single Network", + default=0 + ) + ptp_loopback_id: int = Field( + alias="ptpLoopbackId", + description="Precision Time Protocol Source Loopback Id", + default=0 + ) + + # Netflow Settings + netflow_settings: NetflowSettingsModel = Field( + alias="netflowSettings", + description="Settings associated with netflow", + default_factory=NetflowSettingsModel + ) + + # Backup / Restore + real_time_backup: Optional[bool] = Field( + alias="realTimeBackup", + description="Hourly Fabric Backup only if there is any config deployment since last backup", + default=None + ) + scheduled_backup: Optional[bool] = Field( + alias="scheduledBackup", + description="Enable backup at the specified time daily", + default=None + ) + scheduled_backup_time: str = Field( + alias="scheduledBackupTime", + description="Time (UTC) in 24 hour format to take a daily backup if enabled (00:00 to 23:59)", + default="" + ) + + # Hypershield / Connectivity + connectivity_domain_name: Optional[str] = Field( + alias="connectivityDomainName", + description="Domain name to connect to Hypershield", + default=None + ) + hypershield_connectivity_proxy_server: Optional[str] = Field( + alias="hypershieldConnectivityProxyServer", + description="IPv4 address, IPv6 address, or DNS name of the proxy server for Hypershield communication", + default=None + ) + hypershield_connectivity_proxy_server_port: Optional[int] = Field( + alias="hypershieldConnectivityProxyServerPort", + description="Proxy port number for communication with Hypershield", + default=None + ) + hypershield_connectivity_source_intf: Optional[str] = Field( + alias="hypershieldConnectivitySourceIntf", + description="Loopback interface on smart switch for communication with Hypershield", + default=None + ) + + @field_validator("bgp_asn") + @classmethod + def validate_bgp_asn(cls, value: str) -> str: + """ + # Summary + + Validate BGP ASN format and range. + + ## Raises + + - `ValueError` - If value does not match the expected ASN format + """ + if not _BGP_ASN_RE.match(value): + raise ValueError( + f"Invalid BGP ASN '{value}'. " + "Expected a plain integer (1-4294967295) or dotted notation (1-65535.0-65535)." + ) + return value + + +class FabricExternalModel(NDBaseModel): + """ + # Summary + + Complete model for creating a new External VXLAN fabric. + + ## Raises + + - `ValueError` - If required fields are missing or invalid + - `TypeError` - If field types don't match expected types + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + identifiers: ClassVar[Optional[List[str]]] = ["name"] + identifier_strategy: ClassVar[Optional[Literal["single", "composite", "hierarchical", "singleton"]]] = "single" + + # Basic Fabric Properties + category: Literal["fabric"] = Field(description="Resource category", default="fabric") + name: str = Field(description="Fabric name", min_length=1, max_length=64) + location: Optional[LocationModel] = Field(description="Geographic location of the fabric", default=None) + + # License and Operations + license_tier: LicenseTierEnum = Field(alias="licenseTier", description="License tier", default=LicenseTierEnum.PREMIER) + alert_suspend: AlertSuspendEnum = Field(alias="alertSuspend", description="Alert suspension state", default=AlertSuspendEnum.DISABLED) + telemetry_collection: bool = Field(alias="telemetryCollection", description="Enable telemetry collection", default=False) + telemetry_collection_type: str = Field(alias="telemetryCollectionType", description="Telemetry collection type", default="outOfBand") + telemetry_streaming_protocol: str = Field(alias="telemetryStreamingProtocol", description="Telemetry streaming protocol", default="ipv4") + telemetry_source_interface: str = Field(alias="telemetrySourceInterface", description="Telemetry source interface", default="") + telemetry_source_vrf: str = Field(alias="telemetrySourceVrf", description="Telemetry source VRF", default="") + security_domain: str = Field(alias="securityDomain", description="Security domain", default="all") + + # Core Management Configuration + management: Optional[VxlanExternalManagementModel] = Field( + description="External VXLAN management configuration", + default=None + ) + + # Optional Advanced Settings + telemetry_settings: Optional[TelemetrySettingsModel] = Field( + alias="telemetrySettings", + description="Telemetry configuration", + default=None + ) + external_streaming_settings: ExternalStreamingSettingsModel = Field( + alias="externalStreamingSettings", + description="External streaming settings", + default_factory=ExternalStreamingSettingsModel + ) + + @field_validator("name") + @classmethod + def validate_fabric_name(cls, value: str) -> str: + """ + # Summary + + Validate fabric name format and characters. + + ## Raises + + - `ValueError` - If name contains invalid characters or format + """ + if not re.match(r'^[a-zA-Z0-9_-]+$', value): + raise ValueError(f"Fabric name can only contain letters, numbers, underscores, and hyphens, got: {value}") + return value + + @model_validator(mode='after') + def validate_fabric_consistency(self) -> 'FabricExternalModel': + """ + # Summary + + Validate consistency between fabric settings and management configuration. + + ## Raises + + - `ValueError` - If fabric settings are inconsistent + """ + if self.management is not None and self.management.type != FabricTypeEnum.VXLAN_EXTERNAL: + raise ValueError(f"Management type must be {FabricTypeEnum.VXLAN_EXTERNAL}") + + # Propagate fabric name to management model + if self.management is not None: + self.management.name = self.name + + # Auto-create default telemetry settings if collection is enabled + if self.telemetry_collection and self.telemetry_settings is None: + self.telemetry_settings = TelemetrySettingsModel() + + return self + + @classmethod + def get_argument_spec(cls) -> Dict: + return dict( + state={ + "type": "str", + "default": "merged", + "choices": ["merged", "replaced", "deleted", "overridden", "query"], + }, + config={"required": False, "type": "list", "elements": "dict"}, + ) + + +# Export all models for external use +__all__ = [ + "VxlanExternalManagementModel", + "FabricExternalModel", + "FabricExternalDeleteModel", + "FabricTypeEnum", + "AlertSuspendEnum", + "LicenseTierEnum", + "CoppPolicyEnum", + "DhcpProtocolVersionEnum", + "PowerRedundancyModeEnum", +] diff --git a/plugins/module_utils/models/manage_fabric/manage_fabric_ibgp.py b/plugins/module_utils/models/manage_fabric/manage_fabric_ibgp.py new file mode 100644 index 00000000..5e8169de --- /dev/null +++ b/plugins/module_utils/models/manage_fabric/manage_fabric_ibgp.py @@ -0,0 +1,1317 @@ +# -*- coding: utf-8 -*- + +# Copyright: (c) 2026, Mike Wiebe (@mwiebe) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +# pylint: disable=invalid-name +__metaclass__ = type +# pylint: enable=invalid-name + +import re +# from datetime import datetime +from enum import Enum +from typing import List, Dict, Any, Optional, ClassVar, Literal + +from ansible_collections.cisco.nd.plugins.module_utils.models.base import NDBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.models.nested import NDNestedModel +from ansible_collections.cisco.nd.plugins.module_utils.common.pydantic_compat import ( + BaseModel, + ConfigDict, + Field, + field_validator, + model_validator, +) +from ansible_collections.cisco.nd.plugins.module_utils.models.manage_fabric.enums import ( + FabricTypeEnum, + AlertSuspendEnum, + LicenseTierEnum, + OverlayModeEnum, + ReplicationModeEnum, + LinkStateRoutingProtocolEnum, + CoppPolicyEnum, + FabricInterfaceTypeEnum, + GreenfieldDebugFlagEnum, + IsisLevelEnum, + SecurityGroupStatusEnum, + StpRootOptionEnum, + VpcPeerKeepAliveOptionEnum, +) + + +""" +# Comprehensive Pydantic models for iBGP VXLAN fabric management via Nexus Dashboard + +This module provides comprehensive Pydantic models for creating, updating, and deleting +iBGP VXLAN fabrics through the Nexus Dashboard Fabric Controller (NDFC) API. + +## Models Overview + +- `LocationModel` - Geographic location coordinates +- `NetflowExporterModel` - Netflow exporter configuration +- `NetflowRecordModel` - Netflow record configuration +- `NetflowMonitorModel` - Netflow monitor configuration +- `NetflowSettingsModel` - Complete netflow settings +- `BootstrapSubnetModel` - Bootstrap subnet configuration +- `TelemetryFlowCollectionModel` - Telemetry flow collection settings +- `TelemetrySettingsModel` - Complete telemetry configuration +- `ExternalStreamingSettingsModel` - External streaming configuration +- `VxlanIbgpManagementModel` - iBGP VXLAN specific management settings +- `FabricModel` - Complete fabric creation model +- `FabricDeleteModel` - Fabric deletion model + +## Usage + +```python +# Create a new iBGP VXLAN fabric +fabric_data = { + "name": "MyFabric", + "location": {"latitude": 37.7749, "longitude": -122.4194}, + "management": { + "type": "vxlanIbgp", + "bgp_asn": "65001", + "site_id": "65001" + } +} +fabric = FabricModel(**fabric_data) +``` +""" + +# Regex from OpenAPI schema: bgpAsn accepts plain integers (1-4294967295) and +# dotted four-byte ASN notation (1-65535).(0-65535) +_BGP_ASN_RE = re.compile( + r"^(([1-9]{1}[0-9]{0,8}|[1-3]{1}[0-9]{1,9}|[4]{1}([0-1]{1}[0-9]{8}|[2]{1}([0-8]{1}[0-9]{7}|[9]{1}([0-3]{1}[0-9]{6}|[4]{1}([0-8]{1}[0-9]{5}|[9]{1}([0-5]{1}[0-9]{4}|[6]{1}([0-6]{1}[0-9]{3}|[7]{1}([0-1]{1}[0-9]{2}|[2]{1}([0-8]{1}[0-9]{1}|[9]{1}[0-5]{1})))))))))|([1-5]\d{4}|[1-9]\d{0,3}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])(\.([1-5]\d{4}|[1-9]\d{0,3}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]|0))?)$" +) + + +class LocationModel(NDNestedModel): + """ + # Summary + + Geographic location coordinates for the fabric. + + ## Raises + + - `ValueError` - If latitude or longitude are outside valid ranges + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + latitude: float = Field( + description="Latitude coordinate (-90 to 90)", + ge=-90.0, + le=90.0 + ) + longitude: float = Field( + description="Longitude coordinate (-180 to 180)", + ge=-180.0, + le=180.0 + ) + + +class NetflowExporterModel(NDNestedModel): + """ + # Summary + + Netflow exporter configuration for telemetry. + + ## Raises + + - `ValueError` - If UDP port is outside valid range or IP address is invalid + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + exporter_name: str = Field(alias="exporterName", description="Name of the netflow exporter") + exporter_ip: str = Field(alias="exporterIp", description="IP address of the netflow collector") + vrf: str = Field(description="VRF name for the exporter", default="management") + source_interface_name: str = Field(alias="sourceInterfaceName", description="Source interface name") + udp_port: int = Field(alias="udpPort", description="UDP port for netflow export", ge=1, le=65535) + + +class NetflowRecordModel(NDNestedModel): + """ + # Summary + + Netflow record configuration defining flow record templates. + + ## Raises + + None + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + record_name: str = Field(alias="recordName", description="Name of the netflow record") + record_template: str = Field(alias="recordTemplate", description="Template type for the record") + layer2_record: bool = Field(alias="layer2Record", description="Enable layer 2 record fields", default=False) + + +class NetflowMonitorModel(NDNestedModel): + """ + # Summary + + Netflow monitor configuration linking records to exporters. + + ## Raises + + None + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + monitor_name: str = Field(alias="monitorName", description="Name of the netflow monitor") + record_name: str = Field(alias="recordName", description="Associated record name") + exporter1_name: str = Field(alias="exporter1Name", description="Primary exporter name") + exporter2_name: str = Field(alias="exporter2Name", description="Secondary exporter name", default="") + + +class NetflowSettingsModel(NDNestedModel): + """ + # Summary + + Complete netflow configuration including exporters, records, and monitors. + + ## Raises + + - `ValueError` - If netflow lists are inconsistent with netflow enabled state + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + netflow: bool = Field(description="Enable netflow collection", default=False) + netflow_exporter_collection: List[NetflowExporterModel] = Field( + alias="netflowExporterCollection", + description="List of netflow exporters", + default_factory=list + ) + netflow_record_collection: List[NetflowRecordModel] = Field( + alias="netflowRecordCollection", + description="List of netflow records", + default_factory=list + ) + netflow_monitor_collection: List[NetflowMonitorModel] = Field( + alias="netflowMonitorCollection", + description="List of netflow monitors", + default_factory=list + ) + + +class BootstrapSubnetModel(NDNestedModel): + """ + # Summary + + Bootstrap subnet configuration for fabric initialization. + + ## Raises + + - `ValueError` - If IP addresses or subnet prefix are invalid + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + start_ip: str = Field(alias="startIp", description="Starting IP address of the bootstrap range") + end_ip: str = Field(alias="endIp", description="Ending IP address of the bootstrap range") + default_gateway: str = Field(alias="defaultGateway", description="Default gateway for bootstrap subnet") + subnet_prefix: int = Field(alias="subnetPrefix", description="Subnet prefix length", ge=8, le=30) + + +class TelemetryFlowCollectionModel(NDNestedModel): + """ + # Summary + + Telemetry flow collection configuration. + + ## Raises + + None + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + traffic_analytics: str = Field(alias="trafficAnalytics", description="Traffic analytics state", default="enabled") + traffic_analytics_scope: str = Field( + alias="trafficAnalyticsScope", + description="Traffic analytics scope", + default="intraFabric" + ) + operating_mode: str = Field(alias="operatingMode", description="Operating mode", default="flowTelemetry") + udp_categorization: str = Field(alias="udpCategorization", description="UDP categorization", default="enabled") + + +class TelemetryMicroburstModel(NDNestedModel): + """ + # Summary + + Microburst detection configuration. + + ## Raises + + None + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + microburst: bool = Field(description="Enable microburst detection", default=False) + sensitivity: str = Field(description="Microburst sensitivity level", default="low") + + +class TelemetryAnalysisSettingsModel(NDNestedModel): + """ + # Summary + + Telemetry analysis configuration. + + ## Raises + + None + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + is_enabled: bool = Field(alias="isEnabled", description="Enable telemetry analysis", default=False) + + +class TelemetryEnergyManagementModel(NDNestedModel): + """ + # Summary + + Energy management telemetry configuration. + + ## Raises + + None + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + cost: float = Field(description="Energy cost per unit", default=1.2) + + +class TelemetryNasExportSettingsModel(NDNestedModel): + """ + # Summary + + NAS export settings for telemetry. + + ## Raises + + None + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + export_type: str = Field(alias="exportType", description="Export type", default="full") + export_format: str = Field(alias="exportFormat", description="Export format", default="json") + + +class TelemetryNasModel(NDNestedModel): + """ + # Summary + + NAS (Network Attached Storage) telemetry configuration. + + ## Raises + + None + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + server: str = Field(description="NAS server address", default="") + export_settings: TelemetryNasExportSettingsModel = Field( + alias="exportSettings", + description="NAS export settings", + default_factory=TelemetryNasExportSettingsModel + ) + + +class TelemetrySettingsModel(NDNestedModel): + """ + # Summary + + Complete telemetry configuration for the fabric. + + ## Raises + + None + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + flow_collection: TelemetryFlowCollectionModel = Field( + alias="flowCollection", + description="Flow collection settings", + default_factory=TelemetryFlowCollectionModel + ) + microburst: TelemetryMicroburstModel = Field( + description="Microburst detection settings", + default_factory=TelemetryMicroburstModel + ) + analysis_settings: TelemetryAnalysisSettingsModel = Field( + alias="analysisSettings", + description="Analysis settings", + default_factory=TelemetryAnalysisSettingsModel + ) + nas: TelemetryNasModel = Field( + description="NAS telemetry configuration", + default_factory=TelemetryNasModel + ) + energy_management: TelemetryEnergyManagementModel = Field( + alias="energyManagement", + description="Energy management settings", + default_factory=TelemetryEnergyManagementModel + ) + + +class ExternalStreamingSettingsModel(NDNestedModel): + """ + # Summary + + External streaming configuration for events and data export. + + ## Raises + + None + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + email: List[Dict[str, Any]] = Field(description="Email streaming configuration", default_factory=list) + message_bus: List[Dict[str, Any]] = Field(alias="messageBus", description="Message bus configuration", default_factory=list) + syslog: Dict[str, Any] = Field( + description="Syslog streaming configuration", + default_factory=lambda: { + "collectionSettings": {"anomalies": []}, + "facility": "", + "servers": [] + } + ) + webhooks: List[Dict[str, Any]] = Field(description="Webhook configuration", default_factory=list) + + +class VxlanIbgpManagementModel(NDNestedModel): + """ + # Summary + + Comprehensive iBGP VXLAN fabric management configuration. + + This model contains all settings specific to iBGP VXLAN fabric types including + overlay configuration, underlay routing, multicast settings, and advanced features. + + ## Raises + + - `ValueError` - If BGP ASN, VLAN ranges, or IP ranges are invalid + - `TypeError` - If required string fields are not provided + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" + ) + + # Fabric Type (required for discriminated union) + type: Literal[FabricTypeEnum.VXLAN_IBGP] = Field(description="Fabric management type", default=FabricTypeEnum.VXLAN_IBGP) + + # Core iBGP Configuration + bgp_asn: str = Field(alias="bgpAsn", description="BGP Autonomous System Number 1-4294967295 | 1-65535[.0-65535]") + site_id: Optional[str] = Field(alias="siteId", description="Site identifier for the fabric", default="") + + # Name under management section is optional for backward compatibility, but if provided must be non-empty string + name: Optional[str] = Field(description="Fabric name", min_length=1, max_length=64, default="") + # border_count: Optional[int] = Field(alias="borderCount", description="Number of border switches", ge=0, le=32, default=0) + # breakout_spine_interfaces: Optional[bool] = Field(alias="breakoutSpineInterfaces", description="Enable breakout spine interfaces", default=False) + # designer_use_robot_password: Optional[bool] = Field(alias="designerUseRobotPassword", description="Use robot password for designer", default=False) + # leaf_count: Optional[int] = Field(alias="leafCount", description="Number of leaf switches", ge=1, le=128, default=1) + # spine_count: Optional[int] = Field(alias="spineCount", description="Number of spine switches", ge=1, le=32, default=1) + # vrf_lite_ipv6_subnet_range: Optional[str] = Field(alias="vrfLiteIpv6SubnetRange", description="VRF Lite IPv6 subnet range", default="fd00::a33:0/112") + # vrf_lite_ipv6_subnet_target_mask: Optional[int] = Field(alias="vrfLiteIpv6SubnetTargetMask", description="VRF Lite IPv6 subnet target mask", ge=112, le=128, default=126) + + + # Network Addressing + bgp_loopback_ip_range: str = Field( + alias="bgpLoopbackIpRange", + description="BGP loopback IP range", + default="10.2.0.0/22" + ) + nve_loopback_ip_range: str = Field( + alias="nveLoopbackIpRange", + description="NVE loopback IP range", + default="10.3.0.0/22" + ) + anycast_rendezvous_point_ip_range: str = Field( + alias="anycastRendezvousPointIpRange", + description="Anycast RP IP range", + default="10.254.254.0/24" + ) + intra_fabric_subnet_range: str = Field( + alias="intraFabricSubnetRange", + description="Intra-fabric subnet range", + default="10.4.0.0/16" + ) + + # VLAN and VNI Ranges + l2_vni_range: str = Field(alias="l2VniRange", description="Layer 2 VNI range", default="30000-49000") + l3_vni_range: str = Field(alias="l3VniRange", description="Layer 3 VNI range", default="50000-59000") + network_vlan_range: str = Field(alias="networkVlanRange", description="Network VLAN range", default="2300-2999") + vrf_vlan_range: str = Field(alias="vrfVlanRange", description="VRF VLAN range", default="2000-2299") + + # Overlay Configuration + overlay_mode: OverlayModeEnum = Field(alias="overlayMode", description="Overlay configuration mode", default=OverlayModeEnum.CLI) + replication_mode: ReplicationModeEnum = Field( + alias="replicationMode", + description="Multicast replication mode", + default=ReplicationModeEnum.MULTICAST + ) + multicast_group_subnet: str = Field( + alias="multicastGroupSubnet", + description="Multicast group subnet", + default="239.1.1.0/25" + ) + auto_generate_multicast_group_address: bool = Field( + alias="autoGenerateMulticastGroupAddress", + description="Auto-generate multicast group addresses", + default=False + ) + underlay_multicast_group_address_limit: int = Field( + alias="underlayMulticastGroupAddressLimit", + description="Underlay multicast group address limit", + ge=1, + le=255, + default=128 + ) + tenant_routed_multicast: bool = Field( + alias="tenantRoutedMulticast", + description="Enable tenant routed multicast", + default=False + ) + + # Underlay Configuration + link_state_routing_protocol: LinkStateRoutingProtocolEnum = Field( + alias="linkStateRoutingProtocol", + description="Underlay routing protocol", + default=LinkStateRoutingProtocolEnum.OSPF + ) + ospf_area_id: str = Field(alias="ospfAreaId", description="OSPF area ID", default="0.0.0.0") + fabric_interface_type: FabricInterfaceTypeEnum = Field(alias="fabricInterfaceType", description="Fabric interface type", default=FabricInterfaceTypeEnum.P2P) + + # Advanced Features + target_subnet_mask: int = Field(alias="targetSubnetMask", description="Target subnet mask", ge=24, le=31, default=30) + anycast_gateway_mac: str = Field( + alias="anycastGatewayMac", + description="Anycast gateway MAC address", + default="2020.0000.00aa" + ) + fabric_mtu: int = Field(alias="fabricMtu", description="Fabric MTU size", ge=1500, le=9216, default=9216) + l2_host_interface_mtu: int = Field( + alias="l2HostInterfaceMtu", + description="L2 host interface MTU", + ge=1500, + le=9216, + default=9216 + ) + + # VPC Configuration + vpc_domain_id_range: str = Field(alias="vpcDomainIdRange", description="vPC domain ID range", default="1-1000") + vpc_peer_link_vlan: str = Field(alias="vpcPeerLinkVlan", description="vPC peer link VLAN", default="3600") + vpc_peer_link_enable_native_vlan: bool = Field( + alias="vpcPeerLinkEnableNativeVlan", + description="Enable native VLAN on vPC peer link", + default=False + ) + vpc_peer_keep_alive_option: VpcPeerKeepAliveOptionEnum = Field( + alias="vpcPeerKeepAliveOption", + description="vPC peer keep-alive option", + default=VpcPeerKeepAliveOptionEnum.MANAGEMENT + ) + vpc_auto_recovery_timer: int = Field( + alias="vpcAutoRecoveryTimer", + description="vPC auto recovery timer", + ge=240, + le=3600, + default=360 + ) + vpc_delay_restore_timer: int = Field( + alias="vpcDelayRestoreTimer", + description="vPC delay restore timer", + ge=1, + le=3600, + default=150 + ) + + # Loopback Configuration + bgp_loopback_id: int = Field(alias="bgpLoopbackId", description="BGP loopback interface ID", ge=0, le=1023, default=0) + nve_loopback_id: int = Field(alias="nveLoopbackId", description="NVE loopback interface ID", ge=0, le=1023, default=1) + route_reflector_count: int = Field( + alias="routeReflectorCount", + description="Number of route reflectors", + ge=1, + le=4, + default=2 + ) + + # Templates + vrf_template: str = Field(alias="vrfTemplate", description="VRF template", default="Default_VRF_Universal") + network_template: str = Field(alias="networkTemplate", description="Network template", default="Default_Network_Universal") + vrf_extension_template: str = Field( + alias="vrfExtensionTemplate", + description="VRF extension template", + default="Default_VRF_Extension_Universal" + ) + network_extension_template: str = Field( + alias="networkExtensionTemplate", + description="Network extension template", + default="Default_Network_Extension_Universal" + ) + + # Optional Advanced Settings + performance_monitoring: bool = Field(alias="performanceMonitoring", description="Enable performance monitoring", default=False) + tenant_dhcp: bool = Field(alias="tenantDhcp", description="Enable tenant DHCP", default=True) + advertise_physical_ip: bool = Field(alias="advertisePhysicalIp", description="Advertise physical IP", default=False) + advertise_physical_ip_on_border: bool = Field( + alias="advertisePhysicalIpOnBorder", + description="Advertise physical IP on border", + default=True + ) + + # Protocol Settings + bgp_authentication: bool = Field(alias="bgpAuthentication", description="Enable BGP authentication", default=False) + bgp_authentication_key_type: str = Field( + alias="bgpAuthenticationKeyType", + description="BGP authentication key type", + default="3des" + ) + bfd: bool = Field(description="Enable BFD", default=False) + bfd_ibgp: bool = Field(alias="bfdIbgp", description="Enable BFD for iBGP", default=False) + + # Management Settings + nxapi: bool = Field(description="Enable NX-API", default=False) + nxapi_http: bool = Field(alias="nxapiHttp", description="Enable NX-API HTTP", default=False) + nxapi_https_port: int = Field(alias="nxapiHttpsPort", description="NX-API HTTPS port", ge=1, le=65535, default=443) + nxapi_http_port: int = Field(alias="nxapiHttpPort", description="NX-API HTTP port", ge=1, le=65535, default=80) + + # Bootstrap Settings + day0_bootstrap: bool = Field(alias="day0Bootstrap", description="Enable day-0 bootstrap", default=False) + bootstrap_subnet_collection: List[BootstrapSubnetModel] = Field( + alias="bootstrapSubnetCollection", + description="Bootstrap subnet collection", + default_factory=list + ) + + # Netflow Settings + netflow_settings: NetflowSettingsModel = Field( + alias="netflowSettings", + description="Netflow configuration", + default_factory=NetflowSettingsModel + ) + + # Multicast Settings + rendezvous_point_count: int = Field( + alias="rendezvousPointCount", + description="Number of rendezvous points", + ge=1, + le=4, + default=2 + ) + rendezvous_point_loopback_id: int = Field( + alias="rendezvousPointLoopbackId", + description="RP loopback interface ID", + ge=0, + le=1023, + default=254 + ) + + # System Settings + snmp_trap: bool = Field(alias="snmpTrap", description="Enable SNMP traps", default=True) + cdp: bool = Field(description="Enable CDP", default=False) + real_time_interface_statistics_collection: bool = Field( + alias="realTimeInterfaceStatisticsCollection", + description="Enable real-time interface statistics", + default=False + ) + tcam_allocation: bool = Field(alias="tcamAllocation", description="Enable TCAM allocation", default=True) + + # VPC Extended Configuration + vpc_peer_link_port_channel_id: str = Field(alias="vpcPeerLinkPortChannelId", description="vPC peer link port-channel ID", default="500") + vpc_ipv6_neighbor_discovery_sync: bool = Field( + alias="vpcIpv6NeighborDiscoverySync", description="Enable vPC IPv6 ND sync", default=True + ) + vpc_layer3_peer_router: bool = Field(alias="vpcLayer3PeerRouter", description="Enable vPC layer-3 peer router", default=True) + vpc_tor_delay_restore_timer: int = Field(alias="vpcTorDelayRestoreTimer", description="vPC TOR delay restore timer", default=30) + fabric_vpc_domain_id: bool = Field(alias="fabricVpcDomainId", description="Enable fabric vPC domain ID", default=False) + shared_vpc_domain_id: int = Field(alias="sharedVpcDomainId", description="Shared vPC domain ID", default=1) + fabric_vpc_qos: bool = Field(alias="fabricVpcQos", description="Enable fabric vPC QoS", default=False) + fabric_vpc_qos_policy_name: str = Field( + alias="fabricVpcQosPolicyName", description="Fabric vPC QoS policy name", default="spine_qos_for_fabric_vpc_peering" + ) + enable_peer_switch: bool = Field(alias="enablePeerSwitch", description="Enable peer switch", default=False) + + # Bootstrap / Day-0 / DHCP + local_dhcp_server: bool = Field(alias="localDhcpServer", description="Enable local DHCP server", default=False) + dhcp_protocol_version: str = Field(alias="dhcpProtocolVersion", description="DHCP protocol version", default="dhcpv4") + dhcp_start_address: str = Field(alias="dhcpStartAddress", description="DHCP start address", default="") + dhcp_end_address: str = Field(alias="dhcpEndAddress", description="DHCP end address", default="") + management_gateway: str = Field(alias="managementGateway", description="Management gateway", default="") + management_ipv4_prefix: int = Field(alias="managementIpv4Prefix", description="Management IPv4 prefix length", default=24) + management_ipv6_prefix: int = Field(alias="managementIpv6Prefix", description="Management IPv6 prefix length", default=64) + extra_config_nxos_bootstrap: str = Field(alias="extraConfigNxosBootstrap", description="Extra NX-OS bootstrap config", default="") + un_numbered_bootstrap_loopback_id: int = Field( + alias="unNumberedBootstrapLoopbackId", description="Unnumbered bootstrap loopback ID", default=253 + ) + un_numbered_dhcp_start_address: str = Field(alias="unNumberedDhcpStartAddress", description="Unnumbered DHCP start address", default="") + un_numbered_dhcp_end_address: str = Field(alias="unNumberedDhcpEndAddress", description="Unnumbered DHCP end address", default="") + inband_management: bool = Field(alias="inbandManagement", description="Enable in-band management", default=False) + inband_dhcp_servers: List[str] = Field(alias="inbandDhcpServers", description="In-band DHCP servers", default_factory=list) + seed_switch_core_interfaces: List[str] = Field( + alias="seedSwitchCoreInterfaces", description="Seed switch core interfaces", default_factory=list + ) + spine_switch_core_interfaces: List[str] = Field( + alias="spineSwitchCoreInterfaces", description="Spine switch core interfaces", default_factory=list + ) + + # Backup / Restore + real_time_backup: bool = Field(alias="realTimeBackup", description="Enable real-time backup", default=False) + scheduled_backup: bool = Field(alias="scheduledBackup", description="Enable scheduled backup", default=False) + scheduled_backup_time: str = Field(alias="scheduledBackupTime", description="Scheduled backup time", default="") + + # IPv6 / Dual-Stack + underlay_ipv6: bool = Field(alias="underlayIpv6", description="Enable IPv6 underlay", default=False) + ipv6_multicast_group_subnet: str = Field( + alias="ipv6MulticastGroupSubnet", description="IPv6 multicast group subnet", default="ff1e::/121" + ) + tenant_routed_multicast_ipv6: bool = Field( + alias="tenantRoutedMulticastIpv6", description="Enable tenant routed multicast IPv6", default=False + ) + ipv6_link_local: bool = Field(alias="ipv6LinkLocal", description="Enable IPv6 link-local", default=True) + ipv6_subnet_target_mask: int = Field(alias="ipv6SubnetTargetMask", description="IPv6 subnet target mask", default=126) + ipv6_subnet_range: str = Field(alias="ipv6SubnetRange", description="IPv6 subnet range", default="fd00::a04:0/112") + bgp_loopback_ipv6_range: str = Field(alias="bgpLoopbackIpv6Range", description="BGP loopback IPv6 range", default="fd00::a02:0/119") + nve_loopback_ipv6_range: str = Field(alias="nveLoopbackIpv6Range", description="NVE loopback IPv6 range", default="fd00::a03:0/118") + ipv6_anycast_rendezvous_point_ip_range: str = Field( + alias="ipv6AnycastRendezvousPointIpRange", description="IPv6 anycast RP IP range", default="fd00::254:254:0/118" + ) + + # Multicast / Rendezvous Point Extended + mvpn_vrf_route_import_id: bool = Field(alias="mvpnVrfRouteImportId", description="Enable MVPN VRF route import ID", default=True) + mvpn_vrf_route_import_id_range: str = Field( + alias="mvpnVrfRouteImportIdRange", description="MVPN VRF route import ID range", default="" + ) + vrf_route_import_id_reallocation: bool = Field( + alias="vrfRouteImportIdReallocation", description="Enable VRF route import ID reallocation", default=False + ) + l3vni_multicast_group: str = Field(alias="l3vniMulticastGroup", description="L3 VNI multicast group", default="239.1.1.0") + l3_vni_ipv6_multicast_group: str = Field(alias="l3VniIpv6MulticastGroup", description="L3 VNI IPv6 multicast group", default="ff1e::") + rendezvous_point_mode: str = Field(alias="rendezvousPointMode", description="Rendezvous point mode", default="asm") + phantom_rendezvous_point_loopback_id1: int = Field( + alias="phantomRendezvousPointLoopbackId1", description="Phantom RP loopback ID 1", default=2 + ) + phantom_rendezvous_point_loopback_id2: int = Field( + alias="phantomRendezvousPointLoopbackId2", description="Phantom RP loopback ID 2", default=3 + ) + phantom_rendezvous_point_loopback_id3: int = Field( + alias="phantomRendezvousPointLoopbackId3", description="Phantom RP loopback ID 3", default=4 + ) + phantom_rendezvous_point_loopback_id4: int = Field( + alias="phantomRendezvousPointLoopbackId4", description="Phantom RP loopback ID 4", default=5 + ) + anycast_loopback_id: int = Field(alias="anycastLoopbackId", description="Anycast loopback ID", default=10) + + # VRF Lite / Sub-Interface + sub_interface_dot1q_range: str = Field(alias="subInterfaceDot1qRange", description="Sub-interface 802.1q range", default="2-511") + vrf_lite_auto_config: str = Field(alias="vrfLiteAutoConfig", description="VRF lite auto-config mode", default="manual") + vrf_lite_subnet_range: str = Field(alias="vrfLiteSubnetRange", description="VRF lite subnet range", default="10.33.0.0/16") + vrf_lite_subnet_target_mask: int = Field(alias="vrfLiteSubnetTargetMask", description="VRF lite subnet target mask", default=30) + auto_unique_vrf_lite_ip_prefix: bool = Field( + alias="autoUniqueVrfLiteIpPrefix", description="Auto unique VRF lite IP prefix", default=False + ) + auto_symmetric_vrf_lite: bool = Field(alias="autoSymmetricVrfLite", description="Auto symmetric VRF lite", default=False) + auto_vrf_lite_default_vrf: bool = Field(alias="autoVrfLiteDefaultVrf", description="Auto VRF lite default VRF", default=False) + auto_symmetric_default_vrf: bool = Field(alias="autoSymmetricDefaultVrf", description="Auto symmetric default VRF", default=False) + default_vrf_redistribution_bgp_route_map: str = Field( + alias="defaultVrfRedistributionBgpRouteMap", description="Default VRF redistribution BGP route map", default="extcon-rmap-filter" + ) + + # Per-VRF Loopback + per_vrf_loopback_auto_provision: bool = Field( + alias="perVrfLoopbackAutoProvision", description="Per-VRF loopback auto-provision", default=False + ) + per_vrf_loopback_ip_range: str = Field( + alias="perVrfLoopbackIpRange", description="Per-VRF loopback IP range", default="10.5.0.0/22" + ) + per_vrf_loopback_auto_provision_ipv6: bool = Field( + alias="perVrfLoopbackAutoProvisionIpv6", description="Per-VRF loopback auto-provision IPv6", default=False + ) + per_vrf_loopback_ipv6_range: str = Field( + alias="perVrfLoopbackIpv6Range", description="Per-VRF loopback IPv6 range", default="fd00::a05:0/112" + ) + per_vrf_unique_loopback_auto_provision: bool = Field( + alias="perVrfUniqueLoopbackAutoProvision", description="Per-VRF unique loopback auto-provision", default=False + ) + per_vrf_unique_loopback_ip_range: str = Field( + alias="perVrfUniqueLoopbackIpRange", description="Per-VRF unique loopback IP range", default="10.6.0.0/22" + ) + per_vrf_unique_loopback_auto_provision_v6: bool = Field( + alias="perVrfUniqueLoopbackAutoProvisionV6", description="Per-VRF unique loopback auto-provision IPv6", default=False + ) + per_vrf_unique_loopback_ipv6_range: str = Field( + alias="perVrfUniqueLoopbackIpv6Range", description="Per-VRF unique loopback IPv6 range", default="fd00::a06:0/112" + ) + + # Authentication — BGP Extended + bgp_authentication_key: str = Field(alias="bgpAuthenticationKey", description="BGP authentication key", default="") + + # Authentication — PIM + pim_hello_authentication: bool = Field(alias="pimHelloAuthentication", description="Enable PIM hello authentication", default=False) + pim_hello_authentication_key: str = Field(alias="pimHelloAuthenticationKey", description="PIM hello authentication key", default="") + + # Authentication — BFD + bfd_authentication: bool = Field(alias="bfdAuthentication", description="Enable BFD authentication", default=False) + bfd_authentication_key_id: int = Field(alias="bfdAuthenticationKeyId", description="BFD authentication key ID", default=100) + bfd_authentication_key: str = Field(alias="bfdAuthenticationKey", description="BFD authentication key", default="") + bfd_ospf: bool = Field(alias="bfdOspf", description="Enable BFD for OSPF", default=False) + bfd_isis: bool = Field(alias="bfdIsis", description="Enable BFD for IS-IS", default=False) + bfd_pim: bool = Field(alias="bfdPim", description="Enable BFD for PIM", default=False) + + # Authentication — OSPF + ospf_authentication: bool = Field(alias="ospfAuthentication", description="Enable OSPF authentication", default=False) + ospf_authentication_key_id: int = Field(alias="ospfAuthenticationKeyId", description="OSPF authentication key ID", default=127) + ospf_authentication_key: str = Field(alias="ospfAuthenticationKey", description="OSPF authentication key", default="") + + # IS-IS + isis_level: IsisLevelEnum = Field(alias="isisLevel", description="IS-IS level", default=IsisLevelEnum.LEVEL_2) + isis_area_number: str = Field(alias="isisAreaNumber", description="IS-IS area number", default="0001") + isis_point_to_point: bool = Field(alias="isisPointToPoint", description="IS-IS point-to-point", default=True) + isis_authentication: bool = Field(alias="isisAuthentication", description="Enable IS-IS authentication", default=False) + isis_authentication_keychain_name: str = Field( + alias="isisAuthenticationKeychainName", description="IS-IS authentication keychain name", default="" + ) + isis_authentication_keychain_key_id: int = Field( + alias="isisAuthenticationKeychainKeyId", description="IS-IS authentication keychain key ID", default=127 + ) + isis_authentication_key: str = Field(alias="isisAuthenticationKey", description="IS-IS authentication key", default="") + isis_overload: bool = Field(alias="isisOverload", description="Enable IS-IS overload bit", default=True) + isis_overload_elapse_time: int = Field(alias="isisOverloadElapseTime", description="IS-IS overload elapse time", default=60) + + # MACsec + macsec: bool = Field(description="Enable MACsec", default=False) + macsec_cipher_suite: str = Field(alias="macsecCipherSuite", description="MACsec cipher suite", default="GCM-AES-XPN-256") + macsec_key_string: str = Field(alias="macsecKeyString", description="MACsec key string", default="") + macsec_algorithm: str = Field(alias="macsecAlgorithm", description="MACsec algorithm", default="AES_128_CMAC") + macsec_fallback_key_string: str = Field(alias="macsecFallbackKeyString", description="MACsec fallback key string", default="") + macsec_fallback_algorithm: str = Field(alias="macsecFallbackAlgorithm", description="MACsec fallback algorithm", default="AES_128_CMAC") + macsec_report_timer: int = Field(alias="macsecReportTimer", description="MACsec report timer", default=5) + + # VRF Lite MACsec + vrf_lite_macsec: bool = Field(alias="vrfLiteMacsec", description="Enable VRF lite MACsec", default=False) + vrf_lite_macsec_cipher_suite: str = Field( + alias="vrfLiteMacsecCipherSuite", description="VRF lite MACsec cipher suite", default="GCM-AES-XPN-256" + ) + vrf_lite_macsec_key_string: str = Field(alias="vrfLiteMacsecKeyString", description="VRF lite MACsec key string", default="") + vrf_lite_macsec_algorithm: str = Field( + alias="vrfLiteMacsecAlgorithm", description="VRF lite MACsec algorithm", default="AES_128_CMAC" + ) + vrf_lite_macsec_fallback_key_string: str = Field( + alias="vrfLiteMacsecFallbackKeyString", description="VRF lite MACsec fallback key string", default="" + ) + vrf_lite_macsec_fallback_algorithm: str = Field( + alias="vrfLiteMacsecFallbackAlgorithm", description="VRF lite MACsec fallback algorithm", default="AES_128_CMAC" + ) + + # Quantum Key Distribution / Trustpoint + quantum_key_distribution: bool = Field(alias="quantumKeyDistribution", description="Enable quantum key distribution", default=False) + quantum_key_distribution_profile_name: str = Field( + alias="quantumKeyDistributionProfileName", description="Quantum key distribution profile name", default="" + ) + key_management_entity_server_ip: str = Field( + alias="keyManagementEntityServerIp", description="Key management entity server IP", default="" + ) + key_management_entity_server_port: int = Field( + alias="keyManagementEntityServerPort", description="Key management entity server port", default=0 + ) + trustpoint_label: str = Field(alias="trustpointLabel", description="Trustpoint label", default="") + skip_certificate_verification: bool = Field( + alias="skipCertificateVerification", description="Skip certificate verification", default=False + ) + + # BGP / Routing Enhancements + auto_bgp_neighbor_description: bool = Field( + alias="autoBgpNeighborDescription", description="Auto BGP neighbor description", default=True + ) + ibgp_peer_template: str = Field(alias="ibgpPeerTemplate", description="iBGP peer template", default="") + leaf_ibgp_peer_template: str = Field(alias="leafIbgpPeerTemplate", description="Leaf iBGP peer template", default="") + link_state_routing_tag: str = Field(alias="linkStateRoutingTag", description="Link state routing tag", default="UNDERLAY") + static_underlay_ip_allocation: bool = Field( + alias="staticUnderlayIpAllocation", description="Static underlay IP allocation", default=False + ) + router_id_range: str = Field(alias="routerIdRange", description="Router ID range", default="10.2.0.0/23") + + # Security Group Tags (SGT) + security_group_tag: bool = Field(alias="securityGroupTag", description="Enable security group tag", default=False) + security_group_tag_prefix: str = Field(alias="securityGroupTagPrefix", description="SGT prefix", default="SG_") + security_group_tag_mac_segmentation: bool = Field( + alias="securityGroupTagMacSegmentation", description="Enable SGT MAC segmentation", default=False + ) + security_group_tag_id_range: str = Field( + alias="securityGroupTagIdRange", description="SGT ID range", default="10000-14000" + ) + security_group_tag_preprovision: bool = Field( + alias="securityGroupTagPreprovision", description="Enable SGT preprovision", default=False + ) + security_group_status: SecurityGroupStatusEnum = Field(alias="securityGroupStatus", description="Security group status", default=SecurityGroupStatusEnum.DISABLED) + + # Queuing / QoS + default_queuing_policy: bool = Field(alias="defaultQueuingPolicy", description="Enable default queuing policy", default=False) + default_queuing_policy_cloudscale: str = Field( + alias="defaultQueuingPolicyCloudscale", description="Default queuing policy cloudscale", default="queuing_policy_default_8q_cloudscale" + ) + default_queuing_policy_r_series: str = Field( + alias="defaultQueuingPolicyRSeries", description="Default queuing policy R-Series", default="queuing_policy_default_r_series" + ) + default_queuing_policy_other: str = Field( + alias="defaultQueuingPolicyOther", description="Default queuing policy other", default="queuing_policy_default_other" + ) + aiml_qos: bool = Field(alias="aimlQos", description="Enable AI/ML QoS", default=False) + aiml_qos_policy: str = Field(alias="aimlQosPolicy", description="AI/ML QoS policy", default="400G") + roce_v2: str = Field(alias="roceV2", description="RoCEv2 DSCP value", default="26") + cnp: str = Field(description="CNP value", default="48") + wred_min: int = Field(alias="wredMin", description="WRED minimum threshold", default=950) + wred_max: int = Field(alias="wredMax", description="WRED maximum threshold", default=3000) + wred_drop_probability: int = Field(alias="wredDropProbability", description="WRED drop probability", default=7) + wred_weight: int = Field(alias="wredWeight", description="WRED weight", default=0) + bandwidth_remaining: int = Field(alias="bandwidthRemaining", description="Bandwidth remaining percentage", default=50) + dlb: bool = Field(description="Enable dynamic load balancing", default=False) + dlb_mode: str = Field(alias="dlbMode", description="DLB mode", default="flowlet") + dlb_mixed_mode_default: str = Field(alias="dlbMixedModeDefault", description="DLB mixed mode default", default="ecmp") + flowlet_aging: int = Field(alias="flowletAging", description="Flowlet aging interval", default=1) + flowlet_dscp: str = Field(alias="flowletDscp", description="Flowlet DSCP value", default="") + per_packet_dscp: str = Field(alias="perPacketDscp", description="Per-packet DSCP value", default="") + ai_load_sharing: bool = Field(alias="aiLoadSharing", description="Enable AI load sharing", default=False) + priority_flow_control_watch_interval: int = Field( + alias="priorityFlowControlWatchInterval", description="Priority flow control watch interval", default=101 + ) + + # PTP + ptp: bool = Field(description="Enable PTP", default=False) + ptp_loopback_id: int = Field(alias="ptpLoopbackId", description="PTP loopback ID", default=0) + ptp_domain_id: int = Field(alias="ptpDomainId", description="PTP domain ID", default=0) + ptp_vlan_id: int = Field(alias="ptpVlanId", description="PTP VLAN ID", default=2) + + # STP + stp_root_option: StpRootOptionEnum = Field(alias="stpRootOption", description="STP root option", default=StpRootOptionEnum.UNMANAGED) + stp_vlan_range: str = Field(alias="stpVlanRange", description="STP VLAN range", default="1-3967") + mst_instance_range: str = Field(alias="mstInstanceRange", description="MST instance range", default="0") + stp_bridge_priority: int = Field(alias="stpBridgePriority", description="STP bridge priority", default=0) + + # MPLS Handoff + mpls_handoff: bool = Field(alias="mplsHandoff", description="Enable MPLS handoff", default=False) + mpls_loopback_identifier: int = Field(alias="mplsLoopbackIdentifier", description="MPLS loopback identifier", default=101) + mpls_isis_area_number: str = Field(alias="mplsIsisAreaNumber", description="MPLS IS-IS area number", default="0001") + mpls_loopback_ip_range: str = Field(alias="mplsLoopbackIpRange", description="MPLS loopback IP range", default="10.101.0.0/25") + + # Private VLAN + private_vlan: bool = Field(alias="privateVlan", description="Enable private VLAN", default=False) + default_private_vlan_secondary_network_template: str = Field( + alias="defaultPrivateVlanSecondaryNetworkTemplate", + description="Default private VLAN secondary network template", + default="Pvlan_Secondary_Network" + ) + allow_vlan_on_leaf_tor_pairing: str = Field( + alias="allowVlanOnLeafTorPairing", description="Allow VLAN on leaf/TOR pairing", default="none" + ) + + # Leaf / TOR + leaf_tor_id_range: bool = Field(alias="leafTorIdRange", description="Enable leaf/TOR ID range", default=False) + leaf_tor_vpc_port_channel_id_range: str = Field( + alias="leafTorVpcPortChannelIdRange", description="Leaf/TOR vPC port-channel ID range", default="1-499" + ) + + # Resource ID Ranges + l3_vni_no_vlan_default_option: bool = Field( + alias="l3VniNoVlanDefaultOption", description="L3 VNI no-VLAN default option", default=False + ) + ip_service_level_agreement_id_range: str = Field( + alias="ipServiceLevelAgreementIdRange", description="IP SLA ID range", default="10000-19999" + ) + object_tracking_number_range: str = Field( + alias="objectTrackingNumberRange", description="Object tracking number range", default="100-299" + ) + service_network_vlan_range: str = Field( + alias="serviceNetworkVlanRange", description="Service network VLAN range", default="3000-3199" + ) + route_map_sequence_number_range: str = Field( + alias="routeMapSequenceNumberRange", description="Route map sequence number range", default="1-65534" + ) + + # DNS / NTP / Syslog Collections + ntp_server_collection: List[str] = Field(default_factory=lambda: ["string"], alias="ntpServerCollection") + ntp_server_vrf_collection: List[str] = Field(default_factory=lambda: ["string"], alias="ntpServerVrfCollection") + dns_collection: List[str] = Field(default_factory=lambda: ["5.192.28.174"], alias="dnsCollection") + dns_vrf_collection: List[str] = Field(default_factory=lambda: ["string"], alias="dnsVrfCollection") + syslog_server_collection: List[str] = Field(default_factory=lambda: ["string"], alias="syslogServerCollection") + syslog_server_vrf_collection: List[str] = Field(default_factory=lambda: ["string"], alias="syslogServerVrfCollection") + syslog_severity_collection: List[int] = Field(default_factory=lambda: [7], alias="syslogSeverityCollection", description="Syslog severity levels (0-7)") + + # Extra Config / Pre-Interface Config / AAA / Banner + banner: str = Field(description="Fabric banner text", default="") + extra_config_leaf: str = Field(alias="extraConfigLeaf", description="Extra leaf config", default="") + extra_config_spine: str = Field(alias="extraConfigSpine", description="Extra spine config", default="") + extra_config_tor: str = Field(alias="extraConfigTor", description="Extra TOR config", default="") + extra_config_intra_fabric_links: str = Field( + alias="extraConfigIntraFabricLinks", description="Extra intra-fabric links config", default="" + ) + extra_config_aaa: str = Field(alias="extraConfigAaa", description="Extra AAA config", default="") + aaa: bool = Field(description="Enable AAA", default=False) + pre_interface_config_leaf: str = Field(alias="preInterfaceConfigLeaf", description="Pre-interface leaf config", default="") + pre_interface_config_spine: str = Field(alias="preInterfaceConfigSpine", description="Pre-interface spine config", default="") + pre_interface_config_tor: str = Field(alias="preInterfaceConfigTor", description="Pre-interface TOR config", default="") + + # System / Compliance / OAM / Misc + anycast_border_gateway_advertise_physical_ip: bool = Field( + alias="anycastBorderGatewayAdvertisePhysicalIp", description="Anycast border gateway advertise physical IP", default=False + ) + greenfield_debug_flag: GreenfieldDebugFlagEnum = Field(alias="greenfieldDebugFlag", description="Greenfield debug flag", default=GreenfieldDebugFlagEnum.DISABLE) + interface_statistics_load_interval: int = Field( + alias="interfaceStatisticsLoadInterval", description="Interface statistics load interval", default=10 + ) + nve_hold_down_timer: int = Field(alias="nveHoldDownTimer", description="NVE hold-down timer", default=180) + next_generation_oam: bool = Field(alias="nextGenerationOAM", description="Enable next-generation OAM", default=True) + ngoam_south_bound_loop_detect: bool = Field( + alias="ngoamSouthBoundLoopDetect", description="Enable NGOAM south bound loop detect", default=False + ) + ngoam_south_bound_loop_detect_probe_interval: int = Field( + alias="ngoamSouthBoundLoopDetectProbeInterval", description="NGOAM south bound loop detect probe interval", default=300 + ) + ngoam_south_bound_loop_detect_recovery_interval: int = Field( + alias="ngoamSouthBoundLoopDetectRecoveryInterval", description="NGOAM south bound loop detect recovery interval", default=600 + ) + strict_config_compliance_mode: bool = Field( + alias="strictConfigComplianceMode", description="Enable strict config compliance mode", default=False + ) + advanced_ssh_option: bool = Field(alias="advancedSshOption", description="Enable advanced SSH option", default=False) + copp_policy: CoppPolicyEnum = Field(alias="coppPolicy", description="CoPP policy", default=CoppPolicyEnum.STRICT) + power_redundancy_mode: str = Field(alias="powerRedundancyMode", description="Power redundancy mode", default="redundant") + host_interface_admin_state: bool = Field( + alias="hostInterfaceAdminState", description="Host interface admin state", default=True + ) + heartbeat_interval: int = Field(alias="heartbeatInterval", description="Heartbeat interval", default=190) + policy_based_routing: bool = Field(alias="policyBasedRouting", description="Enable policy-based routing", default=False) + brownfield_network_name_format: str = Field( + alias="brownfieldNetworkNameFormat", description="Brownfield network name format", default="Auto_Net_VNI$$VNI$$_VLAN$$VLAN_ID$$" + ) + brownfield_skip_overlay_network_attachments: bool = Field( + alias="brownfieldSkipOverlayNetworkAttachments", description="Skip brownfield overlay network attachments", default=False + ) + allow_smart_switch_onboarding: bool = Field( + alias="allowSmartSwitchOnboarding", description="Allow smart switch onboarding", default=False + ) + + # Hypershield / Connectivity + connectivity_domain_name: Optional[str] = Field( + alias="connectivityDomainName", description="Domain name to connect to Hypershield", default=None + ) + hypershield_connectivity_proxy_server: Optional[str] = Field( + alias="hypershieldConnectivityProxyServer", + description="IPv4 address, IPv6 address, or DNS name of the proxy server for Hypershield communication", + default=None + ) + hypershield_connectivity_proxy_server_port: Optional[int] = Field( + alias="hypershieldConnectivityProxyServerPort", + description="Proxy port number for communication with Hypershield", + default=None + ) + hypershield_connectivity_source_intf: Optional[str] = Field( + alias="hypershieldConnectivitySourceIntf", + description="Loopback interface on smart switch for communication with Hypershield", + default=None + ) + + @field_validator("bgp_asn") + @classmethod + def validate_bgp_asn(cls, value: str) -> str: + """ + # Summary + + Validate BGP ASN format and range. + + ## Description + + Accepts either a plain integer ASN (1-4294967295) or dotted four-byte + ASN notation in the form ``MMMM.NNNN`` where both parts are in the + range 1-65535 / 0-65535 respectively. + + ## Raises + + - `ValueError` - If the value does not match the expected ASN format + """ + if not _BGP_ASN_RE.match(value): + raise ValueError( + f"Invalid BGP ASN '{value}'. " + "Expected a plain integer (1-4294967295) or dotted notation (1-65535.0-65535)." + ) + return value + + @field_validator("site_id") + @classmethod + def validate_site_id(cls, value: str) -> str: + """ + # Summary + + Validate site ID format. + + ## Raises + + - `ValueError` - If site ID is not numeric or outside valid range + """ + + # If value is empty string (default), skip validation (will be set to BGP ASN later if still empty) + if value == "": + return value + + if not value.isdigit(): + raise ValueError(f"Site ID must be numeric, got: {value}") + + site_id_int = int(value) + if not (1 <= site_id_int <= 281474976710655): + raise ValueError(f"Site ID must be between 1 and 281474976710655, got: {site_id_int}") + + return value + + @field_validator("anycast_gateway_mac") + @classmethod + def validate_mac_address(cls, value: str) -> str: + """ + # Summary + + Validate MAC address format. + + ## Raises + + - `ValueError` - If MAC address format is invalid + """ + mac_pattern = re.compile(r'^([0-9a-fA-F]{4}\.){2}[0-9a-fA-F]{4}$') + if not mac_pattern.match(value): + raise ValueError(f"Invalid MAC address format, expected xxxx.xxxx.xxxx, got: {value}") + + return value.lower() + + +class FabricIbgpModel(NDBaseModel): + """ + # Summary + + Complete model for creating a new iBGP VXLAN fabric. + + This model combines all necessary components for fabric creation including + basic fabric properties, management settings, telemetry, and streaming configuration. + + ## Raises + + - `ValueError` - If required fields are missing or invalid + - `TypeError` - If field types don't match expected types + """ + + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True, + populate_by_name=True, + extra="allow" # Allow extra fields from API responses + ) + + identifiers: ClassVar[Optional[List[str]]] = ["name"] + identifier_strategy: ClassVar[Optional[Literal["single", "composite", "hierarchical", "singleton"]]] = "single" + + # Basic Fabric Properties + category: Literal["fabric"] = Field(description="Resource category", default="fabric") + name: str = Field(description="Fabric name", min_length=1, max_length=64) + location: Optional[LocationModel] = Field(description="Geographic location of the fabric", default=None) + + # License and Operations + license_tier: LicenseTierEnum = Field(alias="licenseTier", description="License tier", default=LicenseTierEnum.PREMIER) + alert_suspend: AlertSuspendEnum = Field(alias="alertSuspend", description="Alert suspension state", default=AlertSuspendEnum.DISABLED) + telemetry_collection: bool = Field(alias="telemetryCollection", description="Enable telemetry collection", default=False) + telemetry_collection_type: str = Field(alias="telemetryCollectionType", description="Telemetry collection type", default="outOfBand") + telemetry_streaming_protocol: str = Field(alias="telemetryStreamingProtocol", description="Telemetry streaming protocol", default="ipv4") + telemetry_source_interface: str = Field(alias="telemetrySourceInterface", description="Telemetry source interface", default="") + telemetry_source_vrf: str = Field(alias="telemetrySourceVrf", description="Telemetry source VRF", default="") + security_domain: str = Field(alias="securityDomain", description="Security domain", default="all") + + # Core Management Configuration + management: Optional[VxlanIbgpManagementModel] = Field(description="iBGP VXLAN management configuration", default=None) + + # Optional Advanced Settings + telemetry_settings: Optional[TelemetrySettingsModel] = Field( + alias="telemetrySettings", + description="Telemetry configuration", + default=None + ) + external_streaming_settings: ExternalStreamingSettingsModel = Field( + alias="externalStreamingSettings", + description="External streaming settings", + default_factory=ExternalStreamingSettingsModel + ) + + @field_validator("name") + @classmethod + def validate_fabric_name(cls, value: str) -> str: + """ + # Summary + + Validate fabric name format and characters. + + ## Raises + + - `ValueError` - If name contains invalid characters or format + """ + if not re.match(r'^[a-zA-Z0-9_-]+$', value): + raise ValueError(f"Fabric name can only contain letters, numbers, underscores, and hyphens, got: {value}") + + return value + + @model_validator(mode='after') + def validate_fabric_consistency(self) -> 'FabricModel': + """ + # Summary + + Validate consistency between fabric settings and management configuration. + + ## Raises + + - `ValueError` - If fabric settings are inconsistent + """ + # Ensure management type matches model type + if self.management is not None and self.management.type != FabricTypeEnum.VXLAN_IBGP: + raise ValueError(f"Management type must be {FabricTypeEnum.VXLAN_IBGP}") + + # Propagate fabric name to management model + if self.management is not None: + self.management.name = self.name + + # Propagate BGP ASN to Site ID management model if not set + if self.management is not None and self.management.site_id == "": + bgp_asn = self.management.bgp_asn + if "." in bgp_asn: + # asdot notation (High.Low) → convert to asplain decimal: (High × 65536) + Low + high, low = bgp_asn.split(".") + self.management.site_id = str(int(high) * 65536 + int(low)) + else: + # Already plain decimal + self.management.site_id = bgp_asn + + # Validate telemetry consistency + if self.telemetry_collection and self.telemetry_settings is None: + # Auto-create default telemetry settings if collection is enabled + self.telemetry_settings = TelemetrySettingsModel() + + return self + + # TODO: to generate from Fields (low priority) + @classmethod + def get_argument_spec(cls) -> Dict: + return dict( + state={ + "type": "str", + "default": "merged", + "choices": ["merged", "replaced", "deleted", "overridden", "query"], + }, + config={"required": False, "type": "list", "elements": "dict"}, + ) + + +# Export all models for external use +__all__ = [ + "LocationModel", + "NetflowExporterModel", + "NetflowRecordModel", + "NetflowMonitorModel", + "NetflowSettingsModel", + "BootstrapSubnetModel", + "TelemetryFlowCollectionModel", + "TelemetryMicroburstModel", + "TelemetryAnalysisSettingsModel", + "TelemetryEnergyManagementModel", + "TelemetrySettingsModel", + "ExternalStreamingSettingsModel", + "VxlanIbgpManagementModel", + "FabricModel", + "FabricDeleteModel", + "FabricTypeEnum", + "AlertSuspendEnum", + "LicenseTierEnum", + "ReplicationModeEnum", + "OverlayModeEnum", + "LinkStateRoutingProtocolEnum" +] \ No newline at end of file diff --git a/plugins/module_utils/models/nested.py b/plugins/module_utils/models/nested.py new file mode 100644 index 00000000..c3af1d71 --- /dev/null +++ b/plugins/module_utils/models/nested.py @@ -0,0 +1,18 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +from typing import List, ClassVar +from ansible_collections.cisco.nd.plugins.module_utils.models.base import NDBaseModel + + +class NDNestedModel(NDBaseModel): + """ + Base for nested models without identifiers. + """ + + # NOTE: model_config, ClassVar, and Fields can be overwritten here if needed + + identifiers: ClassVar[List[str]] = [] diff --git a/plugins/module_utils/nd.py b/plugins/module_utils/nd.py index 03ffc85f..50a5eeb2 100644 --- a/plugins/module_utils/nd.py +++ b/plugins/module_utils/nd.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2021, Lionel Hercot (@lhercot) # Copyright: (c) 2022, Cindy Zhao (@cizhao) # Copyright: (c) 2022, Akini Ross (@akinross) @@ -9,8 +7,6 @@ from __future__ import absolute_import, division, print_function from functools import reduce -__metaclass__ = type - from copy import deepcopy import os import shutil @@ -18,7 +14,6 @@ from ansible.module_utils.basic import json from ansible.module_utils.basic import env_fallback from ansible.module_utils.six import PY3 -from ansible.module_utils.six.moves import filterfalse from ansible.module_utils.six.moves.urllib.parse import urlencode from ansible.module_utils._text import to_native, to_text from ansible.module_utils.connection import Connection @@ -73,53 +68,27 @@ def cmp(a, b): def issubset(subset, superset): - """Recurse through nested dictionary and compare entries""" - - # Both objects are the same object - if subset is superset: - return True + """Recurse through a nested dictionary and check if it is a subset of another.""" - # Both objects are identical - if subset == superset: - return True - - # Both objects have a different type - if isinstance(subset) is not isinstance(superset): + if type(subset) is not type(superset): return False + if not isinstance(subset, dict): + if isinstance(subset, list): + return all(item in superset for item in subset) + return subset == superset + for key, value in subset.items(): - # Ignore empty values if value is None: - return True + continue - # Item from subset is missing from superset if key not in superset: return False - # Item has different types in subset and superset - if isinstance(superset.get(key)) is not isinstance(value): - return False + superset_value = superset.get(key) - # Compare if item values are subset - if isinstance(value, dict): - if not issubset(superset.get(key), value): - return False - elif isinstance(value, list): - try: - # NOTE: Fails for lists of dicts - if not set(value) <= set(superset.get(key)): - return False - except TypeError: - # Fall back to exact comparison for lists of dicts - diff = list(filterfalse(lambda i: i in value, superset.get(key))) + list(filterfalse(lambda j: j in superset.get(key), value)) - if diff: - return False - elif isinstance(value, set): - if not value <= superset.get(key): - return False - else: - if not value == superset.get(key): - return False + if not issubset(value, superset_value): + return False return True @@ -212,7 +181,7 @@ def __init__(self, module): self.previous = dict() self.proposed = dict() self.sent = dict() - self.stdout = None + self.stdout = "" # debug output self.has_modified = False @@ -266,7 +235,7 @@ def request( if file is not None: info = self.connection.send_file_request(method, uri, file, data, None, file_key, file_ext) else: - if data: + if data is not None: info = self.connection.send_request(method, uri, json.dumps(data)) else: info = self.connection.send_request(method, uri) @@ -324,6 +293,8 @@ def request( self.fail_json(msg="ND Error: {0}".format(self.error.get("message")), data=data, info=info) self.error = payload if "code" in payload: + if self.status == 404 and ignore_not_found_error: + return {} self.fail_json(msg="ND Error {code}: {message}".format(**payload), data=data, info=info, payload=payload) elif "messages" in payload and len(payload.get("messages")) > 0: self.fail_json(msg="ND Error {code} ({severity}): {message}".format(**payload["messages"][0]), data=data, info=info, payload=payload) @@ -520,30 +491,27 @@ def get_diff(self, unwanted=None): if not self.existing and self.sent: return True - existing = self.existing - sent = self.sent + existing = deepcopy(self.existing) + sent = deepcopy(self.sent) for key in unwanted: if isinstance(key, str): if key in existing: - try: - del existing[key] - except KeyError: - pass - try: - del sent[key] - except KeyError: - pass + del existing[key] + if key in sent: + del sent[key] elif isinstance(key, list): key_path, last = key[:-1], key[-1] try: existing_parent = reduce(dict.get, key_path, existing) - del existing_parent[last] + if existing_parent is not None: + del existing_parent[last] except KeyError: pass try: sent_parent = reduce(dict.get, key_path, sent) - del sent_parent[last] + if sent_parent is not None: + del sent_parent[last] except KeyError: pass return not issubset(sent, existing) diff --git a/plugins/module_utils/nd_argument_specs.py b/plugins/module_utils/nd_argument_specs.py index 7ef10d04..798ca90f 100644 --- a/plugins/module_utils/nd_argument_specs.py +++ b/plugins/module_utils/nd_argument_specs.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2023, Shreyas Srish (@shrsr) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function -__metaclass__ = type - def ntp_server_spec(): return dict( diff --git a/plugins/module_utils/nd_config_collection.py b/plugins/module_utils/nd_config_collection.py new file mode 100644 index 00000000..832cc132 --- /dev/null +++ b/plugins/module_utils/nd_config_collection.py @@ -0,0 +1,214 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +from typing import Optional, List, Dict, Any, Literal +from copy import deepcopy +from ansible_collections.cisco.nd.plugins.module_utils.models.base import NDBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.types import IdentifierKey + + +class NDConfigCollection: + """ + Nexus Dashboard configuration collection for NDBaseModel instances. + """ + + def __init__(self, model_class: NDBaseModel, items: Optional[List[NDBaseModel]] = None): + """ + Initialize collection. + """ + self._model_class: NDBaseModel = model_class + + # Dual storage + self._items: List[NDBaseModel] = [] + self._index: Dict[IdentifierKey, int] = {} + + if items: + for item in items: + self.add(item) + + def _extract_key(self, item: NDBaseModel) -> IdentifierKey: + """ + Extract identifier key from item. + """ + try: + return item.get_identifier_value() + except Exception as e: + raise ValueError(f"Failed to extract identifier: {e}") from e + + def _rebuild_index(self) -> None: + """Rebuild index from scratch (O(n) operation).""" + self._index.clear() + for index, item in enumerate(self._items): + key = self._extract_key(item) + self._index[key] = index + + # Core Operations + + def add(self, item: NDBaseModel) -> IdentifierKey: + """ + Add item to collection (O(1) operation). + """ + if not isinstance(item, self._model_class): + raise TypeError(f"Item must be instance of {self._model_class.__name__}, " f"got {type(item).__name__}") + + key = self._extract_key(item) + + if key in self._index: + raise ValueError(f"Item with identifier {key} already exists. Use replace() to update") + + position = len(self._items) + self._items.append(item) + self._index[key] = position + + return key + + def get(self, key: IdentifierKey) -> Optional[NDBaseModel]: + """ + Get item by identifier key (O(1) operation). + """ + index = self._index.get(key) + return self._items[index] if index is not None else None + + def replace(self, item: NDBaseModel) -> bool: + """ + Replace existing item with same identifier (O(1) operation). + """ + if not isinstance(item, self._model_class): + raise TypeError(f"Item must be instance of {self._model_class.__name__}, " f"got {type(item).__name__}") + + key = self._extract_key(item) + index = self._index.get(key) + + if index is None: + return False + + self._items[index] = item + return True + + def merge(self, item: NDBaseModel) -> NDBaseModel: + """ + Merge item with existing, or add if not present. + """ + key = self._extract_key(item) + existing = self.get(key) + + if existing is None: + self.add(item) + return item + else: + merged = existing.merge(item) + self.replace(merged) + return merged + + def delete(self, key: IdentifierKey) -> bool: + """ + Delete item by identifier (O(n) operation due to index rebuild) + """ + index = self._index.get(key) + + if index is None: + return False + + del self._items[index] + self._rebuild_index() + + return True + + # Diff Operations + + def get_diff_config(self, new_item: NDBaseModel) -> Literal["new", "no_diff", "changed"]: + """ + Compare single item against collection. + """ + try: + key = self._extract_key(new_item) + except ValueError: + return "new" + + existing = self.get(key) + + if existing is None: + return "new" + + is_subset = existing.get_diff(new_item) + + return "no_diff" if is_subset else "changed" + + def get_diff_collection(self, other: "NDConfigCollection") -> bool: + """ + Check if two collections differ. + """ + if not isinstance(other, NDConfigCollection): + raise TypeError("Argument must be NDConfigCollection") + + if len(self) != len(other): + return True + + for item in other: + if self.get_diff_config(item) != "no_diff": + return True + + for key in self.keys(): + if other.get(key) is None: + return True + + return False + + def get_diff_identifiers(self, other: "NDConfigCollection") -> List[IdentifierKey]: + """ + Get identifiers in self but not in other. + """ + current_keys = set(self.keys()) + other_keys = set(other.keys()) + return list(current_keys - other_keys) + + # Collection Operations + + def __len__(self) -> int: + """Return number of items.""" + return len(self._items) + + def __iter__(self): + """Iterate over items.""" + return iter(self._items) + + def keys(self) -> List[IdentifierKey]: + """Get all identifier keys.""" + return list(self._index.keys()) + + def copy(self) -> "NDConfigCollection": + """Create deep copy of collection.""" + return NDConfigCollection(model_class=self._model_class, items=deepcopy(self._items)) + + # Collection Serialization + + def to_ansible_config(self, **kwargs) -> List[Dict]: + """ + Export as an Ansible config. + """ + return [item.to_config(**kwargs) for item in self._items] + + def to_payload_list(self, **kwargs) -> List[Dict[str, Any]]: + """ + Export as list of API payloads. + """ + return [item.to_payload(**kwargs) for item in self._items] + + @staticmethod + def from_ansible_config(data: List[Dict], model_class: type[NDBaseModel], **kwargs) -> "NDConfigCollection": + """ + Create collection from Ansible config. + """ + items = [model_class.from_config(item_data, **kwargs) for item_data in data] + return NDConfigCollection(model_class=model_class, items=items) + + @staticmethod + def from_api_response(response_data: List[Dict[str, Any]], model_class: type[NDBaseModel], **kwargs) -> "NDConfigCollection": + """ + Create collection from API response. + """ + items = [model_class.from_response(item_data, **kwargs) for item_data in response_data] + return NDConfigCollection(model_class=model_class, items=items) diff --git a/plugins/module_utils/nd_output.py b/plugins/module_utils/nd_output.py new file mode 100644 index 00000000..09759b96 --- /dev/null +++ b/plugins/module_utils/nd_output.py @@ -0,0 +1,65 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +from typing import Dict, Any, Optional, List, Union +from ansible_collections.cisco.nd.plugins.module_utils.nd_config_collection import NDConfigCollection + + +class NDOutput: + def __init__(self, output_level: str): + self._output_level: str = output_level + self._changed: bool = False + self._before: Union[NDConfigCollection, List] = [] + self._after: Union[NDConfigCollection, List] = [] + self._diff: Union[NDConfigCollection, List] = [] + self._proposed: Union[NDConfigCollection, List] = [] + self._logs: List = [] + self._extra: Dict[str, Any] = {} + + def format(self, **kwargs) -> Dict[str, Any]: + if isinstance(self._before, NDConfigCollection) and isinstance(self._after, NDConfigCollection) and self._before.get_diff_collection(self._after): + self._changed = True + + output = { + "output_level": self._output_level, + "changed": self._changed, + "after": self._after.to_ansible_config() if isinstance(self._after, NDConfigCollection) else self._after, + "before": self._before.to_ansible_config() if isinstance(self._before, NDConfigCollection) else self._before, + "diff": self._diff.to_ansible_config() if isinstance(self._diff, NDConfigCollection) else self._diff, + } + + if self._output_level in ("debug", "info"): + output["proposed"] = self._proposed.to_ansible_config() if isinstance(self._proposed, NDConfigCollection) else self._proposed + if self._output_level == "debug": + output["logs"] = self._logs + + if self._extra: + output.update(self._extra) + + output.update(**kwargs) + + return output + + def assign( + self, + after: Optional[NDConfigCollection] = None, + before: Optional[NDConfigCollection] = None, + diff: Optional[NDConfigCollection] = None, + proposed: Optional[NDConfigCollection] = None, + logs: Optional[List] = None, + **kwargs + ) -> None: + if isinstance(after, NDConfigCollection): + self._after = after + if isinstance(before, NDConfigCollection): + self._before = before + if isinstance(diff, NDConfigCollection): + self._diff = diff + if isinstance(proposed, NDConfigCollection): + self._proposed = proposed + if isinstance(logs, List): + self._logs = logs + self._extra.update(**kwargs) diff --git a/plugins/module_utils/nd_state_machine.py b/plugins/module_utils/nd_state_machine.py new file mode 100644 index 00000000..fb812c33 --- /dev/null +++ b/plugins/module_utils/nd_state_machine.py @@ -0,0 +1,165 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +from typing import Type +from ansible.module_utils.basic import AnsibleModule +from ansible_collections.cisco.nd.plugins.module_utils.nd import NDModule +from ansible_collections.cisco.nd.plugins.module_utils.nd_output import NDOutput +from ansible_collections.cisco.nd.plugins.module_utils.nd_config_collection import NDConfigCollection +from ansible_collections.cisco.nd.plugins.module_utils.orchestrators.base import NDBaseOrchestrator +from ansible_collections.cisco.nd.plugins.module_utils.common.exceptions import NDStateMachineError + + +class NDStateMachine: + """ + Generic State Machine for Nexus Dashboard. + """ + + def __init__(self, module: AnsibleModule, model_orchestrator: Type[NDBaseOrchestrator]): + """ + Initialize the ND State Machine. + """ + self.module = module + self.nd_module = NDModule(self.module) + + # Operation tracking + self.output = NDOutput(output_level=module.params.get("output_level", "normal")) + + # Configuration + self.model_orchestrator = model_orchestrator(sender=self.nd_module) + self.model_class = self.model_orchestrator.model_class + self.state = self.module.params["state"] + + # Initialize collections + try: + response_data = self.model_orchestrator.query_all() + # State of configuration objects in ND before change execution + self.before = NDConfigCollection.from_api_response(response_data=response_data, model_class=self.model_class) + # State of current configuration objects in ND during change execution + self.existing = self.before.copy() + # Ongoing collection of configuration objects that were changed + self.sent = NDConfigCollection(model_class=self.model_class) + # Collection of configuration objects given by user + self.proposed = NDConfigCollection.from_ansible_config(data=self.module.params.get("config", []), model_class=self.model_class) + + self.output.assign(after=self.existing, before=self.before, proposed=self.proposed) + + except Exception as e: + raise NDStateMachineError(f"Initialization failed: {str(e)}") from e + + # State Management (core function) + def manage_state(self) -> None: + """ + Manage state according to desired configuration. + """ + # Execute state operations + if self.state in ["merged", "replaced", "overridden"]: + self._manage_create_update_state() + + if self.state == "overridden": + self._manage_override_deletions() + + elif self.state == "deleted": + self._manage_delete_state() + + else: + raise NDStateMachineError(f"Invalid state: {self.state}") + + def _manage_create_update_state(self) -> None: + """ + Handle merged/replaced/overridden states. + """ + for proposed_item in self.proposed: + # Extract identifier + identifier = proposed_item.get_identifier_value() + try: + # Determine diff status + diff_status = self.existing.get_diff_config(proposed_item) + + # No changes needed + if diff_status == "no_diff": + continue + + # Prepare final config based on state + if self.state == "merged": + # Merge with existing + final_item = self.existing.merge(proposed_item) + else: + # Replace or create + if diff_status == "changed": + self.existing.replace(proposed_item) + else: + self.existing.add(proposed_item) + final_item = proposed_item + + # Execute API operation + if diff_status == "changed": + if not self.module.check_mode: + self.model_orchestrator.update(final_item) + elif diff_status == "new": + if not self.module.check_mode: + self.model_orchestrator.create(final_item) + self.sent.add(final_item) + + # Log operation + self.output.assign(after=self.existing) + + except Exception as e: + error_msg = f"Failed to process {identifier}: {e}" + if not self.module.params.get("ignore_errors", False): + raise NDStateMachineError(error_msg) from e + + def _manage_override_deletions(self) -> None: + """ + Delete items not in proposed config (for overridden state). + """ + diff_identifiers = self.before.get_diff_identifiers(self.proposed) + + for identifier in diff_identifiers: + try: + existing_item = self.existing.get(identifier) + if not existing_item: + continue + + # Execute delete + if not self.module.check_mode: + self.model_orchestrator.delete(existing_item) + + # Remove from collection + self.existing.delete(identifier) + + # Log deletion + self.output.assign(after=self.existing) + + except Exception as e: + error_msg = f"Failed to delete {identifier}: {e}" + if not self.module.params.get("ignore_errors", False): + raise NDStateMachineError(error_msg) from e + + def _manage_delete_state(self) -> None: + """Handle deleted state.""" + for proposed_item in self.proposed: + try: + identifier = proposed_item.get_identifier_value() + + existing_item = self.existing.get(identifier) + if not existing_item: + continue + + # Execute delete + if not self.module.check_mode: + self.model_orchestrator.delete(existing_item) + + # Remove from collection + self.existing.delete(identifier) + + # Log deletion + self.output.assign(after=self.existing) + + except Exception as e: + error_msg = f"Failed to delete {identifier}: {e}" + if not self.module.params.get("ignore_errors", False): + raise NDStateMachineError(error_msg) from e diff --git a/plugins/module_utils/nd_v2.py b/plugins/module_utils/nd_v2.py index 0a3fe61a..a622d77f 100644 --- a/plugins/module_utils/nd_v2.py +++ b/plugins/module_utils/nd_v2.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2026, Allen Robel (@arobel) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) @@ -47,10 +45,6 @@ def main(): # fmt: on # isort: on -# pylint: disable=invalid-name -__metaclass__ = type -# pylint: enable=invalid-name - import logging from typing import Any, Optional diff --git a/plugins/module_utils/ndi.py b/plugins/module_utils/ndi.py index 37e7ec56..6ff912aa 100644 --- a/plugins/module_utils/ndi.py +++ b/plugins/module_utils/ndi.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2021, Lionel Hercot (@lhercot) # Copyright: (c) 2022, Cindy Zhao (@cizhao) # Copyright: (c) 2022, Akini Ross (@akinross) @@ -16,7 +14,6 @@ HAS_JSONPATH_NG_PARSE = True except ImportError: HAS_JSONPATH_NG_PARSE = False -__metaclass__ = type from ansible_collections.cisco.nd.plugins.module_utils.constants import OBJECT_TYPES, MATCH_TYPES diff --git a/plugins/module_utils/ndi_argument_specs.py b/plugins/module_utils/ndi_argument_specs.py index 641e675c..a367e3c5 100644 --- a/plugins/module_utils/ndi_argument_specs.py +++ b/plugins/module_utils/ndi_argument_specs.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2022, Akini Ross (@akinross) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function -__metaclass__ = type - from ansible_collections.cisco.nd.plugins.module_utils.constants import MATCH_TYPES, OPERATORS, TCP_FLAGS diff --git a/plugins/module_utils/orchestrators/base.py b/plugins/module_utils/orchestrators/base.py new file mode 100644 index 00000000..42944e26 --- /dev/null +++ b/plugins/module_utils/orchestrators/base.py @@ -0,0 +1,75 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +from ansible_collections.cisco.nd.plugins.module_utils.common.pydantic_compat import BaseModel, ConfigDict +from typing import ClassVar, Type, Optional, Generic, TypeVar +from ansible_collections.cisco.nd.plugins.module_utils.models.base import NDBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.nd import NDModule +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.base import NDEndpointBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.orchestrators.types import ResponseType + +ModelType = TypeVar("ModelType", bound=NDBaseModel) + + +class NDBaseOrchestrator(BaseModel, Generic[ModelType]): + model_config = ConfigDict( + use_enum_values=True, + validate_assignment=True, + populate_by_name=True, + arbitrary_types_allowed=True, + ) + + model_class: ClassVar[Type[NDBaseModel]] = NDBaseModel + + # NOTE: if not defined by subclasses, return an error as they are required + create_endpoint: Type[NDEndpointBaseModel] + update_endpoint: Type[NDEndpointBaseModel] + delete_endpoint: Type[NDEndpointBaseModel] + query_one_endpoint: Type[NDEndpointBaseModel] + query_all_endpoint: Type[NDEndpointBaseModel] + + # NOTE: Module Field is always required + sender: NDModule + + # NOTE: Generic CRUD API operations for simple endpoints with single identifier (e.g. "api/v1/infra/aaa/LocalUsers/{loginID}") + def create(self, model_instance: ModelType, **kwargs) -> ResponseType: + try: + api_endpoint = self.create_endpoint() + return self.sender.request(path=api_endpoint.path, method=api_endpoint.verb, data=model_instance.to_payload()) + except Exception as e: + raise Exception(f"Create failed for {model_instance.get_identifier_value()}: {e}") from e + + def update(self, model_instance: ModelType, **kwargs) -> ResponseType: + try: + api_endpoint = self.update_endpoint() + api_endpoint.set_identifiers(model_instance.get_identifier_value()) + return self.sender.request(path=api_endpoint.path, method=api_endpoint.verb, data=model_instance.to_payload()) + except Exception as e: + raise Exception(f"Update failed for {model_instance.get_identifier_value()}: {e}") from e + + def delete(self, model_instance: ModelType, **kwargs) -> ResponseType: + try: + api_endpoint = self.delete_endpoint() + api_endpoint.set_identifiers(model_instance.get_identifier_value()) + return self.sender.request(path=api_endpoint.path, method=api_endpoint.verb) + except Exception as e: + raise Exception(f"Delete failed for {model_instance.get_identifier_value()}: {e}") from e + + def query_one(self, model_instance: ModelType, **kwargs) -> ResponseType: + try: + api_endpoint = self.query_one_endpoint() + api_endpoint.set_identifiers(model_instance.get_identifier_value()) + return self.sender.request(path=api_endpoint.path, method=api_endpoint.verb) + except Exception as e: + raise Exception(f"Query failed for {model_instance.get_identifier_value()}: {e}") from e + + def query_all(self, model_instance: Optional[ModelType] = None, **kwargs) -> ResponseType: + try: + api_endpoint = self.query_all_endpoint() + result = self.sender.query_obj(api_endpoint.path) + return result or [] + except Exception as e: + raise Exception(f"Query all failed: {e}") from e \ No newline at end of file diff --git a/plugins/module_utils/orchestrators/local_user.py b/plugins/module_utils/orchestrators/local_user.py new file mode 100644 index 00000000..425a8b9b --- /dev/null +++ b/plugins/module_utils/orchestrators/local_user.py @@ -0,0 +1,39 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +from typing import Type, ClassVar +from ansible_collections.cisco.nd.plugins.module_utils.orchestrators.base import NDBaseOrchestrator +from ansible_collections.cisco.nd.plugins.module_utils.models.base import NDBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.models.local_user.local_user import LocalUserModel +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.base import NDEndpointBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.orchestrators.types import ResponseType +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.v1.infra.aaa_local_users import ( + EpInfraAaaLocalUsersPost, + EpInfraAaaLocalUsersPut, + EpInfraAaaLocalUsersDelete, + EpInfraAaaLocalUsersGet, +) + + +class LocalUserOrchestrator(NDBaseOrchestrator[LocalUserModel]): + model_class: ClassVar[Type[NDBaseModel]] = LocalUserModel + + create_endpoint: Type[NDEndpointBaseModel] = EpInfraAaaLocalUsersPost + update_endpoint: Type[NDEndpointBaseModel] = EpInfraAaaLocalUsersPut + delete_endpoint: Type[NDEndpointBaseModel] = EpInfraAaaLocalUsersDelete + query_one_endpoint: Type[NDEndpointBaseModel] = EpInfraAaaLocalUsersGet + query_all_endpoint: Type[NDEndpointBaseModel] = EpInfraAaaLocalUsersGet + + def query_all(self) -> ResponseType: + """ + Custom query_all action to extract 'localusers' from response. + """ + try: + api_endpoint = self.query_all_endpoint() + result = self.sender.query_obj(api_endpoint.path) + return result.get("localusers", []) or [] + except Exception as e: + raise Exception(f"Query all failed: {e}") from e \ No newline at end of file diff --git a/plugins/module_utils/orchestrators/manage_fabric_ebgp.py b/plugins/module_utils/orchestrators/manage_fabric_ebgp.py new file mode 100644 index 00000000..45df1acd --- /dev/null +++ b/plugins/module_utils/orchestrators/manage_fabric_ebgp.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- + +# Copyright: (c) 2026, Mike Wiebe (@mwiebe) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +from typing import Type +from ansible_collections.cisco.nd.plugins.module_utils.orchestrators.base import NDBaseOrchestrator +from ansible_collections.cisco.nd.plugins.module_utils.models.base import NDBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.models.manage_fabric.manage_fabric_ibgp import FabricIbgpModel +from ansible_collections.cisco.nd.plugins.module_utils.models.manage_fabric.manage_fabric_ebgp import FabricEbgpModel +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.base import NDEndpointBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.orchestrators.types import ResponseType +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.v1.manage.manage_fabrics import ( + EpManageFabricsGet, + EpManageFabricsListGet, + EpManageFabricsPost, + EpManageFabricsPut, + EpManageFabricsDelete, +) + +class ManageEbgpFabricOrchestrator(NDBaseOrchestrator): + model_class: Type[NDBaseModel] = FabricEbgpModel + + create_endpoint: Type[NDEndpointBaseModel] = EpManageFabricsPost + update_endpoint: Type[NDEndpointBaseModel] = EpManageFabricsPut + delete_endpoint: Type[NDEndpointBaseModel] = EpManageFabricsDelete + query_one_endpoint: Type[NDEndpointBaseModel] = EpManageFabricsGet + query_all_endpoint: Type[NDEndpointBaseModel] = EpManageFabricsListGet + + def query_all(self) -> ResponseType: + """ + Custom query_all action to extract 'fabrics' from response, + filtered to only vxlanEbgp fabric types. + """ + try: + api_endpoint = self.query_all_endpoint() + result = self.sender.query_obj(api_endpoint.path) + fabrics = result.get("fabrics", []) or [] + return [f for f in fabrics if f.get("management", {}).get("type") == "vxlanEbgp"] + except Exception as e: + raise Exception(f"Query all failed: {e}") from e diff --git a/plugins/module_utils/orchestrators/manage_fabric_ibgp.py b/plugins/module_utils/orchestrators/manage_fabric_ibgp.py new file mode 100644 index 00000000..e2082b57 --- /dev/null +++ b/plugins/module_utils/orchestrators/manage_fabric_ibgp.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- + +# Copyright: (c) 2026, Mike Wiebe (@mwiebe) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +from typing import Type +from ansible_collections.cisco.nd.plugins.module_utils.orchestrators.base import NDBaseOrchestrator +from ansible_collections.cisco.nd.plugins.module_utils.models.base import NDBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.models.manage_fabric.manage_fabric_ibgp import FabricIbgpModel +from ansible_collections.cisco.nd.plugins.module_utils.models.manage_fabric.manage_fabric_ebgp import FabricEbgpModel +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.base import NDEndpointBaseModel +from ansible_collections.cisco.nd.plugins.module_utils.orchestrators.types import ResponseType +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.v1.manage.manage_fabrics import ( + EpManageFabricsGet, + EpManageFabricsListGet, + EpManageFabricsPost, + EpManageFabricsPut, + EpManageFabricsDelete, +) + + +class ManageIbgpFabricOrchestrator(NDBaseOrchestrator): + model_class: Type[NDBaseModel] = FabricIbgpModel + + create_endpoint: Type[NDEndpointBaseModel] = EpManageFabricsPost + update_endpoint: Type[NDEndpointBaseModel] = EpManageFabricsPut + delete_endpoint: Type[NDEndpointBaseModel] = EpManageFabricsDelete + query_one_endpoint: Type[NDEndpointBaseModel] = EpManageFabricsGet + query_all_endpoint: Type[NDEndpointBaseModel] = EpManageFabricsListGet + + def query_all(self) -> ResponseType: + """ + Custom query_all action to extract 'fabrics' from response, + filtered to only vxlanIbgp fabric types. + """ + try: + api_endpoint = self.query_all_endpoint() + result = self.sender.query_obj(api_endpoint.path) + fabrics = result.get("fabrics", []) or [] + return [f for f in fabrics if f.get("management", {}).get("type") == "vxlanIbgp"] + except Exception as e: + raise Exception(f"Query all failed: {e}") from e diff --git a/plugins/module_utils/orchestrators/types.py b/plugins/module_utils/orchestrators/types.py new file mode 100644 index 00000000..415526c7 --- /dev/null +++ b/plugins/module_utils/orchestrators/types.py @@ -0,0 +1,9 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +from typing import Any, Union, List, Dict + +ResponseType = Union[List[Dict[str, Any]], Dict[str, Any], None] diff --git a/plugins/module_utils/rest/protocols/response_handler.py b/plugins/module_utils/rest/protocols/response_handler.py index 487e12cf..ab658c99 100644 --- a/plugins/module_utils/rest/protocols/response_handler.py +++ b/plugins/module_utils/rest/protocols/response_handler.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # pylint: disable=missing-module-docstring # pylint: disable=unnecessary-ellipsis # pylint: disable=wrong-import-position @@ -13,7 +12,7 @@ # isort: on # pylint: disable=invalid-name -__metaclass__ = type + # pylint: enable=invalid-name """ diff --git a/plugins/module_utils/rest/protocols/response_validation.py b/plugins/module_utils/rest/protocols/response_validation.py index d1ec5ef0..30a81b97 100644 --- a/plugins/module_utils/rest/protocols/response_validation.py +++ b/plugins/module_utils/rest/protocols/response_validation.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2026, Allen Robel (@arobel) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) @@ -26,7 +24,7 @@ # isort: on # pylint: disable=invalid-name -__metaclass__ = type + # pylint: enable=invalid-name try: diff --git a/plugins/module_utils/rest/protocols/sender.py b/plugins/module_utils/rest/protocols/sender.py index 5e55047c..df9f4d1b 100644 --- a/plugins/module_utils/rest/protocols/sender.py +++ b/plugins/module_utils/rest/protocols/sender.py @@ -1,7 +1,7 @@ # pylint: disable=wrong-import-position # pylint: disable=missing-module-docstring # pylint: disable=unnecessary-ellipsis -# -*- coding: utf-8 -*- + # Copyright: (c) 2026, Allen Robel (@arobel) @@ -15,7 +15,7 @@ # isort: on # pylint: disable=invalid-name -__metaclass__ = type + # pylint: enable=invalid-name try: diff --git a/plugins/module_utils/rest/response_handler_nd.py b/plugins/module_utils/rest/response_handler_nd.py index e7026d30..f0f30b94 100644 --- a/plugins/module_utils/rest/response_handler_nd.py +++ b/plugins/module_utils/rest/response_handler_nd.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2026, Allen Robel (@arobel) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) @@ -62,7 +60,7 @@ class (e.g. `NdV2Strategy`) conforming to `ResponseValidationStrategy` and injec # isort: on # pylint: disable=invalid-name -__metaclass__ = type + # pylint: enable=invalid-name import copy diff --git a/plugins/module_utils/rest/response_strategies/nd_v1_strategy.py b/plugins/module_utils/rest/response_strategies/nd_v1_strategy.py index 58c7784f..a5953789 100644 --- a/plugins/module_utils/rest/response_strategies/nd_v1_strategy.py +++ b/plugins/module_utils/rest/response_strategies/nd_v1_strategy.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2026, Allen Robel (@arobel) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) @@ -25,7 +23,7 @@ # isort: on # pylint: disable=invalid-name -__metaclass__ = type + # pylint: enable=invalid-name from typing import Any, Optional diff --git a/plugins/module_utils/rest/rest_send.py b/plugins/module_utils/rest/rest_send.py index c87009a5..7631b0dd 100644 --- a/plugins/module_utils/rest/rest_send.py +++ b/plugins/module_utils/rest/rest_send.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # pylint: disable=wrong-import-position # pylint: disable=missing-module-docstring # Copyright: (c) 2026, Allen Robel (@arobel) diff --git a/plugins/module_utils/rest/results.py b/plugins/module_utils/rest/results.py index 59281683..faee00dc 100644 --- a/plugins/module_utils/rest/results.py +++ b/plugins/module_utils/rest/results.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2026, Allen Robel (@arobel) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) diff --git a/plugins/module_utils/rest/sender_nd.py b/plugins/module_utils/rest/sender_nd.py index ae333dd0..b5ed9b85 100644 --- a/plugins/module_utils/rest/sender_nd.py +++ b/plugins/module_utils/rest/sender_nd.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # Copyright: (c) 2026, Allen Robel (@arobel) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) @@ -17,7 +15,7 @@ # isort: on # pylint: disable=invalid-name -__metaclass__ = type + # pylint: enable=invalid-name import copy diff --git a/plugins/module_utils/types.py b/plugins/module_utils/types.py new file mode 100644 index 00000000..b0056d5a --- /dev/null +++ b/plugins/module_utils/types.py @@ -0,0 +1,9 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +from typing import Any, Union, Tuple + +IdentifierKey = Union[str, int, Tuple[Any, ...]] diff --git a/plugins/module_utils/utils.py b/plugins/module_utils/utils.py new file mode 100644 index 00000000..7d05e4af --- /dev/null +++ b/plugins/module_utils/utils.py @@ -0,0 +1,78 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +from copy import deepcopy +from typing import Any, Dict, List, Union + + +def sanitize_dict(dict_to_sanitize, keys=None, values=None, recursive=True, remove_none_values=True): + if keys is None: + keys = [] + if values is None: + values = [] + + result = deepcopy(dict_to_sanitize) + for k, v in dict_to_sanitize.items(): + if k in keys: + del result[k] + elif v in values or (v is None and remove_none_values): + del result[k] + elif isinstance(v, dict) and recursive: + result[k] = sanitize_dict(v, keys, values) + elif isinstance(v, list) and recursive: + for index, item in enumerate(v): + if isinstance(item, dict): + result[k][index] = sanitize_dict(item, keys, values) + return result + + +def issubset(subset: Any, superset: Any) -> bool: + """Check if subset is contained in superset.""" + if type(subset) is not type(superset): + return False + + if not isinstance(subset, dict): + if isinstance(subset, list): + return all(item in superset for item in subset) + return subset == superset + + for key, value in subset.items(): + if value is None: + continue + + if key not in superset: + return False + + if not issubset(value, superset[key]): + return False + + return True + + +def remove_unwanted_keys(data: Dict, unwanted_keys: List[Union[str, List[str]]]) -> Dict: + """Remove unwanted keys from dict (supports nested paths).""" + data = deepcopy(data) + + for key in unwanted_keys: + if isinstance(key, str): + if key in data: + del data[key] + + elif isinstance(key, list) and len(key) > 0: + try: + parent = data + for k in key[:-1]: + if isinstance(parent, dict) and k in parent: + parent = parent[k] + else: + break + else: + if isinstance(parent, dict) and key[-1] in parent: + del parent[key[-1]] + except (KeyError, TypeError, IndexError): + pass + + return data diff --git a/plugins/modules/nd_api_key.py b/plugins/modules/nd_api_key.py index c00428a9..1a3e4823 100644 --- a/plugins/modules/nd_api_key.py +++ b/plugins/modules/nd_api_key.py @@ -146,7 +146,6 @@ def main(): nd.existing = nd.previous = nd.query_objs(path, key="apiKeys") if state == "present": - if len(api_key_name) > 32 or len(api_key_name) < 1: nd.fail_json("A length of 1 to 32 characters is allowed.") elif re.search(r"[^a-zA-Z0-9_.-]", api_key_name): diff --git a/plugins/modules/nd_local_user.py b/plugins/modules/nd_local_user.py new file mode 100644 index 00000000..24eb49c4 --- /dev/null +++ b/plugins/modules/nd_local_user.py @@ -0,0 +1,212 @@ +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "community"} + +DOCUMENTATION = r""" +--- +module: nd_local_user +version_added: "1.6.0" +short_description: Manage local users on Cisco Nexus Dashboard +description: +- Manage local users on Cisco Nexus Dashboard (ND). +- It supports creating, updating, and deleting local users. +author: +- Gaspard Micol (@gmicol) +options: + config: + description: + - The list of the local users to configure. + type: list + elements: dict + required: True + suboptions: + email: + description: + - The email address of the local user. + type: str + login_id: + description: + - The login ID of the local user. + - The O(config.login_id) must be defined when creating, updating or deleting a local user. + type: str + required: true + first_name: + description: + - The first name of the local user. + type: str + last_name: + description: + - The last name of the local user. + type: str + user_password: + description: + - The password of the local user. + - Password must have a minimum of 8 characters to a maximum of 64 characters. + - Password must have three of the following; one number, one lower case character, one upper case character, one special character. + - The O(config.user_password) must be defined when creating a new local_user. + type: str + reuse_limitation: + description: + - The number of different passwords a user must use before they can reuse a previous one. + - It defaults to C(0) when unset during creation. + type: int + time_interval_limitation: + description: + - The minimum time period that must pass before a previous password can be reused. + - It defaults to C(0) when unset during creation. + type: int + security_domains: + description: + - The list of Security Domains and Roles for the local user. + - At least, one Security Domain must be defined when creating a new local user. + type: list + elements: dict + suboptions: + name: + description: + - The name of the Security Domain to which the local user is given access. + type: str + required: true + aliases: [ security_domain_name, domain_name ] + roles: + description: + - The Permission Roles of the local user within the Security Domain. + type: list + elements: str + choices: [ fabric_admin, observer, super_admin, support_engineer, approver, designer ] + aliases: [ domains ] + remote_id_claim: + description: + - The remote ID claim of the local user. + type: str + remote_user_authorization: + description: + - To enable/disable the Remote User Authorization of the local user. + - Remote User Authorization is used for signing into Nexus Dashboard when using identity providers that cannot provide authorization claims. + Once this attribute is enabled, the local user ID cannot be used to directly login to Nexus Dashboard. + - It defaults to C(false) when unset during creation. + type: bool + state: + description: + - The desired state of the network resources on the Cisco Nexus Dashboard. + - Use O(state=merged) to create new resources and updates existing ones as defined in your configuration. + Resources on ND that are not specified in the configuration will be left unchanged. + - Use O(state=replaced) to replace the resources specified in the configuration. + - Use O(state=overridden) to enforce the configuration as the single source of truth. + The resources on ND will be modified to exactly match the configuration. + Any resource existing on ND but not present in the configuration will be deleted. Use with extra caution. + - Use O(state=deleted) to remove the resources specified in the configuration from the Cisco Nexus Dashboard. + type: str + default: merged + choices: [ merged, replaced, overridden, deleted ] +extends_documentation_fragment: +- cisco.nd.modules +- cisco.nd.check_mode +notes: +- This module is only supported on Nexus Dashboard having version 4.2.1 or higher. +- This module is not idempotent when creating or updating a local user object when O(config.user_password) is used. +- When using O(state=overridden), admin user configuration must be specified as it cannot be deleted. +""" + +EXAMPLES = r""" +- name: Create a new local user + cisco.nd.nd_local_user: + config: + - email: user@example.com + login_id: local_user + first_name: User first name + last_name: User last name + user_password: localUserPassword1% + reuse_limitation: 20 + time_interval_limitation: 10 + security_domains: + - name: all + roles: + - observer + - support_engineer + remote_id_claim: remote_user + remote_user_authorization: true + state: merged + register: result + +- name: Create local user with minimal configuration + cisco.nd.nd_local_user: + config: + - login_id: local_user_min + user_password: localUserMinuser_password + security_domains: + - name: all + state: merged + +- name: Update local user + cisco.nd.nd_local_user: + config: + - email: updateduser@example.com + login_id: local_user + first_name: Updated user first name + last_name: Updated user last name + user_password: updatedLocalUserPassword1% + reuse_limitation: 25 + time_interval_limitation: 15 + security_domains: + - name: all + roles: super_admin + - name: ansible_domain + roles: observer + remote_id_claim: "" + remote_user_authorization: false + state: replaced + +- name: Delete a local user + cisco.nd.nd_local_user: + config: + - login_id: local_user + state: deleted +""" + +RETURN = r""" +""" + +from ansible.module_utils.basic import AnsibleModule +from ansible_collections.cisco.nd.plugins.module_utils.nd import nd_argument_spec +from ansible_collections.cisco.nd.plugins.module_utils.nd_state_machine import NDStateMachine +from ansible_collections.cisco.nd.plugins.module_utils.common.pydantic_compat import require_pydantic +from ansible_collections.cisco.nd.plugins.module_utils.models.local_user.local_user import LocalUserModel +from ansible_collections.cisco.nd.plugins.module_utils.orchestrators.local_user import LocalUserOrchestrator + + +def main(): + argument_spec = nd_argument_spec() + argument_spec.update(LocalUserModel.get_argument_spec()) + + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + require_pydantic(module) + + try: + # Initialize StateMachine + nd_state_machine = NDStateMachine( + module=module, + model_orchestrator=LocalUserOrchestrator, + ) + + # Manage state + # TODO: return module output class object: + # output = nd_state_machine.manage_state() + # module.exit_json(**output) + nd_state_machine.manage_state() + + module.exit_json(**nd_state_machine.output.format()) + + except Exception as e: + module.fail_json(msg=f"Module execution failed: {str(e)}", **nd_state_machine.output.format()) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/nd_manage_fabric_ebgp.py b/plugins/modules/nd_manage_fabric_ebgp.py new file mode 100644 index 00000000..04a4ab72 --- /dev/null +++ b/plugins/modules/nd_manage_fabric_ebgp.py @@ -0,0 +1,1179 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2026, Mike Wiebe (@mwiebe) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "community"} + +DOCUMENTATION = r""" +--- +module: nd_manage_fabric_ebgp +version_added: "1.4.0" +short_description: Manage eBGP VXLAN fabrics on Cisco Nexus Dashboard +description: +- Manage eBGP VXLAN fabrics on Cisco Nexus Dashboard (ND). +- It supports creating, updating, replacing, and deleting eBGP VXLAN fabrics. +author: +- Mike Wiebe (@mwiebe) +options: + config: + description: + - The list of eBGP VXLAN fabrics to configure. + type: list + elements: dict + suboptions: + name: + description: + - The name of the fabric. + - Only letters, numbers, underscores, and hyphens are allowed. + - The O(config.name) must be defined when creating, updating or deleting a fabric. + type: str + required: true + category: + description: + - The resource category. + type: str + default: fabric + location: + description: + - The geographic location of the fabric. + type: dict + suboptions: + latitude: + description: + - Latitude coordinate of the fabric location (-90 to 90). + type: float + required: true + longitude: + description: + - Longitude coordinate of the fabric location (-180 to 180). + type: float + required: true + license_tier: + description: + - The license tier for the fabric. + type: str + default: premier + choices: [ essentials, premier ] + alert_suspend: + description: + - The alert suspension state for the fabric. + type: str + default: disabled + choices: [ enabled, disabled ] + telemetry_collection: + description: + - Enable telemetry collection for the fabric. + type: bool + default: false + telemetry_collection_type: + description: + - The telemetry collection type. + type: str + default: outOfBand + telemetry_streaming_protocol: + description: + - The telemetry streaming protocol. + type: str + default: ipv4 + telemetry_source_interface: + description: + - The telemetry source interface. + type: str + default: "" + telemetry_source_vrf: + description: + - The telemetry source VRF. + type: str + default: "" + security_domain: + description: + - The security domain associated with the fabric. + type: str + default: all + management: + description: + - The eBGP VXLAN management configuration for the fabric. + type: dict + suboptions: + type: + description: + - The fabric management type. Must be C(vxlanEbgp) for eBGP VXLAN fabrics. + type: str + default: vxlanEbgp + choices: [ vxlanEbgp ] + bgp_asn: + description: + - The BGP Autonomous System Number for the fabric. + - Must be a numeric value between 1 and 4294967295, or dotted notation (1-65535.0-65535). + - Optional when O(config.management.bgp_asn_auto_allocation) is C(true). + type: str + bgp_asn_auto_allocation: + description: + - Enable automatic BGP ASN allocation from the O(config.management.bgp_asn_range) pool. + type: bool + default: true + bgp_asn_range: + description: + - The BGP ASN range to use for automatic ASN allocation (e.g. C(65000-65535)). + - Required when O(config.management.bgp_asn_auto_allocation) is C(true). + type: str + bgp_as_mode: + description: + - The BGP AS mode for the fabric. + - C(multiAS) assigns a unique AS number to each leaf tier. + - C(sameTierAS) assigns the same AS number within a tier. + type: str + default: multiAS + choices: [ multiAS, sameTierAS ] + bgp_allow_as_in_num: + description: + - The number of times BGP allows an AS-path containing the local AS number. + type: int + default: 1 + bgp_max_path: + description: + - The maximum number of BGP equal-cost paths. + type: int + default: 4 + bgp_underlay_failure_protect: + description: + - Enable BGP underlay failure protection. + type: bool + default: false + auto_configure_ebgp_evpn_peering: + description: + - Automatically configure eBGP EVPN peering between spine and leaf switches. + type: bool + default: true + allow_leaf_same_as: + description: + - Allow leaf switches to share the same BGP AS number. + type: bool + default: false + assign_ipv4_to_loopback0: + description: + - Assign an IPv4 address to the loopback0 interface. + type: bool + default: true + evpn: + description: + - Enable the EVPN control plane. + type: bool + default: true + route_map_tag: + description: + - The route map tag used for redistribution. + type: int + default: 12345 + disable_route_map_tag: + description: + - Disable route map tag usage. + type: bool + default: false + leaf_bgp_as: + description: + - The BGP AS number for leaf switches (used with C(sameTierAS) mode). + type: str + border_bgp_as: + description: + - The BGP AS number for border switches. + type: str + super_spine_bgp_as: + description: + - The BGP AS number for super-spine switches. + type: str + site_id: + description: + - The site identifier for the fabric. + - Defaults to the value of O(config.management.bgp_asn) if not provided. + type: str + default: "" + target_subnet_mask: + description: + - The target subnet mask for intra-fabric links (24-31). + type: int + default: 30 + anycast_gateway_mac: + description: + - The anycast gateway MAC address in xxxx.xxxx.xxxx format. + type: str + default: 2020.0000.00aa + replication_mode: + description: + - The multicast replication mode. + type: str + default: multicast + choices: [ multicast, ingress ] + multicast_group_subnet: + description: + - The multicast group subnet. + type: str + default: "239.1.1.0/25" + auto_generate_multicast_group_address: + description: + - Automatically generate multicast group addresses. + type: bool + default: false + underlay_multicast_group_address_limit: + description: + - The underlay multicast group address limit (1-255). + type: int + default: 128 + tenant_routed_multicast: + description: + - Enable tenant routed multicast. + type: bool + default: false + tenant_routed_multicast_ipv6: + description: + - Enable tenant routed multicast for IPv6. + type: bool + default: false + first_hop_redundancy_protocol: + description: + - The first-hop redundancy protocol for tenant networks. + type: str + default: hsrp + choices: [ hsrp, vrrp ] + rendezvous_point_count: + description: + - The number of rendezvous points (1-4). + type: int + default: 2 + rendezvous_point_loopback_id: + description: + - The rendezvous point loopback interface ID (0-1023). + type: int + default: 254 + overlay_mode: + description: + - The overlay configuration mode. + type: str + default: cli + choices: [ cli, config-profile ] + bgp_loopback_id: + description: + - The BGP loopback interface ID (0-1023). + type: int + default: 0 + nve_loopback_id: + description: + - The NVE loopback interface ID (0-1023). + type: int + default: 1 + anycast_loopback_id: + description: + - The anycast loopback interface ID. + type: int + default: 10 + bgp_loopback_ip_range: + description: + - The BGP loopback IP address pool. + type: str + default: "10.2.0.0/22" + bgp_loopback_ipv6_range: + description: + - The BGP loopback IPv6 address pool. + type: str + default: "fd00::a02:0/119" + nve_loopback_ip_range: + description: + - The NVE loopback IP address pool. + type: str + default: "10.3.0.0/22" + nve_loopback_ipv6_range: + description: + - The NVE loopback IPv6 address pool. + type: str + default: "fd00::a03:0/118" + anycast_rendezvous_point_ip_range: + description: + - The anycast rendezvous point IP address pool. + type: str + default: "10.254.254.0/24" + ipv6_anycast_rendezvous_point_ip_range: + description: + - The IPv6 anycast rendezvous point IP address pool. + type: str + default: "fd00::254:254:0/118" + intra_fabric_subnet_range: + description: + - The intra-fabric subnet IP address pool. + type: str + default: "10.4.0.0/16" + l2_vni_range: + description: + - The Layer 2 VNI range. + type: str + default: "30000-49000" + l3_vni_range: + description: + - The Layer 3 VNI range. + type: str + default: "50000-59000" + network_vlan_range: + description: + - The network VLAN range. + type: str + default: "2300-2999" + vrf_vlan_range: + description: + - The VRF VLAN range. + type: str + default: "2000-2299" + sub_interface_dot1q_range: + description: + - The sub-interface 802.1q range. + type: str + default: "2-511" + l3_vni_no_vlan_default_option: + description: + - Enable L3 VNI no-VLAN default option. + type: bool + default: false + fabric_mtu: + description: + - The fabric MTU size (1500-9216). + type: int + default: 9216 + l2_host_interface_mtu: + description: + - The L2 host interface MTU size (1500-9216). + type: int + default: 9216 + underlay_ipv6: + description: + - Enable IPv6 underlay. + type: bool + default: false + static_underlay_ip_allocation: + description: + - Disable dynamic underlay IP address allocation. + type: bool + default: false + vpc_domain_id_range: + description: + - The vPC domain ID range. + type: str + default: "1-1000" + vpc_peer_link_vlan: + description: + - The vPC peer link VLAN ID. + type: str + default: "3600" + vpc_peer_link_enable_native_vlan: + description: + - Enable native VLAN on the vPC peer link. + type: bool + default: false + vpc_peer_keep_alive_option: + description: + - The vPC peer keep-alive option. + type: str + default: management + choices: [ loopback, management ] + vpc_auto_recovery_timer: + description: + - The vPC auto recovery timer in seconds (240-3600). + type: int + default: 360 + vpc_delay_restore_timer: + description: + - The vPC delay restore timer in seconds (1-3600). + type: int + default: 150 + vpc_peer_link_port_channel_id: + description: + - The vPC peer link port-channel ID. + type: str + default: "500" + vpc_ipv6_neighbor_discovery_sync: + description: + - Enable vPC IPv6 neighbor discovery synchronization. + type: bool + default: true + vpc_layer3_peer_router: + description: + - Enable vPC layer-3 peer router. + type: bool + default: true + vpc_tor_delay_restore_timer: + description: + - The vPC TOR delay restore timer. + type: int + default: 30 + fabric_vpc_domain_id: + description: + - Enable fabric vPC domain ID. + type: bool + default: false + shared_vpc_domain_id: + description: + - The shared vPC domain ID. + type: int + default: 1 + fabric_vpc_qos: + description: + - Enable fabric vPC QoS. + type: bool + default: false + fabric_vpc_qos_policy_name: + description: + - The fabric vPC QoS policy name. + type: str + default: spine_qos_for_fabric_vpc_peering + enable_peer_switch: + description: + - Enable peer switch. + type: bool + default: false + per_vrf_loopback_auto_provision: + description: + - Enable per-VRF loopback auto-provisioning. + type: bool + default: false + per_vrf_loopback_ip_range: + description: + - The per-VRF loopback IP address pool. + type: str + default: "10.5.0.0/22" + per_vrf_loopback_auto_provision_ipv6: + description: + - Enable per-VRF loopback auto-provisioning for IPv6. + type: bool + default: false + per_vrf_loopback_ipv6_range: + description: + - The per-VRF loopback IPv6 address pool. + type: str + default: "fd00::a05:0/112" + vrf_template: + description: + - The VRF template name. + type: str + default: Default_VRF_Universal + network_template: + description: + - The network template name. + type: str + default: Default_Network_Universal + vrf_extension_template: + description: + - The VRF extension template name. + type: str + default: Default_VRF_Extension_Universal + network_extension_template: + description: + - The network extension template name. + type: str + default: Default_Network_Extension_Universal + performance_monitoring: + description: + - Enable performance monitoring. + type: bool + default: false + tenant_dhcp: + description: + - Enable tenant DHCP. + type: bool + default: true + advertise_physical_ip: + description: + - Advertise physical IP address for NVE loopback. + type: bool + default: false + advertise_physical_ip_on_border: + description: + - Advertise physical IP address on border switches. + type: bool + default: true + anycast_border_gateway_advertise_physical_ip: + description: + - Enable anycast border gateway to advertise physical IP. + type: bool + default: false + snmp_trap: + description: + - Enable SNMP traps. + type: bool + default: true + cdp: + description: + - Enable CDP. + type: bool + default: false + tcam_allocation: + description: + - Enable TCAM allocation. + type: bool + default: true + real_time_interface_statistics_collection: + description: + - Enable real-time interface statistics collection. + type: bool + default: false + interface_statistics_load_interval: + description: + - The interface statistics load interval in seconds. + type: int + default: 10 + greenfield_debug_flag: + description: + - The greenfield debug flag. + type: str + default: disable + choices: [ enable, disable ] + nxapi: + description: + - Enable NX-API (HTTPS). + type: bool + default: false + nxapi_https_port: + description: + - The NX-API HTTPS port (1-65535). + type: int + default: 443 + nxapi_http: + description: + - Enable NX-API HTTP. + type: bool + default: false + nxapi_http_port: + description: + - The NX-API HTTP port (1-65535). + type: int + default: 80 + bgp_authentication: + description: + - Enable BGP authentication. + type: bool + default: false + bgp_authentication_key_type: + description: + - The BGP authentication key type. + type: str + default: 3des + bgp_authentication_key: + description: + - The BGP authentication key. + type: str + default: "" + bfd: + description: + - Enable BFD globally. + type: bool + default: false + bfd_ibgp: + description: + - Enable BFD for iBGP sessions. + type: bool + default: false + bfd_authentication: + description: + - Enable BFD authentication. + type: bool + default: false + bfd_authentication_key_id: + description: + - The BFD authentication key ID. + type: int + default: 100 + bfd_authentication_key: + description: + - The BFD authentication key. + type: str + default: "" + pim_hello_authentication: + description: + - Enable PIM hello authentication. + type: bool + default: false + pim_hello_authentication_key: + description: + - The PIM hello authentication key. + type: str + default: "" + macsec: + description: + - Enable MACsec on intra-fabric links. + type: bool + default: false + macsec_cipher_suite: + description: + - The MACsec cipher suite. + type: str + default: GCM-AES-XPN-256 + macsec_key_string: + description: + - The MACsec primary key string. + type: str + default: "" + macsec_algorithm: + description: + - The MACsec algorithm. + type: str + default: AES_128_CMAC + macsec_fallback_key_string: + description: + - The MACsec fallback key string. + type: str + default: "" + macsec_fallback_algorithm: + description: + - The MACsec fallback algorithm. + type: str + default: AES_128_CMAC + macsec_report_timer: + description: + - The MACsec report timer in minutes. + type: int + default: 5 + vrf_lite_auto_config: + description: + - The VRF lite auto-configuration mode. + type: str + default: manual + vrf_lite_subnet_range: + description: + - The VRF lite subnet IP address pool. + type: str + default: "10.33.0.0/16" + vrf_lite_subnet_target_mask: + description: + - The VRF lite subnet target mask. + type: int + default: 30 + auto_unique_vrf_lite_ip_prefix: + description: + - Enable auto unique VRF lite IP prefix. + type: bool + default: false + default_queuing_policy: + description: + - Enable default queuing policy. + type: bool + default: false + aiml_qos: + description: + - Enable AI/ML QoS. + type: bool + default: false + aiml_qos_policy: + description: + - The AI/ML QoS policy. + type: str + default: 400G + dlb: + description: + - Enable dynamic load balancing. + type: bool + default: false + dlb_mode: + description: + - The DLB mode. + type: str + default: flowlet + ptp: + description: + - Enable Precision Time Protocol (PTP). + type: bool + default: false + ptp_loopback_id: + description: + - The PTP loopback ID. + type: int + default: 0 + ptp_domain_id: + description: + - The PTP domain ID. + type: int + default: 0 + private_vlan: + description: + - Enable private VLAN support. + type: bool + default: false + day0_bootstrap: + description: + - Enable day-0 bootstrap (POAP). + type: bool + default: false + local_dhcp_server: + description: + - Enable local DHCP server for bootstrap. + type: bool + default: false + dhcp_protocol_version: + description: + - The DHCP protocol version for bootstrap. + type: str + default: dhcpv4 + dhcp_start_address: + description: + - The DHCP start address for bootstrap. + type: str + default: "" + dhcp_end_address: + description: + - The DHCP end address for bootstrap. + type: str + default: "" + management_gateway: + description: + - The management gateway for bootstrap. + type: str + default: "" + management_ipv4_prefix: + description: + - The management IPv4 prefix length for bootstrap. + type: int + default: 24 + management_ipv6_prefix: + description: + - The management IPv6 prefix length for bootstrap. + type: int + default: 64 + real_time_backup: + description: + - Enable real-time backup. + type: bool + scheduled_backup: + description: + - Enable scheduled backup. + type: bool + scheduled_backup_time: + description: + - The scheduled backup time. + type: str + default: "" + nve_hold_down_timer: + description: + - The NVE hold-down timer in seconds. + type: int + default: 180 + next_generation_oam: + description: + - Enable next-generation OAM. + type: bool + default: true + strict_config_compliance_mode: + description: + - Enable strict configuration compliance mode. + type: bool + default: false + copp_policy: + description: + - The CoPP policy. + type: str + default: strict + power_redundancy_mode: + description: + - The power redundancy mode. + type: str + default: redundant + heartbeat_interval: + description: + - The heartbeat interval. + type: int + default: 190 + allow_smart_switch_onboarding: + description: + - Allow smart switch onboarding. + type: bool + default: false + aaa: + description: + - Enable AAA. + type: bool + default: false + extra_config_leaf: + description: + - Extra freeform configuration applied to leaf switches. + type: str + default: "" + extra_config_spine: + description: + - Extra freeform configuration applied to spine switches. + type: str + default: "" + extra_config_tor: + description: + - Extra freeform configuration applied to TOR switches. + type: str + default: "" + extra_config_intra_fabric_links: + description: + - Extra freeform configuration applied to intra-fabric links. + type: str + default: "" + extra_config_aaa: + description: + - Extra freeform AAA configuration. + type: str + default: "" + banner: + description: + - The fabric banner text displayed on switch login. + type: str + default: "" + ntp_server_collection: + description: + - The list of NTP server IP addresses. + type: list + elements: str + dns_collection: + description: + - The list of DNS server IP addresses. + type: list + elements: str + syslog_server_collection: + description: + - The list of syslog server IP addresses. + type: list + elements: str + syslog_server_vrf_collection: + description: + - The list of VRFs for syslog servers. + type: list + elements: str + syslog_severity_collection: + description: + - The list of syslog severity levels (0-7). + type: list + elements: int + state: + description: + - The desired state of the fabric resources on the Cisco Nexus Dashboard. + - Use O(state=merged) to create new fabrics and update existing ones as defined in the configuration. + Resources on ND that are not specified in the configuration will be left unchanged. + - Use O(state=replaced) to replace the fabric configuration specified in the configuration. + Any settings not explicitly provided will revert to their defaults. + - Use O(state=overridden) to enforce the configuration as the single source of truth. + Any fabric existing on ND but not present in the configuration will be deleted. Use with extra caution. + - Use O(state=deleted) to remove the fabrics specified in the configuration from the Cisco Nexus Dashboard. + type: str + default: merged + choices: [ merged, replaced, overridden, deleted ] +extends_documentation_fragment: +- cisco.nd.modules +- cisco.nd.check_mode +notes: +- This module is only supported on Nexus Dashboard having version 4.1.0 or higher. +- Only eBGP VXLAN fabric type (C(vxlanEbgp)) is supported by this module. +- When using O(state=replaced) with only required fields, all optional management settings revert to their defaults. +- The O(config.management.bgp_asn) field is optional when O(config.management.bgp_asn_auto_allocation) is C(true). +- The O(config.management.bgp_asn) field is required when O(config.management.bgp_asn_auto_allocation) is C(false). +- O(config.management.site_id) defaults to the value of O(config.management.bgp_asn) if not provided. +- The default O(config.management.vpc_peer_keep_alive_option) for eBGP fabrics is C(management), unlike iBGP fabrics. +""" + +EXAMPLES = r""" +- name: Create an eBGP VXLAN fabric using state merged (with auto ASN allocation) + cisco.nd.nd_manage_fabric_ebgp: + state: merged + config: + - name: my_ebgp_fabric + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanEbgp + bgp_asn_auto_allocation: true + bgp_asn_range: "65000-65535" + bgp_as_mode: multiAS + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00aa" + performance_monitoring: false + replication_mode: multicast + multicast_group_subnet: "239.1.1.0/25" + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 2 + rendezvous_point_loopback_id: 254 + vpc_peer_link_vlan: "3600" + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: management + vpc_auto_recovery_timer: 360 + vpc_delay_restore_timer: 150 + vpc_peer_link_port_channel_id: "500" + advertise_physical_ip: false + vpc_domain_id_range: "1-1000" + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9216 + l2_host_interface_mtu: 9216 + tenant_dhcp: true + nxapi: false + nxapi_https_port: 443 + nxapi_http: false + nxapi_http_port: 80 + snmp_trap: true + anycast_border_gateway_advertise_physical_ip: false + greenfield_debug_flag: disable + tcam_allocation: true + real_time_interface_statistics_collection: false + interface_statistics_load_interval: 10 + bgp_loopback_ip_range: "10.2.0.0/22" + nve_loopback_ip_range: "10.3.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.254.0/24" + intra_fabric_subnet_range: "10.4.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.33.0.0/16" + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.5.0.0/22" + banner: "" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + register: result + +- name: Create an eBGP VXLAN fabric with a static BGP ASN + cisco.nd.nd_manage_fabric_ebgp: + state: merged + config: + - name: my_ebgp_fabric_static + category: fabric + management: + type: vxlanEbgp + bgp_asn: "65001" + bgp_asn_auto_allocation: false + site_id: "65001" + bgp_as_mode: multiAS + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00aa" + replication_mode: multicast + multicast_group_subnet: "239.1.1.0/25" + bgp_loopback_ip_range: "10.2.0.0/22" + nve_loopback_ip_range: "10.3.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.254.0/24" + intra_fabric_subnet_range: "10.4.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + register: result + +- name: Update specific fields on an existing eBGP fabric using state merged (partial update) + cisco.nd.nd_manage_fabric_ebgp: + state: merged + config: + - name: my_ebgp_fabric + category: fabric + management: + bgp_asn_range: "65100-65199" + anycast_gateway_mac: "2020.0000.00bb" + performance_monitoring: true + register: result + +- name: Create or fully replace an eBGP VXLAN fabric using state replaced + cisco.nd.nd_manage_fabric_ebgp: + state: replaced + config: + - name: my_ebgp_fabric + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanEbgp + bgp_asn: "65004" + bgp_asn_auto_allocation: false + site_id: "65004" + bgp_as_mode: multiAS + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00dd" + performance_monitoring: true + replication_mode: multicast + multicast_group_subnet: "239.1.3.0/25" + rendezvous_point_count: 3 + rendezvous_point_loopback_id: 253 + vpc_peer_link_vlan: "3700" + vpc_peer_keep_alive_option: management + vpc_auto_recovery_timer: 300 + vpc_delay_restore_timer: 120 + vpc_peer_link_port_channel_id: "600" + advertise_physical_ip: true + vpc_domain_id_range: "1-800" + fabric_mtu: 9000 + l2_host_interface_mtu: 9000 + tenant_dhcp: false + snmp_trap: false + anycast_border_gateway_advertise_physical_ip: true + greenfield_debug_flag: disable + tcam_allocation: false + real_time_interface_statistics_collection: true + interface_statistics_load_interval: 30 + bgp_loopback_ip_range: "10.22.0.0/22" + nve_loopback_ip_range: "10.23.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.252.0/24" + intra_fabric_subnet_range: "10.24.0.0/16" + l2_vni_range: "40000-59000" + l3_vni_range: "60000-69000" + network_vlan_range: "2400-3099" + vrf_vlan_range: "2100-2399" + banner: "^ Managed by Ansible ^" + register: result + +- name: Replace fabric with only required fields (all optional settings revert to defaults) + cisco.nd.nd_manage_fabric_ebgp: + state: replaced + config: + - name: my_ebgp_fabric + category: fabric + management: + type: vxlanEbgp + bgp_asn: "65004" + bgp_asn_auto_allocation: false + site_id: "65004" + banner: "^ Managed by Ansible ^" + register: result + +- name: Enforce exact fabric inventory using state overridden (deletes unlisted fabrics) + cisco.nd.nd_manage_fabric_ebgp: + state: overridden + config: + - name: fabric_east + category: fabric + location: + latitude: 40.7128 + longitude: -74.0060 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanEbgp + bgp_asn: "65010" + bgp_asn_auto_allocation: false + site_id: "65010" + bgp_as_mode: multiAS + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.0010" + replication_mode: multicast + multicast_group_subnet: "239.1.10.0/25" + bgp_loopback_ip_range: "10.10.0.0/22" + nve_loopback_ip_range: "10.11.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.10.0/24" + intra_fabric_subnet_range: "10.12.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + - name: fabric_west + category: fabric + location: + latitude: 34.0522 + longitude: -118.2437 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanEbgp + bgp_asn: "65020" + bgp_asn_auto_allocation: false + site_id: "65020" + bgp_as_mode: multiAS + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.0020" + replication_mode: multicast + multicast_group_subnet: "239.1.20.0/25" + bgp_loopback_ip_range: "10.20.0.0/22" + nve_loopback_ip_range: "10.21.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.20.0/24" + intra_fabric_subnet_range: "10.22.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + register: result + +- name: Delete a specific eBGP fabric using state deleted + cisco.nd.nd_manage_fabric_ebgp: + state: deleted + config: + - name: my_ebgp_fabric + register: result + +- name: Delete multiple eBGP fabrics in a single task + cisco.nd.nd_manage_fabric_ebgp: + state: deleted + config: + - name: fabric_east + - name: fabric_west + - name: fabric_old + register: result +""" + +RETURN = r""" +""" + +from ansible.module_utils.basic import AnsibleModule +from ansible_collections.cisco.nd.plugins.module_utils.nd import nd_argument_spec +from ansible_collections.cisco.nd.plugins.module_utils.nd_state_machine import NDStateMachine +from ansible_collections.cisco.nd.plugins.module_utils.models.manage_fabric.manage_fabric_ebgp import FabricEbgpModel +from ansible_collections.cisco.nd.plugins.module_utils.orchestrators.manage_fabric_ebgp import ManageEbgpFabricOrchestrator +from ansible_collections.cisco.nd.plugins.module_utils.common.exceptions import NDStateMachineError + + +def main(): + argument_spec = nd_argument_spec() + argument_spec.update(FabricEbgpModel.get_argument_spec()) + + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + try: + # Initialize StateMachine + nd_state_machine = NDStateMachine( + module=module, + model_orchestrator=ManageEbgpFabricOrchestrator, + ) + + # Manage state + nd_state_machine.manage_state() + + module.exit_json(**nd_state_machine.output.format()) + + except NDStateMachineError as e: + module.fail_json(msg=str(e)) + except Exception as e: + module.fail_json(msg=f"Module execution failed: {str(e)}") + +if __name__ == "__main__": + main() diff --git a/plugins/modules/nd_manage_fabric_ibgp.py b/plugins/modules/nd_manage_fabric_ibgp.py new file mode 100644 index 00000000..9d857fc6 --- /dev/null +++ b/plugins/modules/nd_manage_fabric_ibgp.py @@ -0,0 +1,1393 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright: (c) 2026, Mike Wiebe (@mwiebe) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "community"} + +DOCUMENTATION = r""" +--- +module: nd_manage_fabric_ibgp +version_added: "1.4.0" +short_description: Manage iBGP VXLAN fabrics on Cisco Nexus Dashboard +description: +- Manage iBGP VXLAN fabrics on Cisco Nexus Dashboard (ND). +- It supports creating, updating, replacing, and deleting iBGP VXLAN fabrics. +author: +- Mike Wiebe (@mwiebe) +options: + config: + description: + - The list of iBGP VXLAN fabrics to configure. + type: list + elements: dict + suboptions: + name: + description: + - The name of the fabric. + - Only letters, numbers, underscores, and hyphens are allowed. + - The O(config.name) must be defined when creating, updating or deleting a fabric. + type: str + required: true + category: + description: + - The resource category. + type: str + default: fabric + location: + description: + - The geographic location of the fabric. + type: dict + suboptions: + latitude: + description: + - Latitude coordinate of the fabric location (-90 to 90). + type: float + required: true + longitude: + description: + - Longitude coordinate of the fabric location (-180 to 180). + type: float + required: true + license_tier: + description: + - The license tier for the fabric. + type: str + default: premier + choices: [ essentials, premier ] + alert_suspend: + description: + - The alert suspension state for the fabric. + type: str + default: disabled + choices: [ enabled, disabled ] + telemetry_collection: + description: + - Enable telemetry collection for the fabric. + type: bool + default: false + telemetry_collection_type: + description: + - The telemetry collection type. + type: str + default: outOfBand + telemetry_streaming_protocol: + description: + - The telemetry streaming protocol. + type: str + default: ipv4 + telemetry_source_interface: + description: + - The telemetry source interface. + type: str + default: "" + telemetry_source_vrf: + description: + - The telemetry source VRF. + type: str + default: "" + security_domain: + description: + - The security domain associated with the fabric. + type: str + default: all + management: + description: + - The iBGP VXLAN management configuration for the fabric. + type: dict + suboptions: + type: + description: + - The fabric management type. Must be C(vxlanIbgp) for iBGP VXLAN fabrics. + type: str + default: vxlanIbgp + choices: [ vxlanIbgp ] + bgp_asn: + description: + - The BGP Autonomous System Number for the fabric. + - Must be a numeric value between 1 and 4294967295. + type: str + required: true + site_id: + description: + - The site identifier for the fabric. + - Must be a numeric value between 1 and 65535. + - Defaults to the value of O(config.management.bgp_asn) if not provided. + type: str + default: "" + target_subnet_mask: + description: + - The target subnet mask for intra-fabric links. + type: int + default: 30 + anycast_gateway_mac: + description: + - The anycast gateway MAC address in xxxx.xxxx.xxxx format. + type: str + default: 2020.0000.00aa + replication_mode: + description: + - The multicast replication mode. + type: str + default: multicast + choices: [ multicast, ingress ] + multicast_group_subnet: + description: + - The multicast group subnet. + type: str + default: "239.1.1.0/25" + auto_generate_multicast_group_address: + description: + - Automatically generate multicast group addresses. + type: bool + default: false + underlay_multicast_group_address_limit: + description: + - The underlay multicast group address limit (1-255). + type: int + default: 128 + tenant_routed_multicast: + description: + - Enable tenant routed multicast. + type: bool + default: false + rendezvous_point_count: + description: + - The number of rendezvous points (1-4). + type: int + default: 2 + rendezvous_point_loopback_id: + description: + - The rendezvous point loopback interface ID (0-1023). + type: int + default: 254 + overlay_mode: + description: + - The overlay configuration mode. + type: str + default: cli + choices: [ cli, config-profile ] + link_state_routing_protocol: + description: + - The underlay link-state routing protocol. + type: str + default: ospf + choices: [ ospf, isis ] + ospf_area_id: + description: + - The OSPF area ID. + type: str + default: "0.0.0.0" + fabric_interface_type: + description: + - The fabric interface type. + type: str + default: p2p + bgp_loopback_id: + description: + - The BGP loopback interface ID (0-1023). + type: int + default: 0 + nve_loopback_id: + description: + - The NVE loopback interface ID (0-1023). + type: int + default: 1 + route_reflector_count: + description: + - The number of BGP route reflectors (1-4). + type: int + default: 2 + bgp_loopback_ip_range: + description: + - The BGP loopback IP address pool. + type: str + default: "10.2.0.0/22" + nve_loopback_ip_range: + description: + - The NVE loopback IP address pool. + type: str + default: "10.3.0.0/22" + anycast_rendezvous_point_ip_range: + description: + - The anycast rendezvous point IP address pool. + type: str + default: "10.254.254.0/24" + intra_fabric_subnet_range: + description: + - The intra-fabric subnet IP address pool. + type: str + default: "10.4.0.0/16" + router_id_range: + description: + - The router ID IP address pool. + type: str + default: "10.2.0.0/23" + l2_vni_range: + description: + - The Layer 2 VNI range. + type: str + default: "30000-49000" + l3_vni_range: + description: + - The Layer 3 VNI range. + type: str + default: "50000-59000" + network_vlan_range: + description: + - The network VLAN range. + type: str + default: "2300-2999" + vrf_vlan_range: + description: + - The VRF VLAN range. + type: str + default: "2000-2299" + sub_interface_dot1q_range: + description: + - The sub-interface 802.1q range. + type: str + default: "2-511" + service_network_vlan_range: + description: + - The service network VLAN range. + type: str + default: "3000-3199" + l3_vni_no_vlan_default_option: + description: + - Enable L3 VNI no-VLAN default option. + type: bool + default: false + fabric_mtu: + description: + - The fabric MTU size (1500-9216). + type: int + default: 9216 + l2_host_interface_mtu: + description: + - The L2 host interface MTU size (1500-9216). + type: int + default: 9216 + vpc_domain_id_range: + description: + - The vPC domain ID range. + type: str + default: "1-1000" + vpc_peer_link_vlan: + description: + - The vPC peer link VLAN ID. + type: str + default: "3600" + vpc_peer_link_enable_native_vlan: + description: + - Enable native VLAN on the vPC peer link. + type: bool + default: false + vpc_peer_keep_alive_option: + description: + - The vPC peer keep-alive option. + type: str + default: loopback + vpc_auto_recovery_timer: + description: + - The vPC auto recovery timer in seconds (240-3600). + type: int + default: 360 + vpc_delay_restore_timer: + description: + - The vPC delay restore timer in seconds (1-3600). + type: int + default: 150 + vpc_peer_link_port_channel_id: + description: + - The vPC peer link port-channel ID. + type: str + default: "500" + vpc_ipv6_neighbor_discovery_sync: + description: + - Enable vPC IPv6 neighbor discovery synchronization. + type: bool + default: true + vpc_layer3_peer_router: + description: + - Enable vPC layer-3 peer router. + type: bool + default: true + vpc_tor_delay_restore_timer: + description: + - The vPC TOR delay restore timer. + type: int + default: 30 + fabric_vpc_domain_id: + description: + - Enable fabric vPC domain ID. + type: bool + default: false + shared_vpc_domain_id: + description: + - The shared vPC domain ID. + type: int + default: 1 + fabric_vpc_qos: + description: + - Enable fabric vPC QoS. + type: bool + default: false + fabric_vpc_qos_policy_name: + description: + - The fabric vPC QoS policy name. + type: str + default: spine_qos_for_fabric_vpc_peering + enable_peer_switch: + description: + - Enable peer switch. + type: bool + default: false + vrf_template: + description: + - The VRF template name. + type: str + default: Default_VRF_Universal + network_template: + description: + - The network template name. + type: str + default: Default_Network_Universal + vrf_extension_template: + description: + - The VRF extension template name. + type: str + default: Default_VRF_Extension_Universal + network_extension_template: + description: + - The network extension template name. + type: str + default: Default_Network_Extension_Universal + performance_monitoring: + description: + - Enable performance monitoring. + type: bool + default: false + tenant_dhcp: + description: + - Enable tenant DHCP. + type: bool + default: true + advertise_physical_ip: + description: + - Advertise physical IP address for NVE loopback. + type: bool + default: false + advertise_physical_ip_on_border: + description: + - Advertise physical IP address on border switches. + type: bool + default: true + anycast_border_gateway_advertise_physical_ip: + description: + - Enable anycast border gateway to advertise physical IP. + type: bool + default: false + snmp_trap: + description: + - Enable SNMP traps. + type: bool + default: true + cdp: + description: + - Enable CDP. + type: bool + default: false + tcam_allocation: + description: + - Enable TCAM allocation. + type: bool + default: true + real_time_interface_statistics_collection: + description: + - Enable real-time interface statistics collection. + type: bool + default: false + interface_statistics_load_interval: + description: + - The interface statistics load interval in seconds. + type: int + default: 10 + greenfield_debug_flag: + description: + - The greenfield debug flag. + type: str + default: enable + nxapi: + description: + - Enable NX-API (HTTPS). + type: bool + default: false + nxapi_https_port: + description: + - The NX-API HTTPS port (1-65535). + type: int + default: 443 + nxapi_http: + description: + - Enable NX-API HTTP. + type: bool + default: true + nxapi_http_port: + description: + - The NX-API HTTP port (1-65535). + type: int + default: 80 + bgp_authentication: + description: + - Enable BGP authentication. + type: bool + default: false + bgp_authentication_key_type: + description: + - The BGP authentication key type. + type: str + default: 3des + bgp_authentication_key: + description: + - The BGP authentication key. + type: str + default: "" + bfd: + description: + - Enable BFD globally. + type: bool + default: false + bfd_ibgp: + description: + - Enable BFD for iBGP sessions. + type: bool + default: false + bfd_ospf: + description: + - Enable BFD for OSPF. + type: bool + default: false + bfd_isis: + description: + - Enable BFD for IS-IS. + type: bool + default: false + bfd_pim: + description: + - Enable BFD for PIM. + type: bool + default: false + bfd_authentication: + description: + - Enable BFD authentication. + type: bool + default: false + bfd_authentication_key_id: + description: + - The BFD authentication key ID. + type: int + default: 100 + bfd_authentication_key: + description: + - The BFD authentication key. + type: str + default: "" + ospf_authentication: + description: + - Enable OSPF authentication. + type: bool + default: false + ospf_authentication_key_id: + description: + - The OSPF authentication key ID. + type: int + default: 127 + ospf_authentication_key: + description: + - The OSPF authentication key. + type: str + default: "" + pim_hello_authentication: + description: + - Enable PIM hello authentication. + type: bool + default: false + pim_hello_authentication_key: + description: + - The PIM hello authentication key. + type: str + default: "" + isis_level: + description: + - The IS-IS level. + type: str + default: level-2 + isis_area_number: + description: + - The IS-IS area number. + type: str + default: "0001" + isis_point_to_point: + description: + - Enable IS-IS point-to-point. + type: bool + default: true + isis_authentication: + description: + - Enable IS-IS authentication. + type: bool + default: false + isis_authentication_keychain_name: + description: + - The IS-IS authentication keychain name. + type: str + default: "" + isis_authentication_keychain_key_id: + description: + - The IS-IS authentication keychain key ID. + type: int + default: 127 + isis_authentication_key: + description: + - The IS-IS authentication key. + type: str + default: "" + isis_overload: + description: + - Enable IS-IS overload bit. + type: bool + default: true + isis_overload_elapse_time: + description: + - The IS-IS overload elapse time in seconds. + type: int + default: 60 + macsec: + description: + - Enable MACsec on intra-fabric links. + type: bool + default: false + macsec_cipher_suite: + description: + - The MACsec cipher suite. + type: str + default: GCM-AES-XPN-256 + macsec_key_string: + description: + - The MACsec primary key string. + type: str + default: "" + macsec_algorithm: + description: + - The MACsec algorithm. + type: str + default: AES_128_CMAC + macsec_fallback_key_string: + description: + - The MACsec fallback key string. + type: str + default: "" + macsec_fallback_algorithm: + description: + - The MACsec fallback algorithm. + type: str + default: AES_128_CMAC + macsec_report_timer: + description: + - The MACsec report timer. + type: int + default: 5 + vrf_lite_macsec: + description: + - Enable MACsec on VRF lite links. + type: bool + default: false + quantum_key_distribution: + description: + - Enable quantum key distribution. + type: bool + default: false + quantum_key_distribution_profile_name: + description: + - The quantum key distribution profile name. + type: str + default: "" + key_management_entity_server_ip: + description: + - The key management entity server IP address. + type: str + default: "" + key_management_entity_server_port: + description: + - The key management entity server port. + type: int + default: 0 + trustpoint_label: + description: + - The trustpoint label. + type: str + default: "" + vrf_lite_auto_config: + description: + - The VRF lite auto-configuration mode. + type: str + default: manual + vrf_lite_subnet_range: + description: + - The VRF lite subnet IP address pool. + type: str + default: "10.33.0.0/16" + vrf_lite_subnet_target_mask: + description: + - The VRF lite subnet target mask. + type: int + default: 30 + vrf_lite_ipv6_subnet_range: + description: + - The VRF lite IPv6 subnet range. + type: str + default: "fd00::a33:0/112" + vrf_lite_ipv6_subnet_target_mask: + description: + - The VRF lite IPv6 subnet target mask (112-128). + type: int + default: 126 + auto_unique_vrf_lite_ip_prefix: + description: + - Enable auto unique VRF lite IP prefix. + type: bool + default: false + auto_symmetric_vrf_lite: + description: + - Enable auto symmetric VRF lite. + type: bool + default: false + auto_vrf_lite_default_vrf: + description: + - Enable auto VRF lite for the default VRF. + type: bool + default: false + auto_symmetric_default_vrf: + description: + - Enable auto symmetric default VRF. + type: bool + default: false + per_vrf_loopback_auto_provision: + description: + - Enable per-VRF loopback auto-provisioning. + type: bool + default: false + per_vrf_loopback_ip_range: + description: + - The per-VRF loopback IP address pool. + type: str + default: "10.5.0.0/22" + per_vrf_loopback_auto_provision_ipv6: + description: + - Enable per-VRF loopback auto-provisioning for IPv6. + type: bool + default: false + per_vrf_loopback_ipv6_range: + description: + - The per-VRF loopback IPv6 address pool. + type: str + default: "fd00::a05:0/112" + underlay_ipv6: + description: + - Enable IPv6 underlay. + type: bool + default: false + ipv6_multicast_group_subnet: + description: + - The IPv6 multicast group subnet. + type: str + default: "ff1e::/121" + tenant_routed_multicast_ipv6: + description: + - Enable tenant routed multicast for IPv6. + type: bool + default: false + ipv6_link_local: + description: + - Enable IPv6 link-local addressing. + type: bool + default: true + ipv6_subnet_target_mask: + description: + - The IPv6 subnet target mask. + type: int + default: 126 + ipv6_subnet_range: + description: + - The IPv6 subnet range. + type: str + default: "fd00::a04:0/112" + bgp_loopback_ipv6_range: + description: + - The BGP loopback IPv6 address pool. + type: str + default: "fd00::a02:0/119" + nve_loopback_ipv6_range: + description: + - The NVE loopback IPv6 address pool. + type: str + default: "fd00::a03:0/118" + ipv6_anycast_rendezvous_point_ip_range: + description: + - The IPv6 anycast rendezvous point IP address pool. + type: str + default: "fd00::254:254:0/118" + auto_bgp_neighbor_description: + description: + - Enable automatic BGP neighbor description. + type: bool + default: true + ibgp_peer_template: + description: + - The iBGP peer template name. + type: str + default: "" + leaf_ibgp_peer_template: + description: + - The leaf iBGP peer template name. + type: str + default: "" + link_state_routing_tag: + description: + - The link state routing tag. + type: str + default: UNDERLAY + static_underlay_ip_allocation: + description: + - Enable static underlay IP allocation. + type: bool + default: false + security_group_tag: + description: + - Enable Security Group Tag (SGT) support. + type: bool + default: false + security_group_tag_prefix: + description: + - The SGT prefix. + type: str + default: SG_ + security_group_tag_mac_segmentation: + description: + - Enable SGT MAC segmentation. + type: bool + default: false + security_group_tag_id_range: + description: + - The SGT ID range. + type: str + default: "10000-14000" + security_group_tag_preprovision: + description: + - Enable SGT pre-provisioning. + type: bool + default: false + security_group_status: + description: + - The security group status. + type: str + default: enabled + default_queuing_policy: + description: + - Enable default queuing policy. + type: bool + default: false + aiml_qos: + description: + - Enable AI/ML QoS. + type: bool + default: false + aiml_qos_policy: + description: + - The AI/ML QoS policy. + type: str + default: 400G + dlb: + description: + - Enable dynamic load balancing. + type: bool + default: false + dlb_mode: + description: + - The DLB mode. + type: str + default: flowlet + ptp: + description: + - Enable Precision Time Protocol (PTP). + type: bool + default: false + ptp_loopback_id: + description: + - The PTP loopback ID. + type: int + default: 0 + ptp_domain_id: + description: + - The PTP domain ID. + type: int + default: 0 + stp_root_option: + description: + - The STP root option. + type: str + default: mst + stp_vlan_range: + description: + - The STP VLAN range. + type: str + default: "" + mst_instance_range: + description: + - The MST instance range. + type: str + default: "0-3,5,7-9" + stp_bridge_priority: + description: + - The STP bridge priority. + type: int + default: 0 + mpls_handoff: + description: + - Enable MPLS handoff. + type: bool + default: false + mpls_loopback_identifier: + description: + - The MPLS loopback identifier. + type: int + default: 101 + mpls_loopback_ip_range: + description: + - The MPLS loopback IP address pool. + type: str + default: "10.101.0.0/25" + private_vlan: + description: + - Enable private VLAN support. + type: bool + default: false + ip_service_level_agreement_id_range: + description: + - The IP SLA ID range. + type: str + default: "10000-19999" + object_tracking_number_range: + description: + - The object tracking number range. + type: str + default: "100-299" + route_map_sequence_number_range: + description: + - The route map sequence number range. + type: str + default: "1-65534" + day0_bootstrap: + description: + - Enable day-0 bootstrap (POAP). + type: bool + default: false + local_dhcp_server: + description: + - Enable local DHCP server for bootstrap. + type: bool + default: false + dhcp_protocol_version: + description: + - The DHCP protocol version for bootstrap. + type: str + default: dhcpv4 + dhcp_start_address: + description: + - The DHCP start address for bootstrap. + type: str + default: "" + dhcp_end_address: + description: + - The DHCP end address for bootstrap. + type: str + default: "" + management_gateway: + description: + - The management gateway for bootstrap. + type: str + default: "" + management_ipv4_prefix: + description: + - The management IPv4 prefix length for bootstrap. + type: int + default: 24 + management_ipv6_prefix: + description: + - The management IPv6 prefix length for bootstrap. + type: int + default: 64 + real_time_backup: + description: + - Enable real-time backup. + type: bool + default: false + scheduled_backup: + description: + - Enable scheduled backup. + type: bool + default: false + scheduled_backup_time: + description: + - The scheduled backup time. + type: str + default: "" + nve_hold_down_timer: + description: + - The NVE hold-down timer in seconds. + type: int + default: 180 + next_generation_oam: + description: + - Enable next-generation OAM. + type: bool + default: true + strict_config_compliance_mode: + description: + - Enable strict configuration compliance mode. + type: bool + default: false + copp_policy: + description: + - The CoPP policy. + type: str + default: dense + power_redundancy_mode: + description: + - The power redundancy mode. + type: str + default: redundant + host_interface_admin_state: + description: + - Enable host interface admin state. + type: bool + default: true + heartbeat_interval: + description: + - The heartbeat interval. + type: int + default: 190 + policy_based_routing: + description: + - Enable policy-based routing. + type: bool + default: false + brownfield_network_name_format: + description: + - The brownfield network name format. + type: str + default: "Auto_Net_VNI$$VNI$$_VLAN$$VLAN_ID$$" + brownfield_skip_overlay_network_attachments: + description: + - Skip brownfield overlay network attachments. + type: bool + default: false + allow_smart_switch_onboarding: + description: + - Allow smart switch onboarding. + type: bool + default: false + aaa: + description: + - Enable AAA. + type: bool + default: false + extra_config_leaf: + description: + - Extra freeform configuration applied to leaf switches. + type: str + default: "" + extra_config_spine: + description: + - Extra freeform configuration applied to spine switches. + type: str + default: "" + extra_config_tor: + description: + - Extra freeform configuration applied to TOR switches. + type: str + default: "" + extra_config_intra_fabric_links: + description: + - Extra freeform configuration applied to intra-fabric links. + type: str + default: "" + extra_config_aaa: + description: + - Extra freeform AAA configuration. + type: str + default: "" + banner: + description: + - The fabric banner text displayed on switch login. + type: str + default: "" + ntp_server_collection: + description: + - The list of NTP server IP addresses. + type: list + elements: str + dns_collection: + description: + - The list of DNS server IP addresses. + type: list + elements: str + syslog_server_collection: + description: + - The list of syslog server IP addresses. + type: list + elements: str + syslog_server_vrf_collection: + description: + - The list of VRFs for syslog servers. + type: list + elements: str + syslog_severity_collection: + description: + - The list of syslog severity levels (0-7). + type: list + elements: int + state: + description: + - The desired state of the fabric resources on the Cisco Nexus Dashboard. + - Use O(state=merged) to create new fabrics and update existing ones as defined in the configuration. + Resources on ND that are not specified in the configuration will be left unchanged. + - Use O(state=replaced) to replace the fabric configuration specified in the configuration. + Any settings not explicitly provided will revert to their defaults. + - Use O(state=overridden) to enforce the configuration as the single source of truth. + Any fabric existing on ND but not present in the configuration will be deleted. Use with extra caution. + - Use O(state=deleted) to remove the fabrics specified in the configuration from the Cisco Nexus Dashboard. + type: str + default: merged + choices: [ merged, replaced, overridden, deleted ] +extends_documentation_fragment: +- cisco.nd.modules +- cisco.nd.check_mode +notes: +- This module is only supported on Nexus Dashboard having version 4.1.0 or higher. +- Only iBGP VXLAN fabric type (C(vxlanIbgp)) is supported by this module. +- When using O(state=replaced) with only required fields, all optional management settings revert to their defaults. +- The O(config.management.bgp_asn) field is required when creating a fabric. +- O(config.management.site_id) defaults to the value of O(config.management.bgp_asn) if not provided. +""" + +EXAMPLES = r""" +- name: Create an iBGP VXLAN fabric using state merged + cisco.nd.nd_manage_fabric_ibgp: + state: merged + config: + - name: my_fabric + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanIbgp + bgp_asn: "65001" + site_id: "65001" + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00aa" + performance_monitoring: false + replication_mode: multicast + multicast_group_subnet: "239.1.1.0/25" + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 2 + rendezvous_point_loopback_id: 254 + vpc_peer_link_vlan: "3600" + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: loopback + vpc_auto_recovery_timer: 360 + vpc_delay_restore_timer: 150 + vpc_peer_link_port_channel_id: "500" + advertise_physical_ip: false + vpc_domain_id_range: "1-1000" + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9216 + l2_host_interface_mtu: 9216 + tenant_dhcp: true + nxapi: true + nxapi_https_port: 443 + nxapi_http: false + nxapi_http_port: 80 + snmp_trap: true + anycast_border_gateway_advertise_physical_ip: false + greenfield_debug_flag: enable + tcam_allocation: true + real_time_interface_statistics_collection: false + interface_statistics_load_interval: 10 + bgp_loopback_ip_range: "10.2.0.0/22" + nve_loopback_ip_range: "10.3.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.254.0/24" + intra_fabric_subnet_range: "10.4.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.33.0.0/16" + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.5.0.0/22" + banner: "" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + register: result + +- name: Update specific fields on an existing fabric using state merged (partial update) + cisco.nd.nd_manage_fabric_ibgp: + state: merged + config: + - name: my_fabric + category: fabric + management: + bgp_asn: "65002" + site_id: "65002" + anycast_gateway_mac: "2020.0000.00bb" + performance_monitoring: true + register: result + +- name: Create or fully replace an iBGP VXLAN fabric using state replaced + cisco.nd.nd_manage_fabric_ibgp: + state: replaced + config: + - name: my_fabric + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanIbgp + bgp_asn: "65004" + site_id: "65004" + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00dd" + performance_monitoring: true + replication_mode: multicast + multicast_group_subnet: "239.1.3.0/25" + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 3 + rendezvous_point_loopback_id: 253 + vpc_peer_link_vlan: "3700" + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: loopback + vpc_auto_recovery_timer: 300 + vpc_delay_restore_timer: 120 + vpc_peer_link_port_channel_id: "600" + vpc_ipv6_neighbor_discovery_sync: false + advertise_physical_ip: true + vpc_domain_id_range: "1-800" + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9000 + l2_host_interface_mtu: 9000 + tenant_dhcp: false + nxapi: false + nxapi_https_port: 443 + nxapi_http: true + nxapi_http_port: 80 + snmp_trap: false + anycast_border_gateway_advertise_physical_ip: true + greenfield_debug_flag: disable + tcam_allocation: false + real_time_interface_statistics_collection: true + interface_statistics_load_interval: 30 + bgp_loopback_ip_range: "10.22.0.0/22" + nve_loopback_ip_range: "10.23.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.252.0/24" + intra_fabric_subnet_range: "10.24.0.0/16" + l2_vni_range: "40000-59000" + l3_vni_range: "60000-69000" + network_vlan_range: "2400-3099" + vrf_vlan_range: "2100-2399" + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.53.0.0/16" + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.25.0.0/22" + per_vrf_loopback_auto_provision_ipv6: true + per_vrf_loopback_ipv6_range: "fd00::a25:0/112" + banner: "^ Managed by Ansible ^" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + management_ipv6_prefix: 64 + register: result + +- name: Replace fabric with only required fields (all optional settings revert to defaults) + cisco.nd.nd_manage_fabric_ibgp: + state: replaced + config: + - name: my_fabric + category: fabric + management: + type: vxlanIbgp + bgp_asn: "65004" + site_id: "65004" + banner: "^ Managed by Ansible ^" + register: result + +- name: Enforce exact fabric inventory using state overridden (deletes unlisted fabrics) + cisco.nd.nd_manage_fabric_ibgp: + state: overridden + config: + - name: fabric_east + category: fabric + location: + latitude: 40.7128 + longitude: -74.0060 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanIbgp + bgp_asn: "65010" + site_id: "65010" + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.0010" + replication_mode: multicast + multicast_group_subnet: "239.1.10.0/25" + bgp_loopback_ip_range: "10.10.0.0/22" + nve_loopback_ip_range: "10.11.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.10.0/24" + intra_fabric_subnet_range: "10.12.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + - name: fabric_west + category: fabric + location: + latitude: 34.0522 + longitude: -118.2437 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanIbgp + bgp_asn: "65020" + site_id: "65020" + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.0020" + replication_mode: multicast + multicast_group_subnet: "239.1.20.0/25" + bgp_loopback_ip_range: "10.20.0.0/22" + nve_loopback_ip_range: "10.21.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.20.0/24" + intra_fabric_subnet_range: "10.22.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + register: result + +- name: Delete a specific fabric using state deleted + cisco.nd.nd_manage_fabric_ibgp: + state: deleted + config: + - name: my_fabric + register: result + +- name: Delete multiple fabrics in a single task + cisco.nd.nd_manage_fabric_ibgp: + state: deleted + config: + - name: fabric_east + - name: fabric_west + - name: fabric_old + register: result +""" + +RETURN = r""" +""" + +from ansible.module_utils.basic import AnsibleModule +from ansible_collections.cisco.nd.plugins.module_utils.nd import nd_argument_spec +from ansible_collections.cisco.nd.plugins.module_utils.nd_state_machine import NDStateMachine +from ansible_collections.cisco.nd.plugins.module_utils.models.manage_fabric.manage_fabric_ibgp import FabricIbgpModel +from ansible_collections.cisco.nd.plugins.module_utils.orchestrators.manage_fabric_ibgp import ManageIbgpFabricOrchestrator +from ansible_collections.cisco.nd.plugins.module_utils.common.exceptions import NDStateMachineError + + +def main(): + argument_spec = nd_argument_spec() + argument_spec.update(FabricIbgpModel.get_argument_spec()) + + module = AnsibleModule( + argument_spec=argument_spec, + supports_check_mode=True, + ) + + try: + # Initialize StateMachine + nd_state_machine = NDStateMachine( + module=module, + model_orchestrator=ManageIbgpFabricOrchestrator, + ) + + # Manage state + nd_state_machine.manage_state() + + module.exit_json(**nd_state_machine.output.format()) + + except NDStateMachineError as e: + module.fail_json(msg=str(e)) + except Exception as e: + module.fail_json(msg=f"Module execution failed: {str(e)}") + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt index 514632d1..98907e9a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ requests_toolbelt jsonpath-ng -lxml \ No newline at end of file +lxml +pydantic==2.12.5 \ No newline at end of file diff --git a/tests/integration/inventory.networking b/tests/integration/inventory.networking index 6b37d8f3..2aa818d7 100644 --- a/tests/integration/inventory.networking +++ b/tests/integration/inventory.networking @@ -1,15 +1,15 @@ [nd] -nd ansible_host= +nd-test ansible_host=10.48.161.120 [nd:vars] ansible_connection=ansible.netcommon.httpapi -ansible_python_interpreter=/usr/bin/python3.9 +ansible_python_interpreter=/usr/bin/python3.12 ansible_network_os=cisco.nd.nd ansible_httpapi_validate_certs=False ansible_httpapi_use_ssl=True ansible_httpapi_use_proxy=True -ansible_user=ansible_github_ci -ansible_password= +ansible_user=admin +ansible_password=C1sco123 insights_group= site_name= site_host= @@ -28,4 +28,4 @@ external_management_service_ip= external_data_service_ip= data_ip= data_gateway= -service_package_host=173.36.219.254 +service_package_host=173.36.219.254 diff --git a/tests/integration/network-integration.requirements.txt b/tests/integration/network-integration.requirements.txt index 514632d1..98907e9a 100644 --- a/tests/integration/network-integration.requirements.txt +++ b/tests/integration/network-integration.requirements.txt @@ -1,3 +1,4 @@ requests_toolbelt jsonpath-ng -lxml \ No newline at end of file +lxml +pydantic==2.12.5 \ No newline at end of file diff --git a/tests/integration/targets/nd_local_user/tasks/main.yml b/tests/integration/targets/nd_local_user/tasks/main.yml new file mode 100644 index 00000000..c76e22c3 --- /dev/null +++ b/tests/integration/targets/nd_local_user/tasks/main.yml @@ -0,0 +1,1115 @@ +# Test code for the ND modules +# Copyright: (c) 2026, Gaspard Micol (@gmicol) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +- name: Test that we have a Nexus Dashboard host, username and password + ansible.builtin.fail: + msg: 'Please define the following variables: ansible_host, ansible_user and ansible_password.' + when: ansible_host is not defined or ansible_user is not defined or ansible_password is not defined + +- name: Set vars + ansible.builtin.set_fact: + nd_info: &nd_info + output_level: '{{ api_key_output_level | default("debug") }}' + +- name: Ensure local users do not exist before test starts + cisco.nd.nd_local_user: &clean_all_local_users + <<: *nd_info + config: + - login_id: ansible_local_user + - login_id: ansible_local_user_2 + - login_id: ansible_local_user_3 + state: deleted + + +# --- MERGED STATE TESTS --- + +# MERGED STATE TESTS: CREATE +- name: Create local users with full and minimum configuration (merged state - check mode) + cisco.nd.nd_local_user: &create_local_user_merged_state + <<: *nd_info + config: + - email: ansibleuser@example.com + login_id: ansible_local_user + first_name: Ansible first name + last_name: Ansible last name + user_password: ansibleLocalUserPassword1%Test + reuse_limitation: 20 + time_interval_limitation: 10 + security_domains: + - name: all + roles: + - observer + - support_engineer + remote_id_claim: ansible_remote_user + remote_user_authorization: true + - login_id: ansible_local_user_2 + user_password: ansibleLocalUser2Password1%Test + security_domains: + - name: all + state: merged + check_mode: true + register: cm_merged_create_local_users + +- name: Create local users with full and minimum configuration (merged state - normal mode) + cisco.nd.nd_local_user: + <<: *create_local_user_merged_state + register: nm_merged_create_local_users + +- name: Asserts for local users merged state creation tasks + ansible.builtin.assert: + that: + - cm_merged_create_local_users is changed + - cm_merged_create_local_users.after | length == 3 + - cm_merged_create_local_users.after.0.login_id == "admin" + - cm_merged_create_local_users.after.0.first_name == "admin" + - cm_merged_create_local_users.after.0.remote_user_authorization == false + - cm_merged_create_local_users.after.0.reuse_limitation == 0 + - cm_merged_create_local_users.after.0.security_domains | length == 1 + - cm_merged_create_local_users.after.0.security_domains.0.name == "all" + - cm_merged_create_local_users.after.0.security_domains.0.roles | length == 1 + - cm_merged_create_local_users.after.0.security_domains.0.roles.0 == "super_admin" + - cm_merged_create_local_users.after.0.time_interval_limitation == 0 + - cm_merged_create_local_users.after.1.email == "ansibleuser@example.com" + - cm_merged_create_local_users.after.1.first_name == "Ansible first name" + - cm_merged_create_local_users.after.1.last_name == "Ansible last name" + - cm_merged_create_local_users.after.1.login_id == "ansible_local_user" + - cm_merged_create_local_users.after.1.remote_id_claim == "ansible_remote_user" + - cm_merged_create_local_users.after.1.remote_user_authorization == true + - cm_merged_create_local_users.after.1.reuse_limitation == 20 + - cm_merged_create_local_users.after.1.security_domains | length == 1 + - cm_merged_create_local_users.after.1.security_domains.0.name == "all" + - cm_merged_create_local_users.after.1.security_domains.0.roles | length == 2 + - cm_merged_create_local_users.after.1.security_domains.0.roles.0 == "observer" + - cm_merged_create_local_users.after.1.security_domains.0.roles.1 == "support_engineer" + - cm_merged_create_local_users.after.1.time_interval_limitation == 10 + - cm_merged_create_local_users.after.2.login_id == "ansible_local_user_2" + - cm_merged_create_local_users.after.2.security_domains | length == 1 + - cm_merged_create_local_users.after.2.security_domains.0.name == "all" + - cm_merged_create_local_users.before | length == 1 + - cm_merged_create_local_users.before.0.login_id == "admin" + - cm_merged_create_local_users.before.0.first_name == "admin" + - cm_merged_create_local_users.before.0.remote_user_authorization == false + - cm_merged_create_local_users.before.0.reuse_limitation == 0 + - cm_merged_create_local_users.before.0.security_domains | length == 1 + - cm_merged_create_local_users.before.0.security_domains.0.name == "all" + - cm_merged_create_local_users.before.0.security_domains.0.roles | length == 1 + - cm_merged_create_local_users.before.0.security_domains.0.roles.0 == "super_admin" + - cm_merged_create_local_users.before.0.time_interval_limitation == 0 + - cm_merged_create_local_users.proposed.0.email == "ansibleuser@example.com" + - cm_merged_create_local_users.proposed.0.first_name == "Ansible first name" + - cm_merged_create_local_users.proposed.0.last_name == "Ansible last name" + - cm_merged_create_local_users.proposed.0.login_id == "ansible_local_user" + - cm_merged_create_local_users.proposed.0.remote_id_claim == "ansible_remote_user" + - cm_merged_create_local_users.proposed.0.remote_user_authorization == true + - cm_merged_create_local_users.proposed.0.reuse_limitation == 20 + - cm_merged_create_local_users.proposed.0.security_domains | length == 1 + - cm_merged_create_local_users.proposed.0.security_domains.0.name == "all" + - cm_merged_create_local_users.proposed.0.security_domains.0.roles | length == 2 + - cm_merged_create_local_users.proposed.0.security_domains.0.roles.0 == "observer" + - cm_merged_create_local_users.proposed.0.security_domains.0.roles.1 == "support_engineer" + - cm_merged_create_local_users.proposed.0.time_interval_limitation == 10 + - cm_merged_create_local_users.proposed.1.login_id == "ansible_local_user_2" + - cm_merged_create_local_users.proposed.1.security_domains | length == 1 + - cm_merged_create_local_users.proposed.1.security_domains.0.name == "all" + - nm_merged_create_local_users is changed + - nm_merged_create_local_users.after.0.first_name == "admin" + - nm_merged_create_local_users.after.0.remote_user_authorization == false + - nm_merged_create_local_users.after.0.reuse_limitation == 0 + - nm_merged_create_local_users.after.0.security_domains | length == 1 + - nm_merged_create_local_users.after.0.security_domains.0.name == "all" + - nm_merged_create_local_users.after.0.security_domains.0.roles | length == 1 + - nm_merged_create_local_users.after.0.security_domains.0.roles.0 == "super_admin" + - nm_merged_create_local_users.after.0.time_interval_limitation == 0 + - nm_merged_create_local_users.after.1.email == "ansibleuser@example.com" + - nm_merged_create_local_users.after.1.first_name == "Ansible first name" + - nm_merged_create_local_users.after.1.last_name == "Ansible last name" + - nm_merged_create_local_users.after.1.login_id == "ansible_local_user" + - nm_merged_create_local_users.after.1.remote_id_claim == "ansible_remote_user" + - nm_merged_create_local_users.after.1.remote_user_authorization == true + - nm_merged_create_local_users.after.1.reuse_limitation == 20 + - nm_merged_create_local_users.after.1.security_domains | length == 1 + - nm_merged_create_local_users.after.1.security_domains.0.name == "all" + - nm_merged_create_local_users.after.1.security_domains.0.roles | length == 2 + - nm_merged_create_local_users.after.1.security_domains.0.roles.0 == "observer" + - nm_merged_create_local_users.after.1.security_domains.0.roles.1 == "support_engineer" + - nm_merged_create_local_users.after.1.time_interval_limitation == 10 + - nm_merged_create_local_users.after.2.login_id == "ansible_local_user_2" + - nm_merged_create_local_users.after.2.security_domains | length == 1 + - nm_merged_create_local_users.after.2.security_domains.0.name == "all" + - nm_merged_create_local_users.before | length == 1 + - nm_merged_create_local_users.before.0.login_id == "admin" + - nm_merged_create_local_users.before.0.first_name == "admin" + - nm_merged_create_local_users.before.0.remote_user_authorization == false + - nm_merged_create_local_users.before.0.reuse_limitation == 0 + - nm_merged_create_local_users.before.0.security_domains | length == 1 + - nm_merged_create_local_users.before.0.security_domains.0.name == "all" + - nm_merged_create_local_users.before.0.security_domains.0.roles | length == 1 + - nm_merged_create_local_users.before.0.security_domains.0.roles.0 == "super_admin" + - nm_merged_create_local_users.before.0.time_interval_limitation == 0 + - nm_merged_create_local_users.proposed.0.email == "ansibleuser@example.com" + - nm_merged_create_local_users.proposed.0.first_name == "Ansible first name" + - nm_merged_create_local_users.proposed.0.last_name == "Ansible last name" + - nm_merged_create_local_users.proposed.0.login_id == "ansible_local_user" + - nm_merged_create_local_users.proposed.0.remote_id_claim == "ansible_remote_user" + - nm_merged_create_local_users.proposed.0.remote_user_authorization == true + - nm_merged_create_local_users.proposed.0.reuse_limitation == 20 + - nm_merged_create_local_users.proposed.0.security_domains | length == 1 + - nm_merged_create_local_users.proposed.0.security_domains.0.name == "all" + - nm_merged_create_local_users.proposed.0.security_domains.0.roles | length == 2 + - nm_merged_create_local_users.proposed.0.security_domains.0.roles.0 == "observer" + - nm_merged_create_local_users.proposed.0.security_domains.0.roles.1 == "support_engineer" + - nm_merged_create_local_users.proposed.0.time_interval_limitation == 10 + - nm_merged_create_local_users.proposed.1.login_id == "ansible_local_user_2" + - nm_merged_create_local_users.proposed.1.security_domains | length == 1 + - nm_merged_create_local_users.proposed.1.security_domains.0.name == "all" + +# MERGED STATE TESTS: UPDATE +- name: Update all ansible_local_user_2's attributes except password (merge state - check mode) + cisco.nd.nd_local_user: &update_second_local_user_merged_state + <<: *nd_info + config: + - email: secondansibleuser@example.com + login_id: ansible_local_user_2 + first_name: Second Ansible first name + last_name: Second Ansible last name + reuse_limitation: 20 + time_interval_limitation: 10 + security_domains: + - name: all + roles: fabric_admin + remote_id_claim: ansible_remote_user_2 + remote_user_authorization: true + state: merged + check_mode: true + register: cm_merged_update_local_user_2 + +- name: Update all ansible_local_user_2's attributes except password (merge state - normal mode) + cisco.nd.nd_local_user: + <<: *update_second_local_user_merged_state + register: nm_merged_update_local_user_2 + +- name: Update all ansible_local_user_2's attributes except password again (merge state - idempotency) + cisco.nd.nd_local_user: + <<: *update_second_local_user_merged_state + register: nm_merged_update_local_user_2_again + +- name: Asserts for local users update tasks + ansible.builtin.assert: + that: + - cm_merged_update_local_user_2 is changed + - cm_merged_update_local_user_2.after | length == 3 + - cm_merged_update_local_user_2.after.0.email == "secondansibleuser@example.com" + - cm_merged_update_local_user_2.after.0.first_name == "Second Ansible first name" + - cm_merged_update_local_user_2.after.0.last_name == "Second Ansible last name" + - cm_merged_update_local_user_2.after.0.login_id == "ansible_local_user_2" + - cm_merged_update_local_user_2.after.0.remote_id_claim == "ansible_remote_user_2" + - cm_merged_update_local_user_2.after.0.remote_user_authorization == true + - cm_merged_update_local_user_2.after.0.reuse_limitation == 20 + - cm_merged_update_local_user_2.after.0.security_domains | length == 1 + - cm_merged_update_local_user_2.after.0.security_domains.0.name == "all" + - cm_merged_update_local_user_2.after.0.security_domains.0.roles | length == 1 + - cm_merged_update_local_user_2.after.0.security_domains.0.roles.0 == "fabric_admin" + - cm_merged_update_local_user_2.after.0.time_interval_limitation == 10 + - cm_merged_update_local_user_2.after.1.email == "updatedansibleuser@example.com" + - cm_merged_update_local_user_2.after.1.first_name == "Updated Ansible first name" + - cm_merged_update_local_user_2.after.1.last_name == "Updated Ansible last name" + - cm_merged_update_local_user_2.after.1.login_id == "ansible_local_user" + - cm_merged_update_local_user_2.after.1.remote_user_authorization == false + - cm_merged_update_local_user_2.after.1.reuse_limitation == 25 + - cm_merged_update_local_user_2.after.1.security_domains | length == 1 + - cm_merged_update_local_user_2.after.1.security_domains.0.name == "all" + - cm_merged_update_local_user_2.after.1.security_domains.0.roles | length == 1 + - cm_merged_update_local_user_2.after.1.security_domains.0.roles.0 == "super_admin" + - cm_merged_update_local_user_2.after.1.time_interval_limitation == 15 + - cm_merged_update_local_user_2.after.2.login_id == "admin" + - cm_merged_update_local_user_2.after.2.first_name == "admin" + - cm_merged_update_local_user_2.after.2.remote_user_authorization == false + - cm_merged_update_local_user_2.after.2.reuse_limitation == 0 + - cm_merged_update_local_user_2.after.2.security_domains | length == 1 + - cm_merged_update_local_user_2.after.2.security_domains.0.name == "all" + - cm_merged_update_local_user_2.after.2.security_domains.0.roles | length == 1 + - cm_merged_update_local_user_2.after.2.security_domains.0.roles.0 == "super_admin" + - cm_merged_update_local_user_2.after.2.time_interval_limitation == 0 + - cm_merged_update_local_user_2.before | length == 3 + - cm_merged_update_local_user_2.before.2.first_name == "admin" + - cm_merged_update_local_user_2.before.2.remote_user_authorization == false + - cm_merged_update_local_user_2.before.2.reuse_limitation == 0 + - cm_merged_update_local_user_2.before.2.security_domains | length == 1 + - cm_merged_update_local_user_2.before.2.security_domains.0.name == "all" + - cm_merged_update_local_user_2.before.2.security_domains.0.roles | length == 1 + - cm_merged_update_local_user_2.before.2.security_domains.0.roles.0 == "super_admin" + - cm_merged_update_local_user_2.before.2.time_interval_limitation == 0 + - cm_merged_update_local_user_2.before.1.email == "ansibleuser@example.com" + - cm_merged_update_local_user_2.before.1.first_name == "Ansible first name" + - cm_merged_update_local_user_2.before.1.last_name == "Ansible last name" + - cm_merged_update_local_user_2.before.1.login_id == "ansible_local_user" + - cm_merged_update_local_user_2.before.1.remote_id_claim == "ansible_remote_user" + - cm_merged_update_local_user_2.before.1.remote_user_authorization == true + - cm_merged_update_local_user_2.before.1.reuse_limitation == 20 + - cm_merged_update_local_user_2.before.1.security_domains | length == 1 + - cm_merged_update_local_user_2.before.1.security_domains.0.name == "all" + - cm_merged_update_local_user_2.before.1.security_domains.0.roles | length == 2 + - cm_merged_update_local_user_2.before.1.security_domains.0.roles.0 == "observer" + - cm_merged_update_local_user_2.before.1.security_domains.0.roles.0 == "support-engineer" + - cm_merged_update_local_user_2.before.1.time_interval_limitation == 10 + - cm_merged_update_local_user_2.before.0.login_id == "ansible_local_user_2" + - cm_merged_update_local_user_2.before.0.security_domains | length == 1 + - cm_merged_update_local_user_2.before.0.security_domains.0.name == "all" + - cm_merged_update_local_user_2.proposed.0.email == "secondansibleuser@example.com" + - cm_merged_update_local_user_2.proposed.0.first_name == "Second Ansible first name" + - cm_merged_update_local_user_2.proposed.0.last_name == "Second Ansible last name" + - cm_merged_update_local_user_2.proposed.0.login_id == "ansible_local_user_2" + - cm_merged_update_local_user_2.proposed.0.remote_id_claim == "ansible_remote_user_2" + - cm_merged_update_local_user_2.proposed.0.remote_user_authorization == true + - cm_merged_update_local_user_2.proposed.0.reuse_limitation == 20 + - cm_merged_update_local_user_2.proposed.0.security_domains | length == 1 + - cm_merged_update_local_user_2.proposed.0.security_domains.0.name == "all" + - cm_merged_update_local_user_2.proposed.0.security_domains.0.roles | length == 1 + - cm_merged_update_local_user_2.proposed.0.security_domains.0.roles.0 == "fabric_admin" + - cm_merged_update_local_user_2.proposed.0.time_interval_limitation == 10 + - nm_merged_update_local_user_2 is changed + - nm_merged_update_local_user_2.after | length == 3 + - nm_merged_update_local_user_2.after.0.email == "secondansibleuser@example.com" + - nm_merged_update_local_user_2.after.0.first_name == "Second Ansible first name" + - nm_merged_update_local_user_2.after.0.last_name == "Second Ansible last name" + - nm_merged_update_local_user_2.after.0.login_id == "ansible_local_user_2" + - nm_merged_update_local_user_2.after.0.remote_id_claim == "ansible_remote_user_2" + - nm_merged_update_local_user_2.after.0.remote_user_authorization == true + - nm_merged_update_local_user_2.after.0.reuse_limitation == 20 + - nm_merged_update_local_user_2.after.0.security_domains | length == 1 + - nm_merged_update_local_user_2.after.0.security_domains.0.name == "all" + - nm_merged_update_local_user_2.after.0.security_domains.0.roles | length == 1 + - nm_merged_update_local_user_2.after.0.security_domains.0.roles.0 == "fabric_admin" + - nm_merged_update_local_user_2.after.0.time_interval_limitation == 10 + - nm_merged_update_local_user_2.after.1.email == "updatedansibleuser@example.com" + - nm_merged_update_local_user_2.after.1.first_name == "Updated Ansible first name" + - nm_merged_update_local_user_2.after.1.last_name == "Updated Ansible last name" + - nm_merged_update_local_user_2.after.1.login_id == "ansible_local_user" + - nm_merged_update_local_user_2.after.1.remote_user_authorization == false + - nm_merged_update_local_user_2.after.1.reuse_limitation == 25 + - nm_merged_update_local_user_2.after.1.security_domains | length == 1 + - nm_merged_update_local_user_2.after.1.security_domains.0.name == "all" + - nm_merged_update_local_user_2.after.1.security_domains.0.roles | length == 1 + - nm_merged_update_local_user_2.after.1.security_domains.0.roles.0 == "super_admin" + - nm_merged_update_local_user_2.after.1.time_interval_limitation == 15 + - nm_merged_update_local_user_2.after.2.login_id == "admin" + - nm_merged_update_local_user_2.after.2.first_name == "admin" + - nm_merged_update_local_user_2.after.2.remote_user_authorization == false + - nm_merged_update_local_user_2.after.2.reuse_limitation == 0 + - nm_merged_update_local_user_2.after.2.security_domains | length == 1 + - nm_merged_update_local_user_2.after.2.security_domains.0.name == "all" + - nm_merged_update_local_user_2.after.2.security_domains.0.roles | length == 1 + - nm_merged_update_local_user_2.after.2.security_domains.0.roles.0 == "super_admin" + - nm_merged_update_local_user_2.after.2.time_interval_limitation == 0 + - nm_merged_update_local_user_2.before | length == 3 + - nm_merged_update_local_user_2.before.2.first_name == "admin" + - nm_merged_update_local_user_2.before.2.remote_user_authorization == false + - nm_merged_update_local_user_2.before.2.reuse_limitation == 0 + - nm_merged_update_local_user_2.before.2.security_domains | length == 1 + - nm_merged_update_local_user_2.before.2.security_domains.0.name == "all" + - nm_merged_update_local_user_2.before.2.security_domains.0.roles | length == 1 + - nm_merged_update_local_user_2.before.2.security_domains.0.roles.0 == "super_admin" + - nm_merged_update_local_user_2.before.2.time_interval_limitation == 0 + - nm_merged_update_local_user_2.before.1.email == "ansibleuser@example.com" + - nm_merged_update_local_user_2.before.1.first_name == "Ansible first name" + - nm_merged_update_local_user_2.before.1.last_name == "Ansible last name" + - nm_merged_update_local_user_2.before.1.login_id == "ansible_local_user" + - nm_merged_update_local_user_2.before.1.remote_id_claim == "ansible_remote_user" + - nm_merged_update_local_user_2.before.1.remote_user_authorization == true + - nm_merged_update_local_user_2.before.1.reuse_limitation == 20 + - nm_merged_update_local_user_2.before.1.security_domains | length == 1 + - nm_merged_update_local_user_2.before.1.security_domains.0.name == "all" + - nm_merged_update_local_user_2.before.1.security_domains.0.roles | length == 2 + - nm_merged_update_local_user_2.before.1.security_domains.0.roles.0 == "observer" + - nm_merged_update_local_user_2.before.1.security_domains.0.roles.0 == "support-engineer" + - nm_merged_update_local_user_2.before.1.time_interval_limitation == 10 + - nm_merged_update_local_user_2.before.0.login_id == "ansible_local_user_2" + - nm_merged_update_local_user_2.before.0.security_domains | length == 1 + - nm_merged_update_local_user_2.before.0.security_domains.0.name == "all" + - nm_merged_update_local_user_2.proposed.0.email == "secondansibleuser@example.com" + - nm_merged_update_local_user_2.proposed.0.first_name == "Second Ansible first name" + - nm_merged_update_local_user_2.proposed.0.last_name == "Second Ansible last name" + - nm_merged_update_local_user_2.proposed.0.login_id == "ansible_local_user_2" + - nm_merged_update_local_user_2.proposed.0.remote_id_claim == "ansible_remote_user_2" + - nm_merged_update_local_user_2.proposed.0.remote_user_authorization == true + - nm_merged_update_local_user_2.proposed.0.reuse_limitation == 20 + - nm_merged_update_local_user_2.proposed.0.security_domains | length == 1 + - nm_merged_update_local_user_2.proposed.0.security_domains.0.name == "all" + - nm_merged_update_local_user_2.proposed.0.security_domains.0.roles | length == 1 + - nm_merged_update_local_user_2.proposed.0.security_domains.0.roles.0 == "fabric_admin" + - nm_merged_update_local_user_2.proposed.0.time_interval_limitation == 10 + - nm_merged_update_local_user_2_again is not changed + - nm_merged_update_local_user_2_again.after == nm_merged_update_local_user_2.after + - nm_merged_update_local_user_2_again.proposed == nm_merged_update_local_user_2.proposed + +- name: Ensure local users do not exist for next tests + cisco.nd.nd_local_user: + <<: *clean_all_local_users + +# --- REPLACED STATE TESTS --- + +# REPLACED STATE TESTS: CREATE +- name: Create local users with full and minimum configuration (replaced state - check mode) + cisco.nd.nd_local_user: &create_local_user_replaced_state + <<: *nd_info + config: + - email: ansibleuser@example.com + login_id: ansible_local_user + first_name: Ansible first name + last_name: Ansible last name + user_password: ansibleLocalUserPassword1%Test + reuse_limitation: 20 + time_interval_limitation: 10 + security_domains: + - name: all + roles: + - observer + - support_engineer + remote_id_claim: ansible_remote_user + remote_user_authorization: true + - login_id: ansible_local_user_2 + user_password: ansibleLocalUser2Password1%Test + security_domains: + - name: all + state: replaced + check_mode: true + register: cm_replaced_create_local_users + +- name: Create local users with full and minimum configuration (replaced state - normal mode) + cisco.nd.nd_local_user: + <<: *create_local_user_replaced_state + register: nm_replaced_create_local_users + +- name: Asserts for local users replaced state creation tasks + ansible.builtin.assert: + that: + - cm_replaced_create_local_users is changed + - cm_replaced_create_local_users.after | length == 3 + - cm_replaced_create_local_users.after.0.login_id == "admin" + - cm_replaced_create_local_users.after.0.first_name == "admin" + - cm_replaced_create_local_users.after.0.remote_user_authorization == false + - cm_replaced_create_local_users.after.0.reuse_limitation == 0 + - cm_replaced_create_local_users.after.0.security_domains | length == 1 + - cm_replaced_create_local_users.after.0.security_domains.0.name == "all" + - cm_replaced_create_local_users.after.0.security_domains.0.roles | length == 1 + - cm_replaced_create_local_users.after.0.security_domains.0.roles.0 == "super_admin" + - cm_replaced_create_local_users.after.0.time_interval_limitation == 0 + - cm_replaced_create_local_users.after.1.email == "ansibleuser@example.com" + - cm_replaced_create_local_users.after.1.first_name == "Ansible first name" + - cm_replaced_create_local_users.after.1.last_name == "Ansible last name" + - cm_replaced_create_local_users.after.1.login_id == "ansible_local_user" + - cm_replaced_create_local_users.after.1.remote_id_claim == "ansible_remote_user" + - cm_replaced_create_local_users.after.1.remote_user_authorization == true + - cm_replaced_create_local_users.after.1.reuse_limitation == 20 + - cm_replaced_create_local_users.after.1.security_domains | length == 1 + - cm_replaced_create_local_users.after.1.security_domains.0.name == "all" + - cm_replaced_create_local_users.after.1.security_domains.0.roles | length == 2 + - cm_replaced_create_local_users.after.1.security_domains.0.roles.0 == "observer" + - cm_replaced_create_local_users.after.1.security_domains.0.roles.1 == "support_engineer" + - cm_replaced_create_local_users.after.1.time_interval_limitation == 10 + - cm_replaced_create_local_users.after.2.login_id == "ansible_local_user_2" + - cm_replaced_create_local_users.after.2.security_domains | length == 1 + - cm_replaced_create_local_users.after.2.security_domains.0.name == "all" + - cm_replaced_create_local_users.before | length == 1 + - cm_replaced_create_local_users.before.0.login_id == "admin" + - cm_replaced_create_local_users.before.0.first_name == "admin" + - cm_replaced_create_local_users.before.0.remote_user_authorization == false + - cm_replaced_create_local_users.before.0.reuse_limitation == 0 + - cm_replaced_create_local_users.before.0.security_domains | length == 1 + - cm_replaced_create_local_users.before.0.security_domains.0.name == "all" + - cm_replaced_create_local_users.before.0.security_domains.0.roles | length == 1 + - cm_replaced_create_local_users.before.0.security_domains.0.roles.0 == "super_admin" + - cm_replaced_create_local_users.before.0.time_interval_limitation == 0 + - cm_replaced_create_local_users.proposed.0.email == "ansibleuser@example.com" + - cm_replaced_create_local_users.proposed.0.first_name == "Ansible first name" + - cm_replaced_create_local_users.proposed.0.last_name == "Ansible last name" + - cm_replaced_create_local_users.proposed.0.login_id == "ansible_local_user" + - cm_replaced_create_local_users.proposed.0.remote_id_claim == "ansible_remote_user" + - cm_replaced_create_local_users.proposed.0.remote_user_authorization == true + - cm_replaced_create_local_users.proposed.0.reuse_limitation == 20 + - cm_replaced_create_local_users.proposed.0.security_domains | length == 1 + - cm_replaced_create_local_users.proposed.0.security_domains.0.name == "all" + - cm_replaced_create_local_users.proposed.0.security_domains.0.roles | length == 2 + - cm_replaced_create_local_users.proposed.0.security_domains.0.roles.0 == "observer" + - cm_replaced_create_local_users.proposed.0.security_domains.0.roles.1 == "support_engineer" + - cm_replaced_create_local_users.proposed.0.time_interval_limitation == 10 + - cm_replaced_create_local_users.proposed.1.login_id == "ansible_local_user_2" + - cm_replaced_create_local_users.proposed.1.security_domains | length == 1 + - cm_replaced_create_local_users.proposed.1.security_domains.0.name == "all" + - nm_replaced_create_local_users is changed + - nm_replaced_create_local_users.after.0.first_name == "admin" + - nm_replaced_create_local_users.after.0.remote_user_authorization == false + - nm_replaced_create_local_users.after.0.reuse_limitation == 0 + - nm_replaced_create_local_users.after.0.security_domains | length == 1 + - nm_replaced_create_local_users.after.0.security_domains.0.name == "all" + - nm_replaced_create_local_users.after.0.security_domains.0.roles | length == 1 + - nm_replaced_create_local_users.after.0.security_domains.0.roles.0 == "super_admin" + - nm_replaced_create_local_users.after.0.time_interval_limitation == 0 + - nm_replaced_create_local_users.after.1.email == "ansibleuser@example.com" + - nm_replaced_create_local_users.after.1.first_name == "Ansible first name" + - nm_replaced_create_local_users.after.1.last_name == "Ansible last name" + - nm_replaced_create_local_users.after.1.login_id == "ansible_local_user" + - nm_replaced_create_local_users.after.1.remote_id_claim == "ansible_remote_user" + - nm_replaced_create_local_users.after.1.remote_user_authorization == true + - nm_replaced_create_local_users.after.1.reuse_limitation == 20 + - nm_replaced_create_local_users.after.1.security_domains | length == 1 + - nm_replaced_create_local_users.after.1.security_domains.0.name == "all" + - nm_replaced_create_local_users.after.1.security_domains.0.roles | length == 2 + - nm_replaced_create_local_users.after.1.security_domains.0.roles.0 == "observer" + - nm_replaced_create_local_users.after.1.security_domains.0.roles.1 == "support_engineer" + - nm_replaced_create_local_users.after.1.time_interval_limitation == 10 + - nm_replaced_create_local_users.after.2.login_id == "ansible_local_user_2" + - nm_replaced_create_local_users.after.2.security_domains | length == 1 + - nm_replaced_create_local_users.after.2.security_domains.0.name == "all" + - nm_replaced_create_local_users.before | length == 1 + - nm_replaced_create_local_users.before.0.login_id == "admin" + - nm_replaced_create_local_users.before.0.first_name == "admin" + - nm_replaced_create_local_users.before.0.remote_user_authorization == false + - nm_replaced_create_local_users.before.0.reuse_limitation == 0 + - nm_replaced_create_local_users.before.0.security_domains | length == 1 + - nm_replaced_create_local_users.before.0.security_domains.0.name == "all" + - nm_replaced_create_local_users.before.0.security_domains.0.roles | length == 1 + - nm_replaced_create_local_users.before.0.security_domains.0.roles.0 == "super_admin" + - nm_replaced_create_local_users.before.0.time_interval_limitation == 0 + - nm_replaced_create_local_users.proposed.0.email == "ansibleuser@example.com" + - nm_replaced_create_local_users.proposed.0.first_name == "Ansible first name" + - nm_replaced_create_local_users.proposed.0.last_name == "Ansible last name" + - nm_replaced_create_local_users.proposed.0.login_id == "ansible_local_user" + - nm_replaced_create_local_users.proposed.0.remote_id_claim == "ansible_remote_user" + - nm_replaced_create_local_users.proposed.0.remote_user_authorization == true + - nm_replaced_create_local_users.proposed.0.reuse_limitation == 20 + - nm_replaced_create_local_users.proposed.0.security_domains | length == 1 + - nm_replaced_create_local_users.proposed.0.security_domains.0.name == "all" + - nm_replaced_create_local_users.proposed.0.security_domains.0.roles | length == 2 + - nm_replaced_create_local_users.proposed.0.security_domains.0.roles.0 == "observer" + - nm_replaced_create_local_users.proposed.0.security_domains.0.roles.1 == "support_engineer" + - nm_replaced_create_local_users.proposed.0.time_interval_limitation == 10 + - nm_replaced_create_local_users.proposed.1.login_id == "ansible_local_user_2" + - nm_replaced_create_local_users.proposed.1.security_domains | length == 1 + - nm_replaced_create_local_users.proposed.1.security_domains.0.name == "all" + +# REPLACED STATE TESTS: UPDATE +- name: Replace all ansible_local_user's attributes (replaced state - check mode) + cisco.nd.nd_local_user: &update_first_local_user_replaced_state + <<: *nd_info + config: + - email: updatedansibleuser@example.com + login_id: ansible_local_user + first_name: Updated Ansible first name + last_name: Updated Ansible last name + user_password: updatedAnsibleLocalUserPassword1% + reuse_limitation: 25 + time_interval_limitation: 15 + security_domains: + - name: all + roles: super_admin + remote_id_claim: "" + remote_user_authorization: false + state: replaced + check_mode: true + register: cm_replace_local_user + +- name: Replace all ansible_local_user's attributes (replaced - normal mode) + cisco.nd.nd_local_user: + <<: *update_first_local_user_replaced_state + register: nm_replace_local_user + +- name: Asserts for local users replaced state update tasks + ansible.builtin.assert: + that: + - cm_replace_local_user is changed + - cm_replace_local_user.after | length == 3 + - cm_replace_local_user.after.0.login_id == "ansible_local_user_2" + - cm_replace_local_user.after.0.security_domains | length == 1 + - cm_replace_local_user.after.0.security_domains.0.name == "all" + - cm_replace_local_user.after.1.email == "updatedansibleuser@example.com" + - cm_replace_local_user.after.1.first_name == "Updated Ansible first name" + - cm_replace_local_user.after.1.last_name == "Updated Ansible last name" + - cm_replace_local_user.after.1.login_id == "ansible_local_user" + - cm_replace_local_user.after.1.remote_id_claim == "" + - cm_replace_local_user.after.1.remote_user_authorization == false + - cm_replace_local_user.after.1.reuse_limitation == 25 + - cm_replace_local_user.after.1.security_domains | length == 1 + - cm_replace_local_user.after.1.security_domains.0.name == "all" + - cm_replace_local_user.after.1.security_domains.0.roles | length == 1 + - cm_replace_local_user.after.1.security_domains.0.roles.0 == "super_admin" + - cm_replace_local_user.after.1.time_interval_limitation == 15 + - cm_replace_local_user.after.2.login_id == "admin" + - cm_replace_local_user.after.2.first_name == "admin" + - cm_replace_local_user.after.2.remote_user_authorization == false + - cm_replace_local_user.after.2.reuse_limitation == 0 + - cm_replace_local_user.after.2.security_domains | length == 1 + - cm_replace_local_user.after.2.security_domains.0.name == "all" + - cm_replace_local_user.after.2.security_domains.0.roles | length == 1 + - cm_replace_local_user.after.2.security_domains.0.roles.0 == "super_admin" + - cm_replace_local_user.after.2.time_interval_limitation == 0 + - cm_replace_local_user.before | length == 3 + - cm_replace_local_user.before.2.first_name == "admin" + - cm_replace_local_user.before.2.remote_user_authorization == false + - cm_replace_local_user.before.2.reuse_limitation == 0 + - cm_replace_local_user.before.2.security_domains | length == 1 + - cm_replace_local_user.before.2.security_domains.0.name == "all" + - cm_replace_local_user.before.2.security_domains.0.roles | length == 1 + - cm_replace_local_user.before.2.security_domains.0.roles.0 == "super_admin" + - cm_replace_local_user.before.2.time_interval_limitation == 0 + - cm_replace_local_user.before.1.email == "ansibleuser@example.com" + - cm_replace_local_user.before.1.first_name == "Ansible first name" + - cm_replace_local_user.before.1.last_name == "Ansible last name" + - cm_replace_local_user.before.1.login_id == "ansible_local_user" + - cm_replace_local_user.before.1.remote_id_claim == "ansible_remote_user" + - cm_replace_local_user.before.1.remote_user_authorization == true + - cm_replace_local_user.before.1.reuse_limitation == 20 + - cm_replace_local_user.before.1.security_domains | length == 1 + - cm_replace_local_user.before.1.security_domains.0.name == "all" + - cm_replace_local_user.before.1.security_domains.0.roles | length == 2 + - cm_replace_local_user.before.1.security_domains.0.roles.0 == "observer" + - cm_replace_local_user.before.1.security_domains.0.roles.1 == "support_engineer" + - cm_replace_local_user.before.1.time_interval_limitation == 10 + - cm_replace_local_user.before.0.login_id == "ansible_local_user_2" + - cm_replace_local_user.before.0.security_domains | length == 1 + - cm_replace_local_user.before.0.security_domains.0.name == "all" + - cm_replace_local_user.proposed.0.email == "updatedansibleuser@example.com" + - cm_replace_local_user.proposed.0.first_name == "Updated Ansible first name" + - cm_replace_local_user.proposed.0.last_name == "Updated Ansible last name" + - cm_replace_local_user.proposed.0.login_id == "ansible_local_user" + - cm_replace_local_user.proposed.0.remote_id_claim == "" + - cm_replace_local_user.proposed.0.remote_user_authorization == false + - cm_replace_local_user.proposed.0.reuse_limitation == 25 + - cm_replace_local_user.proposed.0.security_domains | length == 1 + - cm_replace_local_user.proposed.0.security_domains.0.name == "all" + - cm_replace_local_user.proposed.0.security_domains.0.roles | length == 1 + - cm_replace_local_user.proposed.0.security_domains.0.roles.0 == "super_admin" + - cm_replace_local_user.proposed.0.time_interval_limitation == 15 + - nm_replace_local_user is changed + - nm_replace_local_user.after | length == 3 + - nm_replace_local_user.after.0.login_id == "ansible_local_user_2" + - nm_replace_local_user.after.0.security_domains | length == 1 + - nm_replace_local_user.after.0.security_domains.0.name == "all" + - nm_replace_local_user.after.1.email == "updatedansibleuser@example.com" + - nm_replace_local_user.after.1.first_name == "Updated Ansible first name" + - nm_replace_local_user.after.1.last_name == "Updated Ansible last name" + - nm_replace_local_user.after.1.login_id == "ansible_local_user" + - nm_replace_local_user.after.1.remote_id_claim == "" + - nm_replace_local_user.after.1.remote_user_authorization == false + - nm_replace_local_user.after.1.reuse_limitation == 25 + - nm_replace_local_user.after.1.security_domains | length == 1 + - nm_replace_local_user.after.1.security_domains.0.name == "all" + - nm_replace_local_user.after.1.security_domains.0.roles | length == 1 + - nm_replace_local_user.after.1.security_domains.0.roles.0 == "super_admin" + - nm_replace_local_user.after.1.time_interval_limitation == 15 + - nm_replace_local_user.after.2.login_id == "admin" + - nm_replace_local_user.after.2.first_name == "admin" + - nm_replace_local_user.after.2.remote_user_authorization == false + - nm_replace_local_user.after.2.reuse_limitation == 0 + - nm_replace_local_user.after.2.security_domains | length == 1 + - nm_replace_local_user.after.2.security_domains.0.name == "all" + - nm_replace_local_user.after.2.security_domains.0.roles | length == 1 + - nm_replace_local_user.after.2.security_domains.0.roles.0 == "super_admin" + - nm_replace_local_user.after.2.time_interval_limitation == 0 + - nm_replace_local_user.before | length == 3 + - nm_replace_local_user.before.2.first_name == "admin" + - nm_replace_local_user.before.2.remote_user_authorization == false + - nm_replace_local_user.before.2.reuse_limitation == 0 + - nm_replace_local_user.before.2.security_domains | length == 1 + - nm_replace_local_user.before.2.security_domains.0.name == "all" + - nm_replace_local_user.before.2.security_domains.0.roles | length == 1 + - nm_replace_local_user.before.2.security_domains.0.roles.0 == "super_admin" + - nm_replace_local_user.before.2.time_interval_limitation == 0 + - nm_replace_local_user.before.1.email == "ansibleuser@example.com" + - nm_replace_local_user.before.1.first_name == "Ansible first name" + - nm_replace_local_user.before.1.last_name == "Ansible last name" + - nm_replace_local_user.before.1.login_id == "ansible_local_user" + - nm_replace_local_user.before.1.remote_id_claim == "ansible_remote_user" + - nm_replace_local_user.before.1.remote_user_authorization == true + - nm_replace_local_user.before.1.reuse_limitation == 20 + - nm_replace_local_user.before.1.security_domains | length == 1 + - nm_replace_local_user.before.1.security_domains.0.name == "all" + - nm_replace_local_user.before.1.security_domains.0.roles | length == 2 + - nm_replace_local_user.before.1.security_domains.0.roles.0 == "observer" + - nm_replace_local_user.before.1.security_domains.0.roles.1 == "support_engineer" + - nm_replace_local_user.before.1.time_interval_limitation == 10 + - nm_replace_local_user.before.0.login_id == "ansible_local_user_2" + - nm_replace_local_user.before.0.security_domains | length == 1 + - nm_replace_local_user.before.0.security_domains.0.name == "all" + - nm_replace_local_user.proposed.0.email == "updatedansibleuser@example.com" + - nm_replace_local_user.proposed.0.first_name == "Updated Ansible first name" + - nm_replace_local_user.proposed.0.last_name == "Updated Ansible last name" + - nm_replace_local_user.proposed.0.login_id == "ansible_local_user" + - nm_replace_local_user.proposed.0.remote_id_claim == "" + - nm_replace_local_user.proposed.0.remote_user_authorization == false + - nm_replace_local_user.proposed.0.reuse_limitation == 25 + - nm_replace_local_user.proposed.0.security_domains | length == 1 + - nm_replace_local_user.proposed.0.security_domains.0.name == "all" + - nm_replace_local_user.proposed.0.security_domains.0.roles | length == 1 + - nm_replace_local_user.proposed.0.security_domains.0.roles.0 == "super_admin" + - nm_replace_local_user.proposed.0.time_interval_limitation == 15 + +- name: Ensure local users do not exist for next tests + cisco.nd.nd_local_user: + <<: *clean_all_local_users + +# --- OVERRIDDEN STATE TESTS --- + +# OVERRIDDEN STATE TESTS: CREATE +- name: Create local users with full and minimum configuration (overridden state - check mode) + cisco.nd.nd_local_user: &create_local_user_overridden_state + <<: *nd_info + config: + - login_id: admin + first_name: admin + remote_user_authorization: false + reuse_limitation: 0 + time_interval_limitation: 0 + security_domains: + - name: all + roles: + - super_admin + - email: ansibleuser@example.com + login_id: ansible_local_user + first_name: Ansible first name + last_name: Ansible last name + user_password: ansibleLocalUserPassword1%Test + reuse_limitation: 20 + time_interval_limitation: 10 + security_domains: + - name: all + roles: + - observer + - support_engineer + remote_id_claim: ansible_remote_user + remote_user_authorization: true + - login_id: ansible_local_user_2 + user_password: ansibleLocalUser2Password1%Test + security_domains: + - name: all + state: merged + check_mode: true + register: cm_overridden_create_local_users + +- name: Create local users with full and minimum configuration (overridden state - normal mode) + cisco.nd.nd_local_user: + <<: *create_local_user_overridden_state + register: nm_overridden_create_local_users + +- name: Asserts for local users overridden state creation tasks + ansible.builtin.assert: + that: + - cm_overridden_create_local_users is changed + - cm_overridden_create_local_users.after | length == 3 + - cm_overridden_create_local_users.after.0.login_id == "admin" + - cm_overridden_create_local_users.after.0.first_name == "admin" + - cm_overridden_create_local_users.after.0.remote_user_authorization == false + - cm_overridden_create_local_users.after.0.reuse_limitation == 0 + - cm_overridden_create_local_users.after.0.security_domains | length == 1 + - cm_overridden_create_local_users.after.0.security_domains.0.name == "all" + - cm_overridden_create_local_users.after.0.security_domains.0.roles | length == 1 + - cm_overridden_create_local_users.after.0.security_domains.0.roles.0 == "super_admin" + - cm_overridden_create_local_users.after.0.time_interval_limitation == 0 + - cm_overridden_create_local_users.after.1.email == "ansibleuser@example.com" + - cm_overridden_create_local_users.after.1.first_name == "Ansible first name" + - cm_overridden_create_local_users.after.1.last_name == "Ansible last name" + - cm_overridden_create_local_users.after.1.login_id == "ansible_local_user" + - cm_overridden_create_local_users.after.1.remote_id_claim == "ansible_remote_user" + - cm_overridden_create_local_users.after.1.remote_user_authorization == true + - cm_overridden_create_local_users.after.1.reuse_limitation == 20 + - cm_overridden_create_local_users.after.1.security_domains | length == 1 + - cm_overridden_create_local_users.after.1.security_domains.0.name == "all" + - cm_overridden_create_local_users.after.1.security_domains.0.roles | length == 2 + - cm_overridden_create_local_users.after.1.security_domains.0.roles.0 == "observer" + - cm_overridden_create_local_users.after.1.security_domains.0.roles.1 == "support_engineer" + - cm_overridden_create_local_users.after.1.time_interval_limitation == 10 + - cm_overridden_create_local_users.after.2.login_id == "ansible_local_user_2" + - cm_overridden_create_local_users.after.2.security_domains | length == 1 + - cm_overridden_create_local_users.after.2.security_domains.0.name == "all" + - cm_overridden_create_local_users.before | length == 1 + - cm_overridden_create_local_users.before.0.login_id == "admin" + - cm_overridden_create_local_users.before.0.first_name == "admin" + - cm_overridden_create_local_users.before.0.remote_user_authorization == false + - cm_overridden_create_local_users.before.0.reuse_limitation == 0 + - cm_overridden_create_local_users.before.0.security_domains | length == 1 + - cm_overridden_create_local_users.before.0.security_domains.0.name == "all" + - cm_overridden_create_local_users.before.0.security_domains.0.roles | length == 1 + - cm_overridden_create_local_users.before.0.security_domains.0.roles.0 == "super_admin" + - cm_overridden_create_local_users.before.0.time_interval_limitation == 0 + - cm_overridden_create_local_users.proposed.0.email == "ansibleuser@example.com" + - cm_overridden_create_local_users.proposed.0.first_name == "Ansible first name" + - cm_overridden_create_local_users.proposed.0.last_name == "Ansible last name" + - cm_overridden_create_local_users.proposed.0.login_id == "ansible_local_user" + - cm_overridden_create_local_users.proposed.0.remote_id_claim == "ansible_remote_user" + - cm_overridden_create_local_users.proposed.0.remote_user_authorization == true + - cm_overridden_create_local_users.proposed.0.reuse_limitation == 20 + - cm_overridden_create_local_users.proposed.0.security_domains | length == 1 + - cm_overridden_create_local_users.proposed.0.security_domains.0.name == "all" + - cm_overridden_create_local_users.proposed.0.security_domains.0.roles | length == 2 + - cm_overridden_create_local_users.proposed.0.security_domains.0.roles.0 == "observer" + - cm_overridden_create_local_users.proposed.0.security_domains.0.roles.1 == "support_engineer" + - cm_overridden_create_local_users.proposed.0.time_interval_limitation == 10 + - cm_overridden_create_local_users.proposed.1.login_id == "ansible_local_user_2" + - cm_overridden_create_local_users.proposed.1.security_domains | length == 1 + - cm_overridden_create_local_users.proposed.1.security_domains.0.name == "all" + - nm_overridden_create_local_users is changed + - nm_overridden_create_local_users.after.0.first_name == "admin" + - nm_overridden_create_local_users.after.0.remote_user_authorization == false + - nm_overridden_create_local_users.after.0.reuse_limitation == 0 + - nm_overridden_create_local_users.after.0.security_domains | length == 1 + - nm_overridden_create_local_users.after.0.security_domains.0.name == "all" + - nm_overridden_create_local_users.after.0.security_domains.0.roles | length == 1 + - nm_overridden_create_local_users.after.0.security_domains.0.roles.0 == "super_admin" + - nm_overridden_create_local_users.after.0.time_interval_limitation == 0 + - nm_overridden_create_local_users.after.1.email == "ansibleuser@example.com" + - nm_overridden_create_local_users.after.1.first_name == "Ansible first name" + - nm_overridden_create_local_users.after.1.last_name == "Ansible last name" + - nm_overridden_create_local_users.after.1.login_id == "ansible_local_user" + - nm_overridden_create_local_users.after.1.remote_id_claim == "ansible_remote_user" + - nm_overridden_create_local_users.after.1.remote_user_authorization == true + - nm_overridden_create_local_users.after.1.reuse_limitation == 20 + - nm_overridden_create_local_users.after.1.security_domains | length == 1 + - nm_overridden_create_local_users.after.1.security_domains.0.name == "all" + - nm_overridden_create_local_users.after.1.security_domains.0.roles | length == 2 + - nm_overridden_create_local_users.after.1.security_domains.0.roles.0 == "observer" + - nm_overridden_create_local_users.after.1.security_domains.0.roles.1 == "support_engineer" + - nm_overridden_create_local_users.after.1.time_interval_limitation == 10 + - nm_overridden_create_local_users.after.2.login_id == "ansible_local_user_2" + - nm_overridden_create_local_users.after.2.security_domains | length == 1 + - nm_overridden_create_local_users.after.2.security_domains.0.name == "all" + - nm_overridden_create_local_users.before | length == 1 + - nm_overridden_create_local_users.before.0.login_id == "admin" + - nm_overridden_create_local_users.before.0.first_name == "admin" + - nm_overridden_create_local_users.before.0.remote_user_authorization == false + - nm_overridden_create_local_users.before.0.reuse_limitation == 0 + - nm_overridden_create_local_users.before.0.security_domains | length == 1 + - nm_overridden_create_local_users.before.0.security_domains.0.name == "all" + - nm_overridden_create_local_users.before.0.security_domains.0.roles | length == 1 + - nm_overridden_create_local_users.before.0.security_domains.0.roles.0 == "super_admin" + - nm_overridden_create_local_users.before.0.time_interval_limitation == 0 + - nm_overridden_create_local_users.proposed.0.email == "ansibleuser@example.com" + - nm_overridden_create_local_users.proposed.0.first_name == "Ansible first name" + - nm_overridden_create_local_users.proposed.0.last_name == "Ansible last name" + - nm_overridden_create_local_users.proposed.0.login_id == "ansible_local_user" + - nm_overridden_create_local_users.proposed.0.remote_id_claim == "ansible_remote_user" + - nm_overridden_create_local_users.proposed.0.remote_user_authorization == true + - nm_overridden_create_local_users.proposed.0.reuse_limitation == 20 + - nm_overridden_create_local_users.proposed.0.security_domains | length == 1 + - nm_overridden_create_local_users.proposed.0.security_domains.0.name == "all" + - nm_overridden_create_local_users.proposed.0.security_domains.0.roles | length == 2 + - nm_overridden_create_local_users.proposed.0.security_domains.0.roles.0 == "observer" + - nm_overridden_create_local_users.proposed.0.security_domains.0.roles.1 == "support_engineer" + - nm_overridden_create_local_users.proposed.0.time_interval_limitation == 10 + - nm_overridden_create_local_users.proposed.1.login_id == "ansible_local_user_2" + - nm_overridden_create_local_users.proposed.1.security_domains | length == 1 + - nm_overridden_create_local_users.proposed.1.security_domains.0.name == "all" + +# OVERRIDDEN STATE TESTS: UPDATE +- name: Override local users with minimum configuration (overridden state - check mode) + cisco.nd.nd_local_user: &update_all_local_users_overridden_state + <<: *nd_info + config: + - email: overrideansibleuser@example.com + login_id: ansible_local_user + first_name: Overridden Ansible first name + last_name: Overridden Ansible last name + user_password: overideansibleLocalUserPassword1% + reuse_limitation: 15 + time_interval_limitation: 5 + security_domains: + - name: all + roles: + - observer + remote_id_claim: ansible_remote_user + remote_user_authorization: true + - login_id: admin + first_name: admin + remote_user_authorization: false + reuse_limitation: 0 + time_interval_limitation: 0 + security_domains: + - name: all + roles: + - super_admin + - login_id: ansible_local_user_3 + user_password: ansibleLocalUser3Password1%Test + security_domains: + - name: all + state: overridden + check_mode: true + register: cm_override_local_users + +- name: Override local users with minimum configuration (overridden state - normal mode) + cisco.nd.nd_local_user: + <<: *update_all_local_users_overridden_state + register: nm_override_local_users + +- name: Asserts for local users overridden state update tasks + ansible.builtin.assert: + that: + - cm_override_local_users is changed + - cm_override_local_users.after | length == 3 + - cm_override_local_users.after.0.email == "overrideansibleuser@example.com" + - cm_override_local_users.after.0.first_name == "Overridden Ansible first name" + - cm_override_local_users.after.0.last_name == "Overridden Ansible last name" + - cm_override_local_users.after.0.login_id == "ansible_local_user" + - cm_override_local_users.after.0.remote_id_claim == "ansible_remote_user" + - cm_override_local_users.after.0.remote_user_authorization == true + - cm_override_local_users.after.0.reuse_limitation == 15 + - cm_override_local_users.after.0.security_domains | length == 1 + - cm_override_local_users.after.0.security_domains.0.name == "all" + - cm_override_local_users.after.0.security_domains.0.roles | length == 1 + - cm_override_local_users.after.0.security_domains.0.roles.0 == "observer" + - cm_override_local_users.after.0.time_interval_limitation == 5 + - cm_override_local_users.after.1.login_id == "admin" + - cm_override_local_users.after.1.first_name == "admin" + - cm_override_local_users.after.1.remote_user_authorization == false + - cm_override_local_users.after.1.reuse_limitation == 0 + - cm_override_local_users.after.1.security_domains | length == 1 + - cm_override_local_users.after.1.security_domains.0.name == "all" + - cm_override_local_users.after.1.security_domains.0.roles | length == 1 + - cm_override_local_users.after.1.security_domains.0.roles.0 == "super_admin" + - cm_override_local_users.after.1.time_interval_limitation == 0 + - cm_override_local_users.after.2.login_id == "ansible_local_user_3" + - cm_override_local_users.after.2.security_domains.0.name == "all" + - cm_override_local_users.before | length == 3 + - cm_override_local_users.before.2.first_name == "admin" + - cm_override_local_users.before.2.remote_user_authorization == false + - cm_override_local_users.before.2.reuse_limitation == 0 + - cm_override_local_users.before.2.security_domains | length == 1 + - cm_override_local_users.before.2.security_domains.0.name == "all" + - cm_override_local_users.before.2.security_domains.0.roles | length == 1 + - cm_override_local_users.before.2.security_domains.0.roles.0 == "super_admin" + - cm_override_local_users.before.2.time_interval_limitation == 0 + - cm_override_local_users.before.1.email == "updatedansibleuser@example.com" + - cm_override_local_users.before.1.first_name == "Updated Ansible first name" + - cm_override_local_users.before.1.last_name == "Updated Ansible last name" + - cm_override_local_users.before.1.login_id == "ansible_local_user" + - cm_override_local_users.before.1.remote_user_authorization == false + - cm_override_local_users.before.1.reuse_limitation == 25 + - cm_override_local_users.before.1.security_domains | length == 1 + - cm_override_local_users.before.1.security_domains.0.name == "all" + - cm_override_local_users.before.1.security_domains.0.roles | length == 1 + - cm_override_local_users.before.1.security_domains.0.roles.0 == "super_admin" + - cm_override_local_users.before.1.time_interval_limitation == 15 + - cm_override_local_users.before.0.email == "secondansibleuser@example.com" + - cm_override_local_users.before.0.first_name == "Second Ansible first name" + - cm_override_local_users.before.0.last_name == "Second Ansible last name" + - cm_override_local_users.before.0.login_id == "ansible_local_user_2" + - cm_override_local_users.before.0.remote_id_claim == "ansible_remote_user_2" + - cm_override_local_users.before.0.remote_user_authorization == true + - cm_override_local_users.before.0.reuse_limitation == 20 + - cm_override_local_users.before.0.security_domains | length == 1 + - cm_override_local_users.before.0.security_domains.0.name == "all" + - cm_override_local_users.before.0.security_domains.0.roles | length == 1 + - cm_override_local_users.before.0.security_domains.0.roles.0 == "fabric_admin" + - cm_override_local_users.before.0.time_interval_limitation == 10 + - cm_override_local_users.proposed.0.email == "overrideansibleuser@example.com" + - cm_override_local_users.proposed.0.first_name == "Overridden Ansible first name" + - cm_override_local_users.proposed.0.last_name == "Overridden Ansible last name" + - cm_override_local_users.proposed.0.login_id == "ansible_local_user" + - cm_override_local_users.proposed.0.remote_id_claim == "ansible_remote_user" + - cm_override_local_users.proposed.0.remote_user_authorization == true + - cm_override_local_users.proposed.0.reuse_limitation == 15 + - cm_override_local_users.proposed.0.security_domains | length == 1 + - cm_override_local_users.proposed.0.security_domains.0.name == "all" + - cm_override_local_users.proposed.0.security_domains.0.roles | length == 1 + - cm_override_local_users.proposed.0.security_domains.0.roles.0 == "observer" + - cm_override_local_users.proposed.0.time_interval_limitation == 5 + - cm_override_local_users.proposed.1.login_id == "admin" + - cm_override_local_users.proposed.1.first_name == "admin" + - cm_override_local_users.proposed.1.remote_user_authorization == false + - cm_override_local_users.proposed.1.reuse_limitation == 0 + - cm_override_local_users.proposed.1.security_domains | length == 1 + - cm_override_local_users.proposed.1.security_domains.0.name == "all" + - cm_override_local_users.proposed.1.security_domains.0.roles | length == 1 + - cm_override_local_users.proposed.1.security_domains.0.roles.0 == "super_admin" + - cm_override_local_users.proposed.1.time_interval_limitation == 0 + - cm_override_local_users.proposed.2.login_id == "ansible_local_user_3" + - cm_override_local_users.proposed.2.security_domains.0.name == "all" + - cm_override_local_users is changed + - cm_override_local_users.after | length == 3 + - cm_override_local_users.after.0.email == "overrideansibleuser@example.com" + - cm_override_local_users.after.0.first_name == "Overridden Ansible first name" + - cm_override_local_users.after.0.last_name == "Overridden Ansible last name" + - cm_override_local_users.after.0.login_id == "ansible_local_user" + - cm_override_local_users.after.0.remote_id_claim == "ansible_remote_user" + - cm_override_local_users.after.0.remote_user_authorization == true + - cm_override_local_users.after.0.reuse_limitation == 15 + - cm_override_local_users.after.0.security_domains | length == 1 + - cm_override_local_users.after.0.security_domains.0.name == "all" + - cm_override_local_users.after.0.security_domains.0.roles | length == 1 + - cm_override_local_users.after.0.security_domains.0.roles.0 == "observer" + - cm_override_local_users.after.0.time_interval_limitation == 5 + - cm_override_local_users.after.1.login_id == "admin" + - cm_override_local_users.after.1.first_name == "admin" + - cm_override_local_users.after.1.remote_user_authorization == false + - cm_override_local_users.after.1.reuse_limitation == 0 + - cm_override_local_users.after.1.security_domains | length == 1 + - cm_override_local_users.after.1.security_domains.0.name == "all" + - cm_override_local_users.after.1.security_domains.0.roles | length == 1 + - cm_override_local_users.after.1.security_domains.0.roles.0 == "super_admin" + - cm_override_local_users.after.1.time_interval_limitation == 0 + - cm_override_local_users.after.2.login_id == "ansible_local_user_3" + - cm_override_local_users.after.2.security_domains.0.name == "all" + - cm_override_local_users.before | length == 3 + - cm_override_local_users.before.2.first_name == "admin" + - cm_override_local_users.before.2.remote_user_authorization == false + - cm_override_local_users.before.2.reuse_limitation == 0 + - cm_override_local_users.before.2.security_domains | length == 1 + - cm_override_local_users.before.2.security_domains.0.name == "all" + - cm_override_local_users.before.2.security_domains.0.roles | length == 1 + - cm_override_local_users.before.2.security_domains.0.roles.0 == "super_admin" + - cm_override_local_users.before.2.time_interval_limitation == 0 + - cm_override_local_users.before.1.email == "updatedansibleuser@example.com" + - cm_override_local_users.before.1.first_name == "Updated Ansible first name" + - cm_override_local_users.before.1.last_name == "Updated Ansible last name" + - cm_override_local_users.before.1.login_id == "ansible_local_user" + - cm_override_local_users.before.1.remote_user_authorization == false + - cm_override_local_users.before.1.reuse_limitation == 25 + - cm_override_local_users.before.1.security_domains | length == 1 + - cm_override_local_users.before.1.security_domains.0.name == "all" + - cm_override_local_users.before.1.security_domains.0.roles | length == 1 + - cm_override_local_users.before.1.security_domains.0.roles.0 == "super_admin" + - cm_override_local_users.before.1.time_interval_limitation == 15 + - cm_override_local_users.before.0.email == "secondansibleuser@example.com" + - cm_override_local_users.before.0.first_name == "Second Ansible first name" + - cm_override_local_users.before.0.last_name == "Second Ansible last name" + - cm_override_local_users.before.0.login_id == "ansible_local_user_2" + - cm_override_local_users.before.0.remote_id_claim == "ansible_remote_user_2" + - cm_override_local_users.before.0.remote_user_authorization == true + - cm_override_local_users.before.0.reuse_limitation == 20 + - cm_override_local_users.before.0.security_domains | length == 1 + - cm_override_local_users.before.0.security_domains.0.name == "all" + - cm_override_local_users.before.0.security_domains.0.roles | length == 1 + - cm_override_local_users.before.0.security_domains.0.roles.0 == "fabric_admin" + - cm_override_local_users.before.0.time_interval_limitation == 10 + - cm_override_local_users.proposed.0.email == "overrideansibleuser@example.com" + - cm_override_local_users.proposed.0.first_name == "Overridden Ansible first name" + - cm_override_local_users.proposed.0.last_name == "Overridden Ansible last name" + - cm_override_local_users.proposed.0.login_id == "ansible_local_user" + - cm_override_local_users.proposed.0.remote_id_claim == "ansible_remote_user" + - cm_override_local_users.proposed.0.remote_user_authorization == true + - cm_override_local_users.proposed.0.reuse_limitation == 15 + - cm_override_local_users.proposed.0.security_domains | length == 1 + - cm_override_local_users.proposed.0.security_domains.0.name == "all" + - cm_override_local_users.proposed.0.security_domains.0.roles | length == 1 + - cm_override_local_users.proposed.0.security_domains.0.roles.0 == "observer" + - cm_override_local_users.proposed.0.time_interval_limitation == 5 + - cm_override_local_users.proposed.1.login_id == "admin" + - cm_override_local_users.proposed.1.first_name == "admin" + - cm_override_local_users.proposed.1.remote_user_authorization == false + - cm_override_local_users.proposed.1.reuse_limitation == 0 + - cm_override_local_users.proposed.1.security_domains | length == 1 + - cm_override_local_users.proposed.1.security_domains.0.name == "all" + - cm_override_local_users.proposed.1.security_domains.0.roles | length == 1 + - cm_override_local_users.proposed.1.security_domains.0.roles.0 == "super_admin" + - cm_override_local_users.proposed.1.time_interval_limitation == 0 + - cm_override_local_users.proposed.2.login_id == "ansible_local_user_3" + - cm_override_local_users.proposed.2.security_domains.0.name == "all" + +# --- DELETED STATE TESTS --- + +- name: Delete local user (check mode) + cisco.nd.nd_local_user: &delete_local_user + <<: *nd_info + config: + - login_id: ansible_local_user + state: deleted + check_mode: true + register: cm_delete_local_user + +- name: Delete local user (normal mode) + cisco.nd.nd_local_user: + <<: *delete_local_user + register: nm_delete_local_user + +- name: Delete local user again (idempotency test) + cisco.nd.nd_local_user: + <<: *delete_local_user + register: nm_delete_local_user_again + +- name: Asserts for local users deletion tasks + ansible.builtin.assert: + that: + - cm_delete_local_user is changed + - cm_delete_local_user.after | length == 2 + - cm_delete_local_user.after.0.login_id == "ansible_local_user_3" + - cm_delete_local_user.after.0.security_domains.0.name == "all" + - cm_delete_local_user.after.1.login_id == "admin" + - cm_delete_local_user.after.1.first_name == "admin" + - cm_delete_local_user.after.1.remote_user_authorization == false + - cm_delete_local_user.after.1.reuse_limitation == 0 + - cm_delete_local_user.after.1.security_domains | length == 1 + - cm_delete_local_user.after.1.security_domains.0.name == "all" + - cm_delete_local_user.after.1.security_domains.0.roles | length == 1 + - cm_delete_local_user.after.1.security_domains.0.roles.0 == "super_admin" + - cm_delete_local_user.after.1.time_interval_limitation == 0 + - cm_delete_local_user.before | length == 3 + - cm_delete_local_user.before.0.email == "overrideansibleuser@example.com" + - cm_delete_local_user.before.0.first_name == "Overridden Ansible first name" + - cm_delete_local_user.before.0.last_name == "Overridden Ansible last name" + - cm_delete_local_user.before.0.login_id == "ansible_local_user" + - cm_delete_local_user.before.0.remote_id_claim == "ansible_remote_user" + - cm_delete_local_user.before.0.remote_user_authorization == true + - cm_delete_local_user.before.0.reuse_limitation == 15 + - cm_delete_local_user.before.0.security_domains | length == 1 + - cm_delete_local_user.before.0.security_domains.0.name == "all" + - cm_delete_local_user.before.0.security_domains.0.roles | length == 1 + - cm_delete_local_user.before.0.security_domains.0.roles.0 == "observer" + - cm_delete_local_user.before.0.time_interval_limitation == 5 + - cm_delete_local_user.before.1.login_id == "ansible_local_user_3" + - cm_delete_local_user.before.1.security_domains.0.name == "all" + - cm_delete_local_user.before.2.first_name == "admin" + - cm_delete_local_user.before.2.remote_user_authorization == false + - cm_delete_local_user.before.2.reuse_limitation == 0 + - cm_delete_local_user.before.2.security_domains | length == 1 + - cm_delete_local_user.before.2.security_domains.0.name == "all" + - cm_delete_local_user.before.2.security_domains.0.roles | length == 1 + - cm_delete_local_user.before.2.security_domains.0.roles.0 == "super_admin" + - cm_delete_local_user.before.2.time_interval_limitation == 0 + - cm_delete_local_user.proposed.0.login_id == "ansible_local_user" + - nm_delete_local_user is changed + - nm_delete_local_user.after | length == 2 + - nm_delete_local_user.after.0.login_id == "ansible_local_user_3" + - nm_delete_local_user.after.0.security_domains.0.name == "all" + - nm_delete_local_user.after.1.login_id == "admin" + - nm_delete_local_user.after.1.first_name == "admin" + - nm_delete_local_user.after.1.remote_user_authorization == false + - nm_delete_local_user.after.1.reuse_limitation == 0 + - nm_delete_local_user.after.1.security_domains | length == 1 + - nm_delete_local_user.after.1.security_domains.0.name == "all" + - nm_delete_local_user.after.1.security_domains.0.roles | length == 1 + - nm_delete_local_user.after.1.security_domains.0.roles.0 == "super_admin" + - nm_delete_local_user.after.1.time_interval_limitation == 0 + - nm_delete_local_user.before | length == 3 + - nm_delete_local_user.before.0.email == "overrideansibleuser@example.com" + - nm_delete_local_user.before.0.first_name == "Overridden Ansible first name" + - nm_delete_local_user.before.0.last_name == "Overridden Ansible last name" + - nm_delete_local_user.before.0.login_id == "ansible_local_user" + - nm_delete_local_user.before.0.remote_id_claim == "ansible_remote_user" + - nm_delete_local_user.before.0.remote_user_authorization == true + - nm_delete_local_user.before.0.reuse_limitation == 15 + - nm_delete_local_user.before.0.security_domains | length == 1 + - nm_delete_local_user.before.0.security_domains.0.name == "all" + - nm_delete_local_user.before.0.security_domains.0.roles | length == 1 + - nm_delete_local_user.before.0.security_domains.0.roles.0 == "observer" + - nm_delete_local_user.before.0.time_interval_limitation == 5 + - nm_delete_local_user.before.1.login_id == "ansible_local_user_3" + - nm_delete_local_user.before.1.security_domains.0.name == "all" + - nm_delete_local_user.before.2.first_name == "admin" + - nm_delete_local_user.before.2.remote_user_authorization == false + - nm_delete_local_user.before.2.reuse_limitation == 0 + - nm_delete_local_user.before.2.security_domains | length == 1 + - nm_delete_local_user.before.2.security_domains.0.name == "all" + - nm_delete_local_user.before.2.security_domains.0.roles | length == 1 + - nm_delete_local_user.before.2.security_domains.0.roles.0 == "super_admin" + - nm_delete_local_user.before.2.time_interval_limitation == 0 + - nm_delete_local_user.proposed.0.login_id == "ansible_local_user" + - nm_delete_local_user_again is not changed + - nm_delete_local_user_again.after == nm_delete_local_user.after + - nm_delete_local_user_again.before == nm_delete_local_user.after + - nm_delete_local_user_again.proposed == nm_delete_local_user.proposed + +# --- CLEAN UP --- + +- name: Ensure local users do not exist + cisco.nd.nd_local_user: + <<: *clean_all_local_users diff --git a/tests/integration/targets/nd_manage_fabric/tasks/fabric_ebgp.yaml b/tests/integration/targets/nd_manage_fabric/tasks/fabric_ebgp.yaml new file mode 100644 index 00000000..f8cf517e --- /dev/null +++ b/tests/integration/targets/nd_manage_fabric/tasks/fabric_ebgp.yaml @@ -0,0 +1,1209 @@ +--- +# Test code for the ND modules +# Copyright: (c) 2026, Mike Wiebe (@mwiebe) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +- name: Test that we have a Nexus Dashboard host, username and password + ansible.builtin.fail: + msg: 'Please define the following variables: ansible_host, ansible_user and ansible_password.' + when: ansible_host is not defined or ansible_user is not defined or ansible_password is not defined + +############################################################################# +# CLEANUP - Ensure clean state before tests +############################################################################# +- name: Clean up any existing test fabrics before starting tests + cisco.nd.nd_manage_fabric_ebgp: + state: deleted + config: + - name: "{{ ebgp_test_fabric_merged }}" + - name: "{{ ebgp_test_fabric_replaced }}" + - name: "{{ ebgp_test_fabric_deleted }}" + tags: always + +############################################################################# +# TEST 1: STATE MERGED - Create fabric using merged state +############################################################################# +- name: "TEST 1a: Create eBGP fabric using state merged (first run)" + cisco.nd.nd_manage_fabric_ebgp: + state: merged + config: + - "{{ {'name': ebgp_test_fabric_merged} | combine(common_ebgp_fabric_config) }}" + register: ebgp_merged_result_1 + tags: [test_merged, test_merged_create] + +- name: "TEST 1a: Verify eBGP fabric was created using merged state" + assert: + that: + - ebgp_merged_result_1 is changed + - ebgp_merged_result_1 is not failed + fail_msg: "eBGP fabric creation with state merged failed" + success_msg: "eBGP fabric successfully created with state merged" + tags: [test_merged, test_merged_create] + +- name: "TEST 1b: Create eBGP fabric using state merged (second run - idempotency test)" + cisco.nd.nd_manage_fabric_ebgp: + state: merged + config: + - "{{ {'name': ebgp_test_fabric_merged} | combine(common_ebgp_fabric_config) }}" + register: ebgp_merged_result_2 + tags: [test_merged, test_merged_idempotent] + +- name: "TEST 1b: Verify merged state is idempotent" + assert: + that: + - ebgp_merged_result_2 is not changed + - ebgp_merged_result_2 is not failed + fail_msg: "Merged state is not idempotent - should not change when run twice with same config" + success_msg: "Merged state is idempotent - no changes on second run" + tags: [test_merged, test_merged_idempotent] + +- name: "TEST 1c: Update eBGP fabric using state merged (modify existing)" + cisco.nd.nd_manage_fabric_ebgp: + state: merged + config: + - name: "{{ ebgp_test_fabric_merged }}" + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanEbgp + bgp_asn: "65002" # Changed from 65001 + bgp_asn_auto_allocation: false + site_id: "65002" # Changed from 65001 + bgp_as_mode: multiAS + bgp_allow_as_in_num: 1 + bgp_max_path: 4 + auto_configure_ebgp_evpn_peering: true + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00bb" # Changed from 00aa + performance_monitoring: true # Changed from false + replication_mode: multicast + multicast_group_subnet: "239.1.1.0/25" + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 2 + rendezvous_point_loopback_id: 254 + vpc_peer_link_vlan: "3600" + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: management + vpc_auto_recovery_timer: 360 + vpc_delay_restore_timer: 150 + vpc_peer_link_port_channel_id: "500" + advertise_physical_ip: false + vpc_domain_id_range: "1-1000" + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9216 + l2_host_interface_mtu: 9216 + tenant_dhcp: true + nxapi: false + nxapi_https_port: 443 + nxapi_http: false + nxapi_http_port: 80 + snmp_trap: true + anycast_border_gateway_advertise_physical_ip: false + greenfield_debug_flag: disable + tcam_allocation: true + real_time_interface_statistics_collection: false + interface_statistics_load_interval: 10 + bgp_loopback_ip_range: "10.2.0.0/22" + nve_loopback_ip_range: "10.3.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.254.0/24" + intra_fabric_subnet_range: "10.4.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.33.0.0/16" + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.5.0.0/22" + banner: "" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + register: ebgp_merged_result_3 + tags: [test_merged, test_merged_update] + +- name: "TEST 1c: Verify eBGP fabric was updated using merged state" + assert: + that: + - ebgp_merged_result_3 is changed + - ebgp_merged_result_3 is not failed + fail_msg: "eBGP fabric update with state merged failed" + success_msg: "eBGP fabric successfully updated with state merged" + tags: [test_merged, test_merged_update] + +############################################################################# +# VALIDATION: Query ebgp_test_fabric_merged and validate expected changes +############################################################################# +- name: "VALIDATION 1: Authenticate with ND to get token" + ansible.builtin.uri: + url: "https://{{ ansible_host }}:{{ ansible_httpapi_port | default(443) }}/login" + method: POST + headers: + Content-Type: "application/json" + body_format: json + body: + domain: "{{ ansible_httpapi_login_domain | default('local') }}" + userName: "{{ ansible_user }}" + userPasswd: "{{ ansible_password }}" + validate_certs: false + return_content: true + status_code: + - 200 + register: nd_auth_response + tags: [test_merged, test_merged_validation] + delegate_to: localhost + +- name: "VALIDATION 1: Query ebgp_test_fabric_merged configuration from ND" + ansible.builtin.uri: + url: "https://{{ ansible_host }}:{{ ansible_httpapi_port | default(443) }}/api/v1/manage/fabrics/{{ ebgp_test_fabric_merged }}" + method: GET + headers: + Authorization: "Bearer {{ nd_auth_response.json.jwttoken }}" + Content-Type: "application/json" + validate_certs: false + return_content: true + status_code: + - 200 + - 404 + register: ebgp_merged_fabric_query + tags: [test_merged, test_merged_validation] + delegate_to: localhost + +- name: "VALIDATION 1: Parse eBGP fabric configuration response" + set_fact: + ebgp_merged_fabric_config: "{{ ebgp_merged_fabric_query.json }}" + tags: [test_merged, test_merged_validation] + +- name: "VALIDATION 1: Verify BGP ASN was updated to 65002" + assert: + that: + - ebgp_merged_fabric_config.management.bgpAsn == "65002" + fail_msg: "BGP ASN validation failed. Expected: 65002, Actual: {{ ebgp_merged_fabric_config.management.bgpAsn }}" + success_msg: "✓ BGP ASN correctly updated to 65002" + tags: [test_merged, test_merged_validation] + +- name: "VALIDATION 1: Verify Site ID was updated to 65002" + assert: + that: + - ebgp_merged_fabric_config.management.siteId == "65002" + fail_msg: "Site ID validation failed. Expected: 65002, Actual: {{ ebgp_merged_fabric_config.management.siteId }}" + success_msg: "✓ Site ID correctly updated to 65002" + tags: [test_merged, test_merged_validation] + +- name: "VALIDATION 1: Verify Anycast Gateway MAC was updated to 2020.0000.00bb" + assert: + that: + - ebgp_merged_fabric_config.management.anycastGatewayMac == "2020.0000.00bb" + fail_msg: "Anycast Gateway MAC validation failed. Expected: 2020.0000.00bb, Actual: {{ ebgp_merged_fabric_config.management.anycastGatewayMac }}" + success_msg: "✓ Anycast Gateway MAC correctly updated to 2020.0000.00bb" + tags: [test_merged, test_merged_validation] + +- name: "VALIDATION 1: Verify Performance Monitoring was enabled" + assert: + that: + - ebgp_merged_fabric_config.management.performanceMonitoring == true + fail_msg: "Performance Monitoring validation failed. Expected: true, Actual: {{ ebgp_merged_fabric_config.management.performanceMonitoring }}" + success_msg: "✓ Performance Monitoring correctly enabled" + tags: [test_merged, test_merged_validation] + +- name: "VALIDATION 1: Verify BGP AS Mode is multiAS" + assert: + that: + - ebgp_merged_fabric_config.management.bgpAsMode == "multiAS" + fail_msg: "BGP AS Mode validation failed. Expected: multiAS, Actual: {{ ebgp_merged_fabric_config.management.bgpAsMode }}" + success_msg: "✓ BGP AS Mode correctly set to multiAS" + tags: [test_merged, test_merged_validation] + +- name: "VALIDATION 1: Display successful validation summary for ebgp_test_fabric_merged" + debug: + msg: | + ======================================== + VALIDATION SUMMARY for ebgp_test_fabric_merged: + ======================================== + ✓ BGP ASN: {{ ebgp_merged_fabric_config.management.bgpAsn }} + ✓ Site ID: {{ ebgp_merged_fabric_config.management.siteId }} + ✓ Anycast Gateway MAC: {{ ebgp_merged_fabric_config.management.anycastGatewayMac }} + ✓ Performance Monitoring: {{ ebgp_merged_fabric_config.management.performanceMonitoring }} + ✓ BGP AS Mode: {{ ebgp_merged_fabric_config.management.bgpAsMode }} + + All 5 expected changes validated successfully! + ======================================== + tags: [test_merged, test_merged_validation] + +############################################################################# +# TEST 2: STATE REPLACED - Create and manage fabric using replaced state +############################################################################# +- name: "TEST 2a: Create eBGP fabric using state replaced (first run)" + cisco.nd.nd_manage_fabric_ebgp: + state: replaced + config: + - name: "{{ ebgp_test_fabric_replaced }}" + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanEbgp + bgp_asn: "65004" # Different from default ASN + bgp_asn_auto_allocation: true + bgp_asn_range: "65000-65100" + site_id: "65004" # Different from default site_id + bgp_as_mode: multiAS # Different from default multiAS + bgp_allow_as_in_num: 2 # Different from default 1 + bgp_max_path: 8 # Different from default 4 + auto_configure_ebgp_evpn_peering: true + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00dd" # Different from default MAC + performance_monitoring: true # Different from default false + replication_mode: multicast + multicast_group_subnet: "239.1.3.0/25" # Different from default subnet + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 3 # Different from default 2 + rendezvous_point_loopback_id: 253 # Different from default 254 + vpc_peer_link_vlan: "3700" # Different from default 3600 + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: management + vpc_auto_recovery_timer: 300 # Different from default 360 + vpc_delay_restore_timer: 120 # Different from default 150 + vpc_peer_link_port_channel_id: "600" # Different from default 500 + vpc_ipv6_neighbor_discovery_sync: false # Different from default true + advertise_physical_ip: true # Different from default false + vpc_domain_id_range: "1-800" # Different from default 1-1000 + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9000 # Different from default 9216 + l2_host_interface_mtu: 9000 # Different from default 9216 + tenant_dhcp: false # Different from default true + nxapi: false + nxapi_https_port: 443 + nxapi_http: true # Different from default false + nxapi_http_port: 80 + snmp_trap: false # Different from default true + anycast_border_gateway_advertise_physical_ip: true # Different from default false + greenfield_debug_flag: enable # Different from default disable + tcam_allocation: false # Different from default true + real_time_interface_statistics_collection: true # Different from default false + interface_statistics_load_interval: 30 # Different from default 10 + bgp_loopback_ip_range: "10.22.0.0/22" # Different from default range + nve_loopback_ip_range: "10.23.0.0/22" # Different from default range + anycast_rendezvous_point_ip_range: "10.254.252.0/24" # Different from default range + intra_fabric_subnet_range: "10.24.0.0/16" # Different from default range + l2_vni_range: "40000-59000" # Different from default range + l3_vni_range: "60000-69000" # Different from default range + network_vlan_range: "2400-3099" # Different from default range + vrf_vlan_range: "2100-2399" # Different from default range + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.53.0.0/16" # Different from default range + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.25.0.0/22" # Different from default range + per_vrf_loopback_auto_provision_ipv6: true + per_vrf_loopback_ipv6_range: "fd00::a25:0/112" # Different from default range + banner: "^ Updated via replaced state ^" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + management_ipv6_prefix: 64 + register: ebgp_replaced_result_1 + tags: [test_replaced, test_replaced_create] + +- name: "TEST 2a: Verify eBGP fabric was created using replaced state" + assert: + that: + - ebgp_replaced_result_1 is changed + - ebgp_replaced_result_1 is not failed + fail_msg: "eBGP fabric creation with state replaced failed" + success_msg: "eBGP fabric successfully created with state replaced" + tags: [test_replaced, test_replaced_create] + +- name: "TEST 2b: Create eBGP fabric using state replaced (second run - idempotency test)" + cisco.nd.nd_manage_fabric_ebgp: + state: replaced + config: + - name: "{{ ebgp_test_fabric_replaced }}" + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanEbgp + bgp_asn: "65004" # Different from default ASN + bgp_asn_auto_allocation: true + bgp_asn_range: "65000-65100" + site_id: "65004" + bgp_as_mode: multiAS # Different from default multiAS + bgp_allow_as_in_num: 2 + bgp_max_path: 8 + auto_configure_ebgp_evpn_peering: true + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00dd" + performance_monitoring: true + replication_mode: multicast + multicast_group_subnet: "239.1.3.0/25" + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 3 + rendezvous_point_loopback_id: 253 + vpc_peer_link_vlan: "3700" + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: management + vpc_auto_recovery_timer: 300 + vpc_delay_restore_timer: 120 + vpc_peer_link_port_channel_id: "600" + vpc_ipv6_neighbor_discovery_sync: false + advertise_physical_ip: true + vpc_domain_id_range: "1-800" + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9000 + l2_host_interface_mtu: 9000 + tenant_dhcp: false + nxapi: false + nxapi_https_port: 443 + nxapi_http: true + nxapi_http_port: 80 + snmp_trap: false + anycast_border_gateway_advertise_physical_ip: true + greenfield_debug_flag: enable + tcam_allocation: false + real_time_interface_statistics_collection: true + interface_statistics_load_interval: 30 + bgp_loopback_ip_range: "10.22.0.0/22" + nve_loopback_ip_range: "10.23.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.252.0/24" + intra_fabric_subnet_range: "10.24.0.0/16" + l2_vni_range: "40000-59000" + l3_vni_range: "60000-69000" + network_vlan_range: "2400-3099" + vrf_vlan_range: "2100-2399" + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.53.0.0/16" + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.25.0.0/22" + per_vrf_loopback_auto_provision_ipv6: true + per_vrf_loopback_ipv6_range: "fd00::a25:0/112" + banner: "^ Updated via replaced state ^" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + management_ipv6_prefix: 64 + register: ebgp_replaced_result_2 + tags: [test_replaced, test_replaced_idempotent] + +- name: "TEST 2b: Verify replaced state is idempotent" + assert: + that: + - ebgp_replaced_result_2 is not changed + - ebgp_replaced_result_2 is not failed + fail_msg: "Replaced state is not idempotent - should not change when run twice with same config" + success_msg: "Replaced state is idempotent - no changes on second run" + tags: [test_replaced, test_replaced_idempotent] + +- name: "TEST 2c: Update eBGP fabric using state replaced (complete replacement with minimal config)" + cisco.nd.nd_manage_fabric_ebgp: + state: replaced + config: + - name: "{{ ebgp_test_fabric_replaced }}" + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanEbgp + bgp_asn: "65004" # Different from default ASN + bgp_asn_auto_allocation: true + bgp_asn_range: "65000-65100" + site_id: "65004" + banner: "^ Updated via replaced state ^" + register: ebgp_replaced_result_3 + tags: [test_replaced, test_replaced_update] + +- name: "TEST 2c: Verify eBGP fabric was completely replaced (defaults restored)" + assert: + that: + - ebgp_replaced_result_3 is changed + - ebgp_replaced_result_3 is not failed + fail_msg: "eBGP fabric replacement with state replaced failed" + success_msg: "eBGP fabric successfully replaced with state replaced" + tags: [test_replaced, test_replaced_update] + +############################################################################# +# VALIDATION: Query ebgp_test_fabric_replaced and validate defaults are restored +############################################################################# +- name: "VALIDATION 2: Authenticate with ND to get token" + ansible.builtin.uri: + url: "https://{{ ansible_host }}:{{ ansible_httpapi_port | default(443) }}/login" + method: POST + headers: + Content-Type: "application/json" + body_format: json + body: + domain: "{{ ansible_httpapi_login_domain | default('local') }}" + userName: "{{ ansible_user }}" + userPasswd: "{{ ansible_password }}" + validate_certs: false + return_content: true + status_code: + - 200 + register: nd_auth_response_2 + tags: [test_replaced, test_replaced_validation] + delegate_to: localhost + +- name: "VALIDATION 2: Query ebgp_test_fabric_replaced configuration from ND" + ansible.builtin.uri: + url: "https://{{ ansible_host }}:{{ ansible_httpapi_port | default(443) }}/api/v1/manage/fabrics/{{ ebgp_test_fabric_replaced }}" + method: GET + headers: + Authorization: "Bearer {{ nd_auth_response_2.json.jwttoken }}" + Content-Type: "application/json" + validate_certs: false + return_content: true + status_code: + - 200 + - 404 + register: ebgp_replaced_fabric_query + tags: [test_replaced, test_replaced_validation] + delegate_to: localhost + +- name: "VALIDATION 2: Parse eBGP fabric configuration response" + set_fact: + ebgp_replaced_fabric_config: "{{ ebgp_replaced_fabric_query.json }}" + tags: [test_replaced, test_replaced_validation] + +# Network Range Validations - verify defaults were restored +- name: "VALIDATION 2: Verify L3 VNI Range was standardized to 50000-59000" + assert: + that: + - ebgp_replaced_fabric_config.management.l3VniRange == "50000-59000" + fail_msg: "L3 VNI Range validation failed. Expected: 50000-59000, Actual: {{ ebgp_replaced_fabric_config.management.l3VniRange }}" + success_msg: "✓ L3 VNI Range correctly standardized to 50000-59000" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify L2 VNI Range was standardized to 30000-49000" + assert: + that: + - ebgp_replaced_fabric_config.management.l2VniRange == "30000-49000" + fail_msg: "L2 VNI Range validation failed. Expected: 30000-49000, Actual: {{ ebgp_replaced_fabric_config.management.l2VniRange }}" + success_msg: "✓ L2 VNI Range correctly standardized to 30000-49000" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify BGP Loopback IP Range was standardized to 10.2.0.0/22" + assert: + that: + - ebgp_replaced_fabric_config.management.bgpLoopbackIpRange == "10.2.0.0/22" + fail_msg: "BGP Loopback IP Range validation failed. Expected: 10.2.0.0/22, Actual: {{ ebgp_replaced_fabric_config.management.bgpLoopbackIpRange }}" + success_msg: "✓ BGP Loopback IP Range correctly standardized to 10.2.0.0/22" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify NVE Loopback IP Range was standardized to 10.3.0.0/22" + assert: + that: + - ebgp_replaced_fabric_config.management.nveLoopbackIpRange == "10.3.0.0/22" + fail_msg: "NVE Loopback IP Range validation failed. Expected: 10.3.0.0/22, Actual: {{ ebgp_replaced_fabric_config.management.nveLoopbackIpRange }}" + success_msg: "✓ NVE Loopback IP Range correctly standardized to 10.3.0.0/22" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Intra-Fabric Subnet Range was standardized to 10.4.0.0/16" + assert: + that: + - ebgp_replaced_fabric_config.management.intraFabricSubnetRange == "10.4.0.0/16" + fail_msg: "Intra-Fabric Subnet Range validation failed. Expected: 10.4.0.0/16, Actual: {{ ebgp_replaced_fabric_config.management.intraFabricSubnetRange }}" + success_msg: "✓ Intra-Fabric Subnet Range correctly standardized to 10.4.0.0/16" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VRF Lite Subnet Range was standardized to 10.33.0.0/16" + assert: + that: + - ebgp_replaced_fabric_config.management.vrfLiteSubnetRange == "10.33.0.0/16" + fail_msg: "VRF Lite Subnet Range validation failed. Expected: 10.33.0.0/16, Actual: {{ ebgp_replaced_fabric_config.management.vrfLiteSubnetRange }}" + success_msg: "✓ VRF Lite Subnet Range correctly standardized to 10.33.0.0/16" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Anycast RP IP Range was standardized to 10.254.254.0/24" + assert: + that: + - ebgp_replaced_fabric_config.management.anycastRendezvousPointIpRange == "10.254.254.0/24" + fail_msg: "Anycast RP IP Range validation failed. Expected: 10.254.254.0/24, Actual: {{ ebgp_replaced_fabric_config.management.anycastRendezvousPointIpRange }}" + success_msg: "✓ Anycast RP IP Range correctly standardized to 10.254.254.0/24" + tags: [test_replaced, test_replaced_validation] + +# VLAN Range Validations +- name: "VALIDATION 2: Verify Network VLAN Range was standardized to 2300-2999" + assert: + that: + - ebgp_replaced_fabric_config.management.networkVlanRange == "2300-2999" + fail_msg: "Network VLAN Range validation failed. Expected: 2300-2999, Actual: {{ ebgp_replaced_fabric_config.management.networkVlanRange }}" + success_msg: "✓ Network VLAN Range correctly standardized to 2300-2999" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VRF VLAN Range was standardized to 2000-2299" + assert: + that: + - ebgp_replaced_fabric_config.management.vrfVlanRange == "2000-2299" + fail_msg: "VRF VLAN Range validation failed. Expected: 2000-2299, Actual: {{ ebgp_replaced_fabric_config.management.vrfVlanRange }}" + success_msg: "✓ VRF VLAN Range correctly standardized to 2000-2299" + tags: [test_replaced, test_replaced_validation] + +# MTU Validations +- name: "VALIDATION 2: Verify Fabric MTU was restored to 9216" + assert: + that: + - ebgp_replaced_fabric_config.management.fabricMtu == 9216 + fail_msg: "Fabric MTU validation failed. Expected: 9216, Actual: {{ ebgp_replaced_fabric_config.management.fabricMtu }}" + success_msg: "✓ Fabric MTU correctly restored to 9216" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify L2 Host Interface MTU was restored to 9216" + assert: + that: + - ebgp_replaced_fabric_config.management.l2HostInterfaceMtu == 9216 + fail_msg: "L2 Host Interface MTU validation failed. Expected: 9216, Actual: {{ ebgp_replaced_fabric_config.management.l2HostInterfaceMtu }}" + success_msg: "✓ L2 Host Interface MTU correctly restored to 9216" + tags: [test_replaced, test_replaced_validation] + +# Gateway and Multicast Validations +- name: "VALIDATION 2: Verify Anycast Gateway MAC was standardized to 2020.0000.00aa" + assert: + that: + - ebgp_replaced_fabric_config.management.anycastGatewayMac == "2020.0000.00aa" + fail_msg: "Anycast Gateway MAC validation failed. Expected: 2020.0000.00aa, Actual: {{ ebgp_replaced_fabric_config.management.anycastGatewayMac }}" + success_msg: "✓ Anycast Gateway MAC correctly standardized to 2020.0000.00aa" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Multicast Group Subnet was standardized to 239.1.1.0/25" + assert: + that: + - ebgp_replaced_fabric_config.management.multicastGroupSubnet == "239.1.1.0/25" + fail_msg: "Multicast Group Subnet validation failed. Expected: 239.1.1.0/25, Actual: {{ ebgp_replaced_fabric_config.management.multicastGroupSubnet }}" + success_msg: "✓ Multicast Group Subnet correctly standardized to 239.1.1.0/25" + tags: [test_replaced, test_replaced_validation] + +# VPC Configuration Validations +- name: "VALIDATION 2: Verify VPC Auto Recovery Timer was standardized to 360" + assert: + that: + - ebgp_replaced_fabric_config.management.vpcAutoRecoveryTimer == 360 + fail_msg: "VPC Auto Recovery Timer validation failed. Expected: 360, Actual: {{ ebgp_replaced_fabric_config.management.vpcAutoRecoveryTimer }}" + success_msg: "✓ VPC Auto Recovery Timer correctly standardized to 360" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VPC Delay Restore Timer was standardized to 150" + assert: + that: + - ebgp_replaced_fabric_config.management.vpcDelayRestoreTimer == 150 + fail_msg: "VPC Delay Restore Timer validation failed. Expected: 150, Actual: {{ ebgp_replaced_fabric_config.management.vpcDelayRestoreTimer }}" + success_msg: "✓ VPC Delay Restore Timer correctly standardized to 150" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VPC Peer Link Port Channel ID was standardized to 500" + assert: + that: + - ebgp_replaced_fabric_config.management.vpcPeerLinkPortChannelId == "500" + fail_msg: "VPC Peer Link Port Channel ID validation failed. Expected: 500, Actual: {{ ebgp_replaced_fabric_config.management.vpcPeerLinkPortChannelId }}" + success_msg: "✓ VPC Peer Link Port Channel ID correctly standardized to 500" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VPC Peer Link VLAN was standardized to 3600" + assert: + that: + - ebgp_replaced_fabric_config.management.vpcPeerLinkVlan == "3600" + fail_msg: "VPC Peer Link VLAN validation failed. Expected: 3600, Actual: {{ ebgp_replaced_fabric_config.management.vpcPeerLinkVlan }}" + success_msg: "✓ VPC Peer Link VLAN correctly standardized to 3600" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VPC Domain ID Range was standardized to 1-1000" + assert: + that: + - ebgp_replaced_fabric_config.management.vpcDomainIdRange == "1-1000" + fail_msg: "VPC Domain ID Range validation failed. Expected: 1-1000, Actual: {{ ebgp_replaced_fabric_config.management.vpcDomainIdRange }}" + success_msg: "✓ VPC Domain ID Range correctly standardized to 1-1000" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VPC IPv6 Neighbor Discovery Sync was enabled" + assert: + that: + - ebgp_replaced_fabric_config.management.vpcIpv6NeighborDiscoverySync == true + fail_msg: "VPC IPv6 Neighbor Discovery Sync validation failed. Expected: true, Actual: {{ ebgp_replaced_fabric_config.management.vpcIpv6NeighborDiscoverySync }}" + success_msg: "✓ VPC IPv6 Neighbor Discovery Sync correctly enabled" + tags: [test_replaced, test_replaced_validation] + +# Multicast Settings Validations +- name: "VALIDATION 2: Verify Rendezvous Point Count was standardized to 2" + assert: + that: + - ebgp_replaced_fabric_config.management.rendezvousPointCount == 2 + fail_msg: "Rendezvous Point Count validation failed. Expected: 2, Actual: {{ ebgp_replaced_fabric_config.management.rendezvousPointCount }}" + success_msg: "✓ Rendezvous Point Count correctly standardized to 2" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Rendezvous Point Loopback ID was standardized to 254" + assert: + that: + - ebgp_replaced_fabric_config.management.rendezvousPointLoopbackId == 254 + fail_msg: "Rendezvous Point Loopback ID validation failed. Expected: 254, Actual: {{ ebgp_replaced_fabric_config.management.rendezvousPointLoopbackId }}" + success_msg: "✓ Rendezvous Point Loopback ID correctly standardized to 254" + tags: [test_replaced, test_replaced_validation] + +# eBGP-specific Validations +- name: "VALIDATION 2: Verify BGP AS Mode was standardized to multiAS" + assert: + that: + - ebgp_replaced_fabric_config.management.bgpAsMode == "multiAS" + fail_msg: "BGP AS Mode validation failed. Expected: multiAS, Actual: {{ ebgp_replaced_fabric_config.management.bgpAsMode }}" + success_msg: "✓ BGP AS Mode correctly standardized to multiAS" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify BGP Allow AS In Num was standardized to 1" + assert: + that: + - ebgp_replaced_fabric_config.management.bgpAllowAsInNum == 1 + fail_msg: "BGP Allow AS In Num validation failed. Expected: 1, Actual: {{ ebgp_replaced_fabric_config.management.bgpAllowAsInNum }}" + success_msg: "✓ BGP Allow AS In Num correctly standardized to 1" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify BGP Max Path was standardized to 4" + assert: + that: + - ebgp_replaced_fabric_config.management.bgpMaxPath == 4 + fail_msg: "BGP Max Path validation failed. Expected: 4, Actual: {{ ebgp_replaced_fabric_config.management.bgpMaxPath }}" + success_msg: "✓ BGP Max Path correctly standardized to 4" + tags: [test_replaced, test_replaced_validation] + +# Feature Flag Validations +- name: "VALIDATION 2: Verify TCAM Allocation was re-enabled" + assert: + that: + - ebgp_replaced_fabric_config.management.tcamAllocation == true + fail_msg: "TCAM Allocation validation failed. Expected: true, Actual: {{ ebgp_replaced_fabric_config.management.tcamAllocation }}" + success_msg: "✓ TCAM Allocation correctly re-enabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Real Time Interface Statistics Collection was disabled" + assert: + that: + - ebgp_replaced_fabric_config.management.realTimeInterfaceStatisticsCollection == false + fail_msg: "Real Time Interface Statistics Collection validation failed. Expected: false, Actual: {{ ebgp_replaced_fabric_config.management.realTimeInterfaceStatisticsCollection }}" + success_msg: "✓ Real Time Interface Statistics Collection correctly disabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Performance Monitoring was disabled" + assert: + that: + - ebgp_replaced_fabric_config.management.performanceMonitoring == false + fail_msg: "Performance Monitoring validation failed. Expected: false, Actual: {{ ebgp_replaced_fabric_config.management.performanceMonitoring }}" + success_msg: "✓ Performance Monitoring correctly disabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Tenant DHCP was re-enabled" + assert: + that: + - ebgp_replaced_fabric_config.management.tenantDhcp == true + fail_msg: "Tenant DHCP validation failed. Expected: true, Actual: {{ ebgp_replaced_fabric_config.management.tenantDhcp }}" + success_msg: "✓ Tenant DHCP correctly re-enabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify SNMP Trap was re-enabled" + assert: + that: + - ebgp_replaced_fabric_config.management.snmpTrap == true + fail_msg: "SNMP Trap validation failed. Expected: true, Actual: {{ ebgp_replaced_fabric_config.management.snmpTrap }}" + success_msg: "✓ SNMP Trap correctly re-enabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Greenfield Debug Flag was set to disable (eBGP default)" + assert: + that: + - ebgp_replaced_fabric_config.management.greenfieldDebugFlag == "disable" + fail_msg: "Greenfield Debug Flag validation failed. Expected: disable, Actual: {{ ebgp_replaced_fabric_config.management.greenfieldDebugFlag }}" + success_msg: "✓ Greenfield Debug Flag correctly set to disable (eBGP default)" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify NXAPI HTTP is always true for eBGP (ND enforced behavior)" + assert: + that: + - ebgp_replaced_fabric_config.management.nxapiHttp == true + fail_msg: "NXAPI HTTP validation failed. ND enforces nxapiHttp=true for eBGP fabrics, Actual: {{ ebgp_replaced_fabric_config.management.nxapiHttp }}" + success_msg: "✓ NXAPI HTTP is true (ND enforces this for eBGP fabrics regardless of configured value)" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify NXAPI was disabled" + assert: + that: + - ebgp_replaced_fabric_config.management.nxapi == false + fail_msg: "NXAPI validation failed. Expected: false, Actual: {{ ebgp_replaced_fabric_config.management.nxapi }}" + success_msg: "✓ NXAPI correctly disabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Per VRF Loopback Auto Provision was disabled" + assert: + that: + - ebgp_replaced_fabric_config.management.perVrfLoopbackAutoProvision == false + fail_msg: "Per VRF Loopback Auto Provision validation failed. Expected: false, Actual: {{ ebgp_replaced_fabric_config.management.perVrfLoopbackAutoProvision }}" + success_msg: "✓ Per VRF Loopback Auto Provision correctly disabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Per VRF Loopback Auto Provision IPv6 was disabled" + assert: + that: + - ebgp_replaced_fabric_config.management.perVrfLoopbackAutoProvisionIpv6 == false + fail_msg: "Per VRF Loopback Auto Provision IPv6 validation failed. Expected: false, Actual: {{ ebgp_replaced_fabric_config.management.perVrfLoopbackAutoProvisionIpv6 }}" + success_msg: "✓ Per VRF Loopback Auto Provision IPv6 correctly disabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Banner was preserved" + assert: + that: + - ebgp_replaced_fabric_config.management.banner == "^ Updated via replaced state ^" + fail_msg: "Banner validation failed. Expected: '^ Updated via replaced state ^', Actual: {{ ebgp_replaced_fabric_config.management.banner }}" + success_msg: "✓ Banner correctly preserved: '{{ ebgp_replaced_fabric_config.management.banner }}'" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Display successful validation summary for ebgp_test_fabric_replaced" + debug: + msg: | + ======================================== + VALIDATION SUMMARY for ebgp_test_fabric_replaced: + ======================================== + Network Ranges (restored to defaults): + ✓ L3 VNI Range: {{ ebgp_replaced_fabric_config.management.l3VniRange }} + ✓ L2 VNI Range: {{ ebgp_replaced_fabric_config.management.l2VniRange }} + ✓ BGP Loopback IP Range: {{ ebgp_replaced_fabric_config.management.bgpLoopbackIpRange }} + ✓ NVE Loopback IP Range: {{ ebgp_replaced_fabric_config.management.nveLoopbackIpRange }} + ✓ Intra-Fabric Subnet Range: {{ ebgp_replaced_fabric_config.management.intraFabricSubnetRange }} + ✓ VRF Lite Subnet Range: {{ ebgp_replaced_fabric_config.management.vrfLiteSubnetRange }} + ✓ Anycast RP IP Range: {{ ebgp_replaced_fabric_config.management.anycastRendezvousPointIpRange }} + + VLAN Ranges: + ✓ Network VLAN Range: {{ ebgp_replaced_fabric_config.management.networkVlanRange }} + ✓ VRF VLAN Range: {{ ebgp_replaced_fabric_config.management.vrfVlanRange }} + + MTU Settings: + ✓ Fabric MTU: {{ ebgp_replaced_fabric_config.management.fabricMtu }} + ✓ L2 Host Interface MTU: {{ ebgp_replaced_fabric_config.management.l2HostInterfaceMtu }} + + VPC Configuration: + ✓ VPC Auto Recovery Timer: {{ ebgp_replaced_fabric_config.management.vpcAutoRecoveryTimer }} + ✓ VPC Delay Restore Timer: {{ ebgp_replaced_fabric_config.management.vpcDelayRestoreTimer }} + ✓ VPC Peer Link Port Channel ID: {{ ebgp_replaced_fabric_config.management.vpcPeerLinkPortChannelId }} + ✓ VPC Peer Link VLAN: {{ ebgp_replaced_fabric_config.management.vpcPeerLinkVlan }} + ✓ VPC Domain ID Range: {{ ebgp_replaced_fabric_config.management.vpcDomainIdRange }} + ✓ VPC IPv6 Neighbor Discovery Sync: {{ ebgp_replaced_fabric_config.management.vpcIpv6NeighborDiscoverySync }} + + Gateway & Multicast: + ✓ Anycast Gateway MAC: {{ ebgp_replaced_fabric_config.management.anycastGatewayMac }} + ✓ Multicast Group Subnet: {{ ebgp_replaced_fabric_config.management.multicastGroupSubnet }} + ✓ Rendezvous Point Count: {{ ebgp_replaced_fabric_config.management.rendezvousPointCount }} + ✓ Rendezvous Point Loopback ID: {{ ebgp_replaced_fabric_config.management.rendezvousPointLoopbackId }} + + eBGP-specific: + ✓ BGP AS Mode: {{ ebgp_replaced_fabric_config.management.bgpAsMode }} + ✓ BGP Allow AS In Num: {{ ebgp_replaced_fabric_config.management.bgpAllowAsInNum }} + ✓ BGP Max Path: {{ ebgp_replaced_fabric_config.management.bgpMaxPath }} + + Feature Flags: + ✓ TCAM Allocation: {{ ebgp_replaced_fabric_config.management.tcamAllocation }} + ✓ Real Time Interface Statistics Collection: {{ ebgp_replaced_fabric_config.management.realTimeInterfaceStatisticsCollection }} + ✓ Performance Monitoring: {{ ebgp_replaced_fabric_config.management.performanceMonitoring }} + ✓ Tenant DHCP: {{ ebgp_replaced_fabric_config.management.tenantDhcp }} + ✓ SNMP Trap: {{ ebgp_replaced_fabric_config.management.snmpTrap }} + ✓ Greenfield Debug Flag (eBGP default): {{ ebgp_replaced_fabric_config.management.greenfieldDebugFlag }} + ✓ NXAPI HTTP (ND enforces true for eBGP): {{ ebgp_replaced_fabric_config.management.nxapiHttp }} + ✓ NXAPI: {{ ebgp_replaced_fabric_config.management.nxapi }} + + Auto-Provisioning: + ✓ Per VRF Loopback Auto Provision: {{ ebgp_replaced_fabric_config.management.perVrfLoopbackAutoProvision }} + ✓ Per VRF Loopback Auto Provision IPv6: {{ ebgp_replaced_fabric_config.management.perVrfLoopbackAutoProvisionIpv6 }} + + Preserved Settings: + ✓ Banner: "{{ ebgp_replaced_fabric_config.management.banner }}" + + All 35+ expected changes validated successfully! + ======================================== + tags: [test_replaced, test_replaced_validation] + +############################################################################# +# TEST 3: Demonstrate difference between merged and replaced states +############################################################################# +- name: "TEST 3: Create eBGP fabric for merged vs replaced comparison" + cisco.nd.nd_manage_fabric_ebgp: + state: replaced + config: + - "{{ {'name': ebgp_test_fabric_deleted} | combine(common_ebgp_fabric_config) }}" + register: ebgp_comparison_fabric_creation + tags: [test_comparison] + +- name: "TEST 3a: Partial update using merged state (should merge changes)" + cisco.nd.nd_manage_fabric_ebgp: + state: merged + config: + - name: "{{ ebgp_test_fabric_deleted }}" + category: fabric + management: + bgp_asn: "65004" # Different from default ASN + # bgp_asn_auto_allocation: true + bgp_asn_range: "65000-65100" + fabric_mtu: 8000 # Only updating MTU + register: ebgp_merged_partial_result + tags: [test_comparison, test_merged_partial] + +- name: "TEST 3a: Verify merged state preserves existing configuration" + assert: + that: + - ebgp_merged_partial_result is changed + - ebgp_merged_partial_result is not failed + fail_msg: "Partial update with merged state failed" + success_msg: "Merged state successfully performed partial update" + tags: [test_comparison, test_merged_partial] + +- name: "TEST 3b: Partial update using replaced state (should replace entire config)" + cisco.nd.nd_manage_fabric_ebgp: + state: replaced + config: + - name: "{{ ebgp_test_fabric_deleted }}" + category: fabric + management: + type: vxlanEbgp + bgp_asn: "65100" + bgp_asn_auto_allocation: true + bgp_asn_range: "65000-65100" + target_subnet_mask: 30 + register: ebgp_replaced_partial_result + tags: [test_comparison, test_replaced_partial] + +- name: "TEST 3b: Verify replaced state performs complete replacement" + assert: + that: + - ebgp_replaced_partial_result is changed + - ebgp_replaced_partial_result is not failed + fail_msg: "Partial replacement with replaced state failed" + success_msg: "Replaced state successfully performed complete replacement" + tags: [test_comparison, test_replaced_partial] + +############################################################################# +# TEST 4: STATE DELETED - Delete fabrics +############################################################################# +- name: "TEST 4a: Delete eBGP fabric using state deleted" + cisco.nd.nd_manage_fabric_ebgp: + state: deleted + config: + - name: "{{ ebgp_test_fabric_deleted }}" + register: ebgp_deleted_result_1 + tags: [test_deleted, test_deleted_delete] + +- name: "TEST 4a: Verify eBGP fabric was deleted" + assert: + that: + - ebgp_deleted_result_1 is changed + - ebgp_deleted_result_1 is not failed + fail_msg: "eBGP fabric deletion with state deleted failed" + success_msg: "eBGP fabric successfully deleted with state deleted" + tags: [test_deleted, test_deleted_delete] + +- name: "TEST 4b: Delete eBGP fabric using state deleted (second run - idempotency test)" + cisco.nd.nd_manage_fabric_ebgp: + state: deleted + config: + - name: "{{ ebgp_test_fabric_deleted }}" + register: ebgp_deleted_result_2 + tags: [test_deleted, test_deleted_idempotent] + +- name: "TEST 4b: Verify deleted state is idempotent" + assert: + that: + - ebgp_deleted_result_2 is not changed + - ebgp_deleted_result_2 is not failed + fail_msg: "Deleted state is not idempotent - should not change when deleting non-existent fabric" + success_msg: "Deleted state is idempotent - no changes when deleting non-existent fabric" + tags: [test_deleted, test_deleted_idempotent] + +############################################################################# +# TEST 5: Multiple fabric operations in single task +############################################################################# +- name: "TEST 5: Multiple eBGP fabric operations in single task" + cisco.nd.nd_manage_fabric_ebgp: + state: merged + config: + - name: "multi_ebgp_fabric_1" + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanEbgp + bgp_asn: "65101" + bgp_asn_auto_allocation: false + site_id: "65101" + bgp_as_mode: sameTierAS + bgp_allow_as_in_num: 1 + bgp_max_path: 4 + auto_configure_ebgp_evpn_peering: true + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.0001" + performance_monitoring: false + replication_mode: multicast + multicast_group_subnet: "239.1.1.0/25" + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 2 + rendezvous_point_loopback_id: 254 + vpc_peer_link_vlan: "3600" + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: management + vpc_auto_recovery_timer: 360 + vpc_delay_restore_timer: 150 + vpc_peer_link_port_channel_id: "500" + advertise_physical_ip: false + vpc_domain_id_range: "1-1000" + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9216 + l2_host_interface_mtu: 9216 + tenant_dhcp: true + nxapi: false + nxapi_https_port: 443 + nxapi_http: false + nxapi_http_port: 80 + snmp_trap: true + anycast_border_gateway_advertise_physical_ip: false + greenfield_debug_flag: disable + tcam_allocation: true + real_time_interface_statistics_collection: false + interface_statistics_load_interval: 10 + bgp_loopback_ip_range: "10.101.0.0/22" + nve_loopback_ip_range: "10.103.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.101.0/24" + intra_fabric_subnet_range: "10.104.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.133.0.0/16" + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.105.0.0/22" + banner: "" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + - name: "multi_ebgp_fabric_2" + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanEbgp + bgp_asn: "65102" + bgp_asn_auto_allocation: false + site_id: "65102" + bgp_as_mode: sameTierAS + bgp_allow_as_in_num: 1 + bgp_max_path: 4 + auto_configure_ebgp_evpn_peering: true + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.0002" + performance_monitoring: false + replication_mode: multicast + multicast_group_subnet: "239.1.1.0/25" + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 2 + rendezvous_point_loopback_id: 254 + vpc_peer_link_vlan: "3600" + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: management + vpc_auto_recovery_timer: 360 + vpc_delay_restore_timer: 150 + vpc_peer_link_port_channel_id: "500" + advertise_physical_ip: false + vpc_domain_id_range: "1-1000" + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9216 + l2_host_interface_mtu: 9216 + tenant_dhcp: true + nxapi: false + nxapi_https_port: 443 + nxapi_http: false + nxapi_http_port: 80 + snmp_trap: true + anycast_border_gateway_advertise_physical_ip: false + greenfield_debug_flag: disable + tcam_allocation: true + real_time_interface_statistics_collection: false + interface_statistics_load_interval: 10 + bgp_loopback_ip_range: "10.102.0.0/22" + nve_loopback_ip_range: "10.103.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.102.0/24" + intra_fabric_subnet_range: "10.104.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.134.0.0/16" + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.106.0.0/22" + banner: "" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + register: ebgp_multi_fabric_result + tags: [test_multi, test_multi_create] + +- name: "TEST 5: Verify multiple eBGP fabrics were created" + assert: + that: + - ebgp_multi_fabric_result is changed + - ebgp_multi_fabric_result is not failed + fail_msg: "Multiple eBGP fabric creation failed" + success_msg: "Multiple eBGP fabrics successfully created" + tags: [test_multi, test_multi_create] + +############################################################################# +# FINAL CLEANUP - Clean up all test fabrics +############################################################################# +- name: "CLEANUP: Delete all test eBGP fabrics" + cisco.nd.nd_manage_fabric_ebgp: + state: deleted + config: + - name: "{{ ebgp_test_fabric_merged }}" + - name: "{{ ebgp_test_fabric_replaced }}" + - name: "{{ ebgp_test_fabric_deleted }}" + - name: "multi_ebgp_fabric_1" + - name: "multi_ebgp_fabric_2" + ignore_errors: true + tags: [cleanup, always] + +############################################################################# +# TEST SUMMARY +############################################################################# +- name: "TEST SUMMARY: Display eBGP test results" + debug: + msg: | + ======================================================== + TEST SUMMARY for cisco.nd.nd_manage_fabric_ebgp module: + ======================================================== + ✓ TEST 1: STATE MERGED + - Create fabric: {{ 'PASSED' if ebgp_merged_result_1 is changed else 'FAILED' }} + - Idempotency: {{ 'PASSED' if ebgp_merged_result_2 is not changed else 'FAILED' }} + - Update fabric: {{ 'PASSED' if ebgp_merged_result_3 is changed else 'FAILED' }} + + ✓ TEST 2: STATE REPLACED + - Create fabric: {{ 'PASSED' if ebgp_replaced_result_1 is changed else 'FAILED' }} + - Idempotency: {{ 'PASSED' if ebgp_replaced_result_2 is not changed else 'FAILED' }} + - Replace fabric: {{ 'PASSED' if ebgp_replaced_result_3 is changed else 'FAILED' }} + + ✓ TEST 3: MERGED vs REPLACED Comparison + - Merged partial: {{ 'PASSED' if ebgp_merged_partial_result is changed else 'FAILED' }} + - Replaced partial: {{ 'PASSED' if ebgp_replaced_partial_result is changed else 'FAILED' }} + + ✓ TEST 4: STATE DELETED + - Delete fabric: {{ 'PASSED' if ebgp_deleted_result_1 is changed else 'FAILED' }} + - Idempotency: {{ 'PASSED' if ebgp_deleted_result_2 is not changed else 'FAILED' }} + + ✓ TEST 5: MULTIPLE FABRICS + - Multi-create: {{ 'PASSED' if ebgp_multi_fabric_result is changed else 'FAILED' }} + + All tests validate: + - State merged: Creates and updates eBGP fabrics by merging changes + - State replaced: Creates and completely replaces eBGP fabric configuration + - State deleted: Removes eBGP fabrics + - Idempotency: All operations are idempotent when run multiple times + - Difference: Merged preserves existing config, replaced overwrites completely + - eBGP-specific: bgpAsMode, bgpAllowAsInNum, bgpMaxPath defaults validated + ======================================== + tags: [summary, always] diff --git a/tests/integration/targets/nd_manage_fabric/tasks/fabric_ibgp.yaml b/tests/integration/targets/nd_manage_fabric/tasks/fabric_ibgp.yaml new file mode 100644 index 00000000..30b77c59 --- /dev/null +++ b/tests/integration/targets/nd_manage_fabric/tasks/fabric_ibgp.yaml @@ -0,0 +1,1172 @@ +--- +# Test code for the ND modules +# Copyright: (c) 2026, Mike Wiebe (@mwiebe) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +- name: Test that we have a Nexus Dashboard host, username and password + ansible.builtin.fail: + msg: 'Please define the following variables: ansible_host, ansible_user and ansible_password.' + when: ansible_host is not defined or ansible_user is not defined or ansible_password is not defined + +############################################################################# +# CLEANUP - Ensure clean state before tests +############################################################################# +- name: Clean up any existing test fabrics before starting tests + cisco.nd.nd_manage_fabric_ibgp: + state: deleted + config: + - name: "{{ test_fabric_merged }}" + - name: "{{ test_fabric_replaced }}" + - name: "{{ test_fabric_deleted }}" + tags: always + +############################################################################# +# TEST 1: STATE MERGED - Create fabric using merged state +############################################################################# +- name: "TEST 1a: Create fabric using state merged (first run)" + cisco.nd.nd_manage_fabric_ibgp: + state: merged + config: + - "{{ {'name': test_fabric_merged} | combine(common_fabric_config) }}" + register: merged_result_1 + tags: [test_merged, test_merged_create] + +- name: "TEST 1a: Verify fabric was created using merged state" + assert: + that: + - merged_result_1 is changed + - merged_result_1 is not failed + fail_msg: "Fabric creation with state merged failed" + success_msg: "Fabric successfully created with state merged" + tags: [test_merged, test_merged_create] + +- name: "TEST 1b: Create fabric using state merged (second run - idempotency test)" + cisco.nd.nd_manage_fabric_ibgp: + state: merged + config: + - "{{ {'name': test_fabric_merged} | combine(common_fabric_config) }}" + register: merged_result_2 + tags: [test_merged, test_merged_idempotent] + +- name: "TEST 1b: Verify merged state is idempotent" + assert: + that: + - merged_result_2 is not changed + - merged_result_2 is not failed + fail_msg: "Merged state is not idempotent - should not change when run twice with same config" + success_msg: "Merged state is idempotent - no changes on second run" + tags: [test_merged, test_merged_idempotent] + +# - name: "PAUSE: Review TEST 1b results before continuing" +# ansible.builtin.pause: +# prompt: "TEST 1b complete. Review results and press Enter to continue, or Ctrl+C then A to abort" +# tags: [test_merged, test_merged_update] + +- name: "TEST 1c: Update fabric using state merged (modify existing)" + cisco.nd.nd_manage_fabric_ibgp: + state: merged + config: + - name: "{{ test_fabric_merged }}" + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanIbgp + bgp_asn: "65002" # Changed from 65001 + site_id: "65002" # Changed from 65001 + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00bb" # Changed from 00aa + performance_monitoring: true # Changed from false + replication_mode: multicast + multicast_group_subnet: "239.1.1.0/25" + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 2 + rendezvous_point_loopback_id: 254 + vpc_peer_link_vlan: "3600" + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: loopback + vpc_auto_recovery_timer: 360 + vpc_delay_restore_timer: 150 + vpc_peer_link_port_channel_id: "500" + advertise_physical_ip: false + vpc_domain_id_range: "1-1000" + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9216 + l2_host_interface_mtu: 9216 + tenant_dhcp: true + nxapi: true + nxapi_https_port: 443 + nxapi_http: false + nxapi_http_port: 80 + snmp_trap: true + anycast_border_gateway_advertise_physical_ip: false + greenfield_debug_flag: enable + tcam_allocation: true + real_time_interface_statistics_collection: false + interface_statistics_load_interval: 10 + bgp_loopback_ip_range: "10.2.0.0/22" + nve_loopback_ip_range: "10.3.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.254.0/24" + intra_fabric_subnet_range: "10.4.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.33.0.0/16" + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.5.0.0/22" + # per_vrf_loopback_auto_provision_ipv6: false + # per_vrf_loopback_ipv6_range: "fd00::a05:0/112" + banner: "" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + register: merged_result_3 + tags: [test_merged, test_merged_update] + +- name: "TEST 1c: Verify fabric was updated using merged state" + assert: + that: + - merged_result_3 is changed + - merged_result_3 is not failed + fail_msg: "Fabric update with state merged failed" + success_msg: "Fabric successfully updated with state merged" + tags: [test_merged, test_merged_update] + +############################################################################# +# VALIDATION: Query test_fabric_merged and validate expected changes +############################################################################# +# Get authentication token first +- name: "VALIDATION 1: Authenticate with ND to get token" + ansible.builtin.uri: + url: "https://{{ ansible_host }}:{{ ansible_httpapi_port | default(443) }}/login" + method: POST + headers: + Content-Type: "application/json" + body_format: json + body: + domain: "{{ ansible_httpapi_login_domain | default('local') }}" + userName: "{{ ansible_user }}" + userPasswd: "{{ ansible_password }}" + validate_certs: false + return_content: true + status_code: + - 200 + register: nd_auth_response + tags: [test_merged, test_merged_validation] + delegate_to: localhost + +- name: "VALIDATION 1: Query test_fabric_merged configuration from ND" + ansible.builtin.uri: + url: "https://{{ ansible_host }}:{{ ansible_httpapi_port | default(443) }}/api/v1/manage/fabrics/{{ test_fabric_merged }}" + method: GET + headers: + Authorization: "Bearer {{ nd_auth_response.json.jwttoken }}" + Content-Type: "application/json" + validate_certs: false + return_content: true + status_code: + - 200 + - 404 + register: merged_fabric_query + tags: [test_merged, test_merged_validation] + delegate_to: localhost + +# - debug: msg="{{ merged_fabric_query }}" +# - meta: end_play + +- name: "VALIDATION 1: Parse fabric configuration response" + set_fact: + merged_fabric_config: "{{ merged_fabric_query.json }}" + tags: [test_merged, test_merged_validation] + +- name: "VALIDATION 1: Verify BGP ASN was updated to 65002" + assert: + that: + - merged_fabric_config.management.bgpAsn == "65002" + fail_msg: "BGP ASN validation failed. Expected: 65002, Actual: {{ merged_fabric_config.management.bgpAsn }}" + success_msg: "✓ BGP ASN correctly updated to 65002" + tags: [test_merged, test_merged_validation] + +- name: "VALIDATION 1: Verify Site ID was updated to 65002" + assert: + that: + - merged_fabric_config.management.siteId == "65002" + fail_msg: "Site ID validation failed. Expected: 65002, Actual: {{ merged_fabric_config.management.siteId }}" + success_msg: "✓ Site ID correctly updated to 65002" + tags: [test_merged, test_merged_validation] + +- name: "VALIDATION 1: Verify Anycast Gateway MAC was updated to 2020.0000.00bb" + assert: + that: + - merged_fabric_config.management.anycastGatewayMac == "2020.0000.00bb" + fail_msg: "Anycast Gateway MAC validation failed. Expected: 2020.0000.00bb, Actual: {{ merged_fabric_config.management.anycastGatewayMac }}" + success_msg: "✓ Anycast Gateway MAC correctly updated to 2020.0000.00bb" + tags: [test_merged, test_merged_validation] + +- name: "VALIDATION 1: Verify Performance Monitoring was enabled" + assert: + that: + - merged_fabric_config.management.performanceMonitoring == true + fail_msg: "Performance Monitoring validation failed. Expected: true, Actual: {{ merged_fabric_config.management.performanceMonitoring }}" + success_msg: "✓ Performance Monitoring correctly enabled" + tags: [test_merged, test_merged_validation] + +- name: "VALIDATION 1: Display successful validation summary for test_fabric_merged" + debug: + msg: | + ======================================== + VALIDATION SUMMARY for test_fabric_merged: + ======================================== + ✓ BGP ASN: {{ merged_fabric_config.management.bgpAsn }} + ✓ Site ID: {{ merged_fabric_config.management.siteId }} + ✓ Anycast Gateway MAC: {{ merged_fabric_config.management.anycastGatewayMac }} + ✓ Performance Monitoring: {{ merged_fabric_config.management.performanceMonitoring }} + + All 4 expected changes validated successfully! + ======================================== + tags: [test_merged, test_merged_validation] + +# - name: "PAUSE: Review TEST 1c results before continuing" +# ansible.builtin.pause: +# prompt: "TEST 1c complete. Review results and press Enter to continue, or Ctrl+C then A to abort" +# tags: [test_merged, test_merged_update] + +############################################################################# +# TEST 2: STATE REPLACED - Create and manage fabric using replaced state +############################################################################# +- name: "TEST 2a: Create fabric using state replaced (first run)" + cisco.nd.nd_manage_fabric_ibgp: + state: replaced + config: + - name: "{{ test_fabric_replaced }}" + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanIbgp + bgp_asn: "65004" # DIfferent from default ASN + site_id: "65004" # DIfferent from default site_id + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00dd" # DIfferent from default MAC + performance_monitoring: true # DIfferent from default to true + replication_mode: multicast + multicast_group_subnet: "239.1.3.0/25" # DIfferent from default subnet + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 3 # DIfferent from default count + rendezvous_point_loopback_id: 253 # DIfferent from default loopback + vpc_peer_link_vlan: "3700" # DIfferent from default VLAN + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: loopback + vpc_auto_recovery_timer: 300 # DIfferent from default timer + vpc_delay_restore_timer: 120 # DIfferent from default timer + vpc_peer_link_port_channel_id: "600" # DIfferent from default port channel + vpc_ipv6_neighbor_discovery_sync: false # DIfferent from default to false + advertise_physical_ip: true # DIfferent from default to true + vpc_domain_id_range: "1-800" # DIfferent from default range + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9000 # DIfferent from default MTU + l2_host_interface_mtu: 9000 # DIfferent from default MTU + tenant_dhcp: false # DIfferent from default to false + nxapi: false # DIfferent from default to false + nxapi_https_port: 443 + nxapi_http: true # DIfferent from default to true + nxapi_http_port: 80 + snmp_trap: false # DIfferent from default to false + anycast_border_gateway_advertise_physical_ip: true # DIfferent from default to true + greenfield_debug_flag: disable # DIfferent from default to disable + tcam_allocation: false # DIfferent from default to false + real_time_interface_statistics_collection: true # DIfferent from default to true + interface_statistics_load_interval: 30 # DIfferent from default interval + bgp_loopback_ip_range: "10.22.0.0/22" # DIfferent from default range + nve_loopback_ip_range: "10.23.0.0/22" # DIfferent from default range + anycast_rendezvous_point_ip_range: "10.254.252.0/24" # DIfferent from default range + intra_fabric_subnet_range: "10.24.0.0/16" # DIfferent from default range + l2_vni_range: "40000-59000" # DIfferent from default range + l3_vni_range: "60000-69000" # DIfferent from default range + network_vlan_range: "2400-3099" # DIfferent from default range + vrf_vlan_range: "2100-2399" # DIfferent from default range + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.53.0.0/16" # DIfferent from default range + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.25.0.0/22" # DIfferent from default range + per_vrf_loopback_auto_provision_ipv6: true + per_vrf_loopback_ipv6_range: "fd00::a25:0/112" # DIfferent from default range + banner: "^ Updated via replaced state ^" # Added banner + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + management_ipv6_prefix: 64 + register: replaced_result_1 + tags: [test_replaced, test_replaced_create] + +- name: "TEST 2a: Verify fabric was created using replaced state" + assert: + that: + - replaced_result_1 is changed + - replaced_result_1 is not failed + fail_msg: "Fabric creation with state replaced failed" + success_msg: "Fabric successfully created with state replaced" + tags: [test_replaced, test_replaced_create] + +- name: "TEST 2b: Create fabric using state replaced (second run - idempotency test)" + cisco.nd.nd_manage_fabric_ibgp: + state: replaced + config: + - name: "{{ test_fabric_replaced }}" + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanIbgp + bgp_asn: "65004" # DIfferent from default ASN + site_id: "65004" # DIfferent from default site_id + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00dd" # DIfferent from default MAC + performance_monitoring: true # DIfferent from default to true + replication_mode: multicast + multicast_group_subnet: "239.1.3.0/25" # DIfferent from default subnet + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 3 # DIfferent from default count + rendezvous_point_loopback_id: 253 # DIfferent from default loopback + vpc_peer_link_vlan: "3700" # DIfferent from default VLAN + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: loopback + vpc_auto_recovery_timer: 300 # DIfferent from default timer + vpc_delay_restore_timer: 120 # DIfferent from default timer + vpc_peer_link_port_channel_id: "600" # DIfferent from default port channel + vpc_ipv6_neighbor_discovery_sync: false # DIfferent from default to false + advertise_physical_ip: true # DIfferent from default to true + vpc_domain_id_range: "1-800" # DIfferent from default range + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9000 # DIfferent from default MTU + l2_host_interface_mtu: 9000 # DIfferent from default MTU + tenant_dhcp: false # DIfferent from default to false + nxapi: false # DIfferent from default to false + nxapi_https_port: 443 + nxapi_http: true # DIfferent from default to true + nxapi_http_port: 80 + snmp_trap: false # DIfferent from default to false + anycast_border_gateway_advertise_physical_ip: true # DIfferent from default to true + greenfield_debug_flag: disable # DIfferent from default to disable + tcam_allocation: false # DIfferent from default to false + real_time_interface_statistics_collection: true # DIfferent from default to true + interface_statistics_load_interval: 30 # DIfferent from default interval + bgp_loopback_ip_range: "10.22.0.0/22" # DIfferent from default range + nve_loopback_ip_range: "10.23.0.0/22" # DIfferent from default range + anycast_rendezvous_point_ip_range: "10.254.252.0/24" # DIfferent from default range + intra_fabric_subnet_range: "10.24.0.0/16" # DIfferent from default range + l2_vni_range: "40000-59000" # DIfferent from default range + l3_vni_range: "60000-69000" # DIfferent from default range + network_vlan_range: "2400-3099" # DIfferent from default range + vrf_vlan_range: "2100-2399" # DIfferent from default range + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.53.0.0/16" # DIfferent from default range + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.25.0.0/22" # DIfferent from default range + per_vrf_loopback_auto_provision_ipv6: true + per_vrf_loopback_ipv6_range: "fd00::a25:0/112" # DIfferent from default range + banner: "^ Updated via replaced state ^" # Added banner + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + management_ipv6_prefix: 64 + register: replaced_result_2 + tags: [test_replaced, test_replaced_idempotent] + +- name: "TEST 2b: Verify replaced state is idempotent" + assert: + that: + - replaced_result_2 is not changed + - replaced_result_2 is not failed + fail_msg: "Replaced state is not idempotent - should not change when run twice with same config" + success_msg: "Replaced state is idempotent - no changes on second run" + tags: [test_replaced, test_replaced_idempotent] + +# - name: "PAUSE: Review TEST 2b results before continuing" +# ansible.builtin.pause: +# prompt: "TEST 2b complete. Review results and press Enter to continue, or Ctrl+C then A to abort" +# tags: [test_replaced, test_replaced_idempotent] + +- name: "TEST 2c: Update fabric using state replaced (complete replacement)" + cisco.nd.nd_manage_fabric_ibgp: + state: replaced + config: + - name: "{{ test_fabric_replaced }}" + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanIbgp + bgp_asn: "65004" # Changed ASN + site_id: "65004" # Changed site_id + banner: "^ Updated via replaced state ^" # Added banner + register: replaced_result_3 + tags: [test_replaced, test_replaced_update] + +- name: "TEST 2c: Verify fabric was completely replaced" + assert: + that: + - replaced_result_3 is changed + - replaced_result_3 is not failed + fail_msg: "Fabric replacement with state replaced failed" + success_msg: "Fabric successfully replaced with state replaced" + tags: [test_replaced, test_replaced_update] + +# ############################################################################# +# # VALIDATION: Query test_fabric_replaced and validate expected changes +# ############################################################################# +# Get authentication token first +- name: "VALIDATION 2: Authenticate with ND to get token" + ansible.builtin.uri: + url: "https://{{ ansible_host }}:{{ ansible_httpapi_port | default(443) }}/login" + method: POST + headers: + Content-Type: "application/json" + body_format: json + body: + domain: "{{ ansible_httpapi_login_domain | default('local') }}" + userName: "{{ ansible_user }}" + userPasswd: "{{ ansible_password }}" + validate_certs: false + return_content: true + status_code: + - 200 + register: nd_auth_response_2 + tags: [test_replaced, test_replaced_validation] + delegate_to: localhost + +- name: "VALIDATION 2: Query test_fabric_replaced configuration from ND" + ansible.builtin.uri: + url: "https://{{ ansible_host }}:{{ ansible_httpapi_port | default(443) }}/api/v1/manage/fabrics/{{ test_fabric_replaced }}" + method: GET + headers: + Authorization: "Bearer {{ nd_auth_response_2.json.jwttoken }}" + Content-Type: "application/json" + validate_certs: false + return_content: true + status_code: + - 200 + - 404 + register: replaced_fabric_query + tags: [test_replaced, test_replaced_validation] + delegate_to: localhost + +- name: "VALIDATION 2: Parse fabric configuration response" + set_fact: + replaced_fabric_config: "{{ replaced_fabric_query.json }}" + tags: [test_replaced, test_replaced_validation] + +# Network Range Validations +- name: "VALIDATION 2: Verify L3 VNI Range was standardized to 50000-59000" + assert: + that: + - replaced_fabric_config.management.l3VniRange == "50000-59000" + fail_msg: "L3 VNI Range validation failed. Expected: 50000-59000, Actual: {{ replaced_fabric_config.management.l3VniRange }}" + success_msg: "✓ L3 VNI Range correctly standardized to 50000-59000" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify L2 VNI Range was standardized to 30000-49000" + assert: + that: + - replaced_fabric_config.management.l2VniRange == "30000-49000" + fail_msg: "L2 VNI Range validation failed. Expected: 30000-49000, Actual: {{ replaced_fabric_config.management.l2VniRange }}" + success_msg: "✓ L2 VNI Range correctly standardized to 30000-49000" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify BGP Loopback IP Range was standardized to 10.2.0.0/22" + assert: + that: + - replaced_fabric_config.management.bgpLoopbackIpRange == "10.2.0.0/22" + fail_msg: "BGP Loopback IP Range validation failed. Expected: 10.2.0.0/22, Actual: {{ replaced_fabric_config.management.bgpLoopbackIpRange }}" + success_msg: "✓ BGP Loopback IP Range correctly standardized to 10.2.0.0/22" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify NVE Loopback IP Range was standardized to 10.3.0.0/22" + assert: + that: + - replaced_fabric_config.management.nveLoopbackIpRange == "10.3.0.0/22" + fail_msg: "NVE Loopback IP Range validation failed. Expected: 10.3.0.0/22, Actual: {{ replaced_fabric_config.management.nveLoopbackIpRange }}" + success_msg: "✓ NVE Loopback IP Range correctly standardized to 10.3.0.0/22" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Intra-Fabric Subnet Range was standardized to 10.4.0.0/16" + assert: + that: + - replaced_fabric_config.management.intraFabricSubnetRange == "10.4.0.0/16" + fail_msg: "Intra-Fabric Subnet Range validation failed. Expected: 10.4.0.0/16, Actual: {{ replaced_fabric_config.management.intraFabricSubnetRange }}" + success_msg: "✓ Intra-Fabric Subnet Range correctly standardized to 10.4.0.0/16" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VRF Lite Subnet Range was standardized to 10.33.0.0/16" + assert: + that: + - replaced_fabric_config.management.vrfLiteSubnetRange == "10.33.0.0/16" + fail_msg: "VRF Lite Subnet Range validation failed. Expected: 10.33.0.0/16, Actual: {{ replaced_fabric_config.management.vrfLiteSubnetRange }}" + success_msg: "✓ VRF Lite Subnet Range correctly standardized to 10.33.0.0/16" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Anycast RP IP Range was standardized to 10.254.254.0/24" + assert: + that: + - replaced_fabric_config.management.anycastRendezvousPointIpRange == "10.254.254.0/24" + fail_msg: "Anycast RP IP Range validation failed. Expected: 10.254.254.0/24, Actual: {{ replaced_fabric_config.management.anycastRendezvousPointIpRange }}" + success_msg: "✓ Anycast RP IP Range correctly standardized to 10.254.254.0/24" + tags: [test_replaced, test_replaced_validation] + +# VLAN Range Validations +- name: "VALIDATION 2: Verify Network VLAN Range was standardized to 2300-2999" + assert: + that: + - replaced_fabric_config.management.networkVlanRange == "2300-2999" + fail_msg: "Network VLAN Range validation failed. Expected: 2300-2999, Actual: {{ replaced_fabric_config.management.networkVlanRange }}" + success_msg: "✓ Network VLAN Range correctly standardized to 2300-2999" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VRF VLAN Range was standardized to 2000-2299" + assert: + that: + - replaced_fabric_config.management.vrfVlanRange == "2000-2299" + fail_msg: "VRF VLAN Range validation failed. Expected: 2000-2299, Actual: {{ replaced_fabric_config.management.vrfVlanRange }}" + success_msg: "✓ VRF VLAN Range correctly standardized to 2000-2299" + tags: [test_replaced, test_replaced_validation] + +# MTU Validations +- name: "VALIDATION 2: Verify Fabric MTU was increased to 9216" + assert: + that: + - replaced_fabric_config.management.fabricMtu == 9216 + fail_msg: "Fabric MTU validation failed. Expected: 9216, Actual: {{ replaced_fabric_config.management.fabricMtu }}" + success_msg: "✓ Fabric MTU correctly increased to 9216" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify L2 Host Interface MTU was increased to 9216" + assert: + that: + - replaced_fabric_config.management.l2HostInterfaceMtu == 9216 + fail_msg: "L2 Host Interface MTU validation failed. Expected: 9216, Actual: {{ replaced_fabric_config.management.l2HostInterfaceMtu }}" + success_msg: "✓ L2 Host Interface MTU correctly increased to 9216" + tags: [test_replaced, test_replaced_validation] + +# Gateway and Multicast Validations +- name: "VALIDATION 2: Verify Anycast Gateway MAC was standardized to 2020.0000.00aa" + assert: + that: + - replaced_fabric_config.management.anycastGatewayMac == "2020.0000.00aa" + fail_msg: "Anycast Gateway MAC validation failed. Expected: 2020.0000.00aa, Actual: {{ replaced_fabric_config.management.anycastGatewayMac }}" + success_msg: "✓ Anycast Gateway MAC correctly standardized to 2020.0000.00aa" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Multicast Group Subnet was standardized to 239.1.1.0/25" + assert: + that: + - replaced_fabric_config.management.multicastGroupSubnet == "239.1.1.0/25" + fail_msg: "Multicast Group Subnet validation failed. Expected: 239.1.1.0/25, Actual: {{ replaced_fabric_config.management.multicastGroupSubnet }}" + success_msg: "✓ Multicast Group Subnet correctly standardized to 239.1.1.0/25" + tags: [test_replaced, test_replaced_validation] + +# VPC Configuration Validations +- name: "VALIDATION 2: Verify VPC Auto Recovery Timer was standardized to 360" + assert: + that: + - replaced_fabric_config.management.vpcAutoRecoveryTimer == 360 + fail_msg: "VPC Auto Recovery Timer validation failed. Expected: 360, Actual: {{ replaced_fabric_config.management.vpcAutoRecoveryTimer }}" + success_msg: "✓ VPC Auto Recovery Timer correctly standardized to 360" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VPC Delay Restore Timer was standardized to 150" + assert: + that: + - replaced_fabric_config.management.vpcDelayRestoreTimer == 150 + fail_msg: "VPC Delay Restore Timer validation failed. Expected: 150, Actual: {{ replaced_fabric_config.management.vpcDelayRestoreTimer }}" + success_msg: "✓ VPC Delay Restore Timer correctly standardized to 150" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VPC Peer Link Port Channel ID was standardized to 500" + assert: + that: + - replaced_fabric_config.management.vpcPeerLinkPortChannelId == "500" + fail_msg: "VPC Peer Link Port Channel ID validation failed. Expected: 500, Actual: {{ replaced_fabric_config.management.vpcPeerLinkPortChannelId }}" + success_msg: "✓ VPC Peer Link Port Channel ID correctly standardized to 500" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VPC Peer Link VLAN was standardized to 3600" + assert: + that: + - replaced_fabric_config.management.vpcPeerLinkVlan == "3600" + fail_msg: "VPC Peer Link VLAN validation failed. Expected: 3600, Actual: {{ replaced_fabric_config.management.vpcPeerLinkVlan }}" + success_msg: "✓ VPC Peer Link VLAN correctly standardized to 3600" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VPC Domain ID Range was standardized to 1-1000" + assert: + that: + - replaced_fabric_config.management.vpcDomainIdRange == "1-1000" + fail_msg: "VPC Domain ID Range validation failed. Expected: 1-1000, Actual: {{ replaced_fabric_config.management.vpcDomainIdRange }}" + success_msg: "✓ VPC Domain ID Range correctly standardized to 1-1000" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify VPC IPv6 Neighbor Discovery Sync was enabled" + assert: + that: + - replaced_fabric_config.management.vpcIpv6NeighborDiscoverySync == true + fail_msg: "VPC IPv6 Neighbor Discovery Sync validation failed. Expected: true, Actual: {{ replaced_fabric_config.management.vpcIpv6NeighborDiscoverySync }}" + success_msg: "✓ VPC IPv6 Neighbor Discovery Sync correctly enabled" + tags: [test_replaced, test_replaced_validation] + +# Multicast Settings Validations +- name: "VALIDATION 2: Verify Rendezvous Point Count was standardized to 2" + assert: + that: + - replaced_fabric_config.management.rendezvousPointCount == 2 + fail_msg: "Rendezvous Point Count validation failed. Expected: 2, Actual: {{ replaced_fabric_config.management.rendezvousPointCount }}" + success_msg: "✓ Rendezvous Point Count correctly standardized to 2" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Rendezvous Point Loopback ID was standardized to 254" + assert: + that: + - replaced_fabric_config.management.rendezvousPointLoopbackId == 254 + fail_msg: "Rendezvous Point Loopback ID validation failed. Expected: 254, Actual: {{ replaced_fabric_config.management.rendezvousPointLoopbackId }}" + success_msg: "✓ Rendezvous Point Loopback ID correctly standardized to 254" + tags: [test_replaced, test_replaced_validation] + +# Feature Flag Validations +- name: "VALIDATION 2: Verify TCAM Allocation was enabled" + assert: + that: + - replaced_fabric_config.management.tcamAllocation == true + fail_msg: "TCAM Allocation validation failed. Expected: true, Actual: {{ replaced_fabric_config.management.tcamAllocation }}" + success_msg: "✓ TCAM Allocation correctly enabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Real Time Interface Statistics Collection was disabled" + assert: + that: + - replaced_fabric_config.management.realTimeInterfaceStatisticsCollection == false + fail_msg: "Real Time Interface Statistics Collection validation failed. Expected: false, Actual: {{ replaced_fabric_config.management.realTimeInterfaceStatisticsCollection }}" + success_msg: "✓ Real Time Interface Statistics Collection correctly disabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Performance Monitoring was disabled" + assert: + that: + - replaced_fabric_config.management.performanceMonitoring == false + fail_msg: "Performance Monitoring validation failed. Expected: false, Actual: {{ replaced_fabric_config.management.performanceMonitoring }}" + success_msg: "✓ Performance Monitoring correctly disabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Tenant DHCP was enabled" + assert: + that: + - replaced_fabric_config.management.tenantDhcp == true + fail_msg: "Tenant DHCP validation failed. Expected: true, Actual: {{ replaced_fabric_config.management.tenantDhcp }}" + success_msg: "✓ Tenant DHCP correctly enabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify SNMP Trap was enabled" + assert: + that: + - replaced_fabric_config.management.snmpTrap == true + fail_msg: "SNMP Trap validation failed. Expected: true, Actual: {{ replaced_fabric_config.management.snmpTrap }}" + success_msg: "✓ SNMP Trap correctly enabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Greenfield Debug Flag was disabled" + assert: + that: + - replaced_fabric_config.management.greenfieldDebugFlag == "disable" + fail_msg: "Greenfield Debug Flag validation failed. Expected: disable, Actual: {{ replaced_fabric_config.management.greenfieldDebugFlag }}" + success_msg: "✓ Greenfield Debug Flag correctly disabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify NXAPI HTTP was enabled" + assert: + that: + - replaced_fabric_config.management.nxapiHttp == true + fail_msg: "NXAPI HTTP validation failed. Expected: true, Actual: {{ replaced_fabric_config.management.nxapiHttp }}" + success_msg: "✓ NXAPI HTTP correctly enabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify NXAPI was disabled" + assert: + that: + - replaced_fabric_config.management.nxapi == false + fail_msg: "NXAPI validation failed. Expected: false, Actual: {{ replaced_fabric_config.management.nxapi }}" + success_msg: "✓ NXAPI correctly disabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Per VRF Loopback Auto Provision was disabled" + assert: + that: + - replaced_fabric_config.management.perVrfLoopbackAutoProvision == false + fail_msg: "Per VRF Loopback Auto Provision validation failed. Expected: false, Actual: {{ replaced_fabric_config.management.perVrfLoopbackAutoProvision }}" + success_msg: "✓ Per VRF Loopback Auto Provision correctly disabled" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Verify Per VRF Loopback Auto Provision IPv6 was disabled" + assert: + that: + - replaced_fabric_config.management.perVrfLoopbackAutoProvisionIpv6 == false + fail_msg: "Per VRF Loopback Auto Provision IPv6 validation failed. Expected: false, Actual: {{ replaced_fabric_config.management.perVrfLoopbackAutoProvisionIpv6 }}" + success_msg: "✓ Per VRF Loopback Auto Provision IPv6 correctly disabled" + tags: [test_replaced, test_replaced_validation] + +# Verify banner was preserved +- name: "VALIDATION 2: Verify Banner was preserved" + assert: + that: + - replaced_fabric_config.management.banner == "^ Updated via replaced state ^" + fail_msg: "Banner validation failed. Expected: '^ Updated via replaced state ^', Actual: {{ replaced_fabric_config.management.banner }}" + success_msg: "✓ Banner correctly preserved: '{{ replaced_fabric_config.management.banner }}'" + tags: [test_replaced, test_replaced_validation] + +- name: "VALIDATION 2: Display successful validation summary for test_fabric_replaced" + debug: + msg: | + ======================================== + VALIDATION SUMMARY for test_fabric_replaced: + ======================================== + Network Ranges: + ✓ L3 VNI Range: {{ replaced_fabric_config.management.l3VniRange }} + ✓ L2 VNI Range: {{ replaced_fabric_config.management.l2VniRange }} + ✓ BGP Loopback IP Range: {{ replaced_fabric_config.management.bgpLoopbackIpRange }} + ✓ NVE Loopback IP Range: {{ replaced_fabric_config.management.nveLoopbackIpRange }} + ✓ Intra-Fabric Subnet Range: {{ replaced_fabric_config.management.intraFabricSubnetRange }} + ✓ VRF Lite Subnet Range: {{ replaced_fabric_config.management.vrfLiteSubnetRange }} + ✓ Anycast RP IP Range: {{ replaced_fabric_config.management.anycastRendezvousPointIpRange }} + + VLAN Ranges: + ✓ Network VLAN Range: {{ replaced_fabric_config.management.networkVlanRange }} + ✓ VRF VLAN Range: {{ replaced_fabric_config.management.vrfVlanRange }} + + MTU Settings: + ✓ Fabric MTU: {{ replaced_fabric_config.management.fabricMtu }} + ✓ L2 Host Interface MTU: {{ replaced_fabric_config.management.l2HostInterfaceMtu }} + + VPC Configuration: + ✓ VPC Auto Recovery Timer: {{ replaced_fabric_config.management.vpcAutoRecoveryTimer }} + ✓ VPC Delay Restore Timer: {{ replaced_fabric_config.management.vpcDelayRestoreTimer }} + ✓ VPC Peer Link Port Channel ID: {{ replaced_fabric_config.management.vpcPeerLinkPortChannelId }} + ✓ VPC Peer Link VLAN: {{ replaced_fabric_config.management.vpcPeerLinkVlan }} + ✓ VPC Domain ID Range: {{ replaced_fabric_config.management.vpcDomainIdRange }} + ✓ VPC IPv6 Neighbor Discovery Sync: {{ replaced_fabric_config.management.vpcIpv6NeighborDiscoverySync }} + + Gateway & Multicast: + ✓ Anycast Gateway MAC: {{ replaced_fabric_config.management.anycastGatewayMac }} + ✓ Multicast Group Subnet: {{ replaced_fabric_config.management.multicastGroupSubnet }} + ✓ Rendezvous Point Count: {{ replaced_fabric_config.management.rendezvousPointCount }} + ✓ Rendezvous Point Loopback ID: {{ replaced_fabric_config.management.rendezvousPointLoopbackId }} + + Feature Flags: + ✓ TCAM Allocation: {{ replaced_fabric_config.management.tcamAllocation }} + ✓ Real Time Interface Statistics Collection: {{ replaced_fabric_config.management.realTimeInterfaceStatisticsCollection }} + ✓ Performance Monitoring: {{ replaced_fabric_config.management.performanceMonitoring }} + ✓ Tenant DHCP: {{ replaced_fabric_config.management.tenantDhcp }} + ✓ SNMP Trap: {{ replaced_fabric_config.management.snmpTrap }} + ✓ Greenfield Debug Flag: {{ replaced_fabric_config.management.greenfieldDebugFlag }} + ✓ NXAPI HTTP: {{ replaced_fabric_config.management.nxapiHttp }} + ✓ NXAPI: {{ replaced_fabric_config.management.nxapi }} + + Auto-Provisioning: + ✓ Per VRF Loopback Auto Provision: {{ replaced_fabric_config.management.perVrfLoopbackAutoProvision }} + ✓ Per VRF Loopback Auto Provision IPv6: {{ replaced_fabric_config.management.perVrfLoopbackAutoProvisionIpv6 }} + + Preserved Settings: + ✓ Banner: "{{ replaced_fabric_config.management.banner }}" + + All 30+ expected changes validated successfully! + ======================================== + tags: [test_replaced, test_replaced_validation] + +# - name: "PAUSE: Review TEST 2c results before continuing" +# ansible.builtin.pause: +# prompt: "TEST 2c complete. Review results and press Enter to continue, or Ctrl+C then A to abort" +# tags: [test_replaced, test_replaced_idempotent] + +############################################################################# +# TEST 3: Demonstrate difference between merged and replaced states +############################################################################# +- name: "TEST 3: Create fabric for merged vs replaced comparison" + cisco.nd.nd_manage_fabric_ibgp: + state: replaced + config: + - "{{ {'name': test_fabric_deleted} | combine(common_fabric_config) }}" + register: comparison_fabric_creation + tags: [test_comparison] + +- name: "TEST 3a: Partial update using merged state (should merge changes)" + cisco.nd.nd_manage_fabric_ibgp: + state: merged + config: + - name: "{{ test_fabric_deleted }}" + category: fabric + management: + bgp_asn: "65099" # Only updating ASN + fabric_mtu: 8000 # Only updating MTU + register: merged_partial_result + tags: [test_comparison, test_merged_partial] + +- name: "TEST 3a: Verify merged state preserves existing configuration" + assert: + that: + - merged_partial_result is changed + - merged_partial_result is not failed + fail_msg: "Partial update with merged state failed" + success_msg: "Merged state successfully performed partial update" + tags: [test_comparison, test_merged_partial] + +- name: "TEST 3b: Partial update using replaced state (should replace entire config)" + cisco.nd.nd_manage_fabric_ibgp: + state: replaced + config: + - name: "{{ test_fabric_deleted }}" + category: fabric + management: + type: vxlanIbgp + bgp_asn: "65100" # Only specifying minimal config for replaced + target_subnet_mask: 30 + register: replaced_partial_result + tags: [test_comparison, test_replaced_partial] + +- name: "TEST 3b: Verify replaced state performs complete replacement" + assert: + that: + - replaced_partial_result is changed + - replaced_partial_result is not failed + fail_msg: "Partial replacement with replaced state failed" + success_msg: "Replaced state successfully performed complete replacement" + tags: [test_comparison, test_replaced_partial] + +############################################################################# +# TEST 4: STATE DELETED - Delete fabrics +############################################################################# +- name: "TEST 4a: Delete fabric using state deleted" + cisco.nd.nd_manage_fabric_ibgp: + state: deleted + config: + - name: "{{ test_fabric_deleted }}" + register: deleted_result_1 + tags: [test_deleted, test_deleted_delete] + +- name: "TEST 4a: Verify fabric was deleted" + assert: + that: + - deleted_result_1 is changed + - deleted_result_1 is not failed + fail_msg: "Fabric deletion with state deleted failed" + success_msg: "Fabric successfully deleted with state deleted" + tags: [test_deleted, test_deleted_delete] + +- name: "TEST 4b: Delete fabric using state deleted (second run - idempotency test)" + cisco.nd.nd_manage_fabric_ibgp: + state: deleted + config: + - name: "{{ test_fabric_deleted }}" + register: deleted_result_2 + tags: [test_deleted, test_deleted_idempotent] + +- name: "TEST 4b: Verify deleted state is idempotent" + assert: + that: + - deleted_result_2 is not changed + - deleted_result_2 is not failed + fail_msg: "Deleted state is not idempotent - should not change when deleting non-existent fabric" + success_msg: "Deleted state is idempotent - no changes when deleting non-existent fabric" + tags: [test_deleted, test_deleted_idempotent] + +############################################################################# +# TEST 5: Multiple fabric operations in single task +############################################################################# +- name: "TEST 5: Multiple fabric operations in single task" + cisco.nd.nd_manage_fabric_ibgp: + state: merged + config: + - name: "multi_fabric_1" + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanIbgp + bgp_asn: "65101" + site_id: "65101" + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.0001" + performance_monitoring: false + replication_mode: multicast + multicast_group_subnet: "239.1.1.0/25" + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 2 + rendezvous_point_loopback_id: 254 + vpc_peer_link_vlan: "3600" + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: loopback + vpc_auto_recovery_timer: 360 + vpc_delay_restore_timer: 150 + vpc_peer_link_port_channel_id: "500" + # vpc_ipv6_neighbor_discovery_sync: true + advertise_physical_ip: false + vpc_domain_id_range: "1-1000" + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9216 + l2_host_interface_mtu: 9216 + tenant_dhcp: true + nxapi: true + nxapi_https_port: 443 + nxapi_http: false + nxapi_http_port: 80 + snmp_trap: true + anycast_border_gateway_advertise_physical_ip: false + greenfield_debug_flag: enable + tcam_allocation: true + real_time_interface_statistics_collection: false + interface_statistics_load_interval: 10 + bgp_loopback_ip_range: "10.101.0.0/22" + nve_loopback_ip_range: "10.103.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.101.0/24" + intra_fabric_subnet_range: "10.104.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.133.0.0/16" + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.105.0.0/22" + # per_vrf_loopback_auto_provision_ipv6: false + # per_vrf_loopback_ipv6_range: "fd00::a105:0/112" + banner: "" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + # management_ipv6_prefix: 64 + - name: "multi_fabric_2" + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanIbgp + bgp_asn: "65102" + site_id: "65102" + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.0002" + performance_monitoring: false + replication_mode: multicast + multicast_group_subnet: "239.1.1.0/25" + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 2 + rendezvous_point_loopback_id: 254 + vpc_peer_link_vlan: "3600" + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: loopback + vpc_auto_recovery_timer: 360 + vpc_delay_restore_timer: 150 + vpc_peer_link_port_channel_id: "500" + # vpc_ipv6_neighbor_discovery_sync: true + advertise_physical_ip: false + vpc_domain_id_range: "1-1000" + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9216 + l2_host_interface_mtu: 9216 + tenant_dhcp: true + nxapi: true + nxapi_https_port: 443 + nxapi_http: false + nxapi_http_port: 80 + snmp_trap: true + anycast_border_gateway_advertise_physical_ip: false + greenfield_debug_flag: enable + tcam_allocation: true + real_time_interface_statistics_collection: false + interface_statistics_load_interval: 10 + bgp_loopback_ip_range: "10.102.0.0/22" + nve_loopback_ip_range: "10.103.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.102.0/24" + intra_fabric_subnet_range: "10.104.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.134.0.0/16" + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.106.0.0/22" + # per_vrf_loopback_auto_provision_ipv6: false + # per_vrf_loopback_ipv6_range: "fd00::a106:0/112" + banner: "" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + # management_ipv6_prefix: 64 + register: multi_fabric_result + tags: [test_multi, test_multi_create] + +- name: "TEST 5: Verify multiple fabrics were created" + assert: + that: + - multi_fabric_result is changed + - multi_fabric_result is not failed + fail_msg: "Multiple fabric creation failed" + success_msg: "Multiple fabrics successfully created" + tags: [test_multi, test_multi_create] + +############################################################################# +# FINAL CLEANUP - Clean up all test fabrics +############################################################################# +- name: "CLEANUP: Delete all test fabrics" + cisco.nd.nd_manage_fabric_ibgp: + state: deleted + config: + - name: "{{ test_fabric_merged }}" + - name: "{{ test_fabric_replaced }}" + - name: "{{ test_fabric_deleted }}" + - name: "multi_fabric_1" + - name: "multi_fabric_2" + ignore_errors: true + tags: [cleanup, always] + +############################################################################# +# TEST SUMMARY +############################################################################# +- name: "TEST SUMMARY: Display test results" + debug: + msg: | + ======================================================== + TEST SUMMARY for cisco.nd.nd_manage_fabric_ibgp module: + ======================================================== + ✓ TEST 1: STATE MERGED + - Create fabric: {{ 'PASSED' if merged_result_1 is changed else 'FAILED' }} + - Idempotency: {{ 'PASSED' if merged_result_2 is not changed else 'FAILED' }} + - Update fabric: {{ 'PASSED' if merged_result_3 is changed else 'FAILED' }} + + ✓ TEST 2: STATE REPLACED + - Create fabric: {{ 'PASSED' if replaced_result_1 is changed else 'FAILED' }} + - Idempotency: {{ 'PASSED' if replaced_result_2 is not changed else 'FAILED' }} + - Replace fabric: {{ 'PASSED' if replaced_result_3 is changed else 'FAILED' }} + + ✓ TEST 3: MERGED vs REPLACED Comparison + - Merged partial: {{ 'PASSED' if merged_partial_result is changed else 'FAILED' }} + - Replaced partial: {{ 'PASSED' if replaced_partial_result is changed else 'FAILED' }} + + ✓ TEST 4: STATE DELETED + - Delete fabric: {{ 'PASSED' if deleted_result_1 is changed else 'FAILED' }} + - Idempotency: {{ 'PASSED' if deleted_result_2 is not changed else 'FAILED' }} + + ✓ TEST 5: MULTIPLE FABRICS + - Multi-create: {{ 'PASSED' if multi_fabric_result is changed else 'FAILED' }} + + All tests validate: + - State merged: Creates and updates fabrics by merging changes + - State replaced: Creates and completely replaces fabric configuration + - State deleted: Removes fabrics + - Idempotency: All operations are idempotent when run multiple times + - Difference: Merged preserves existing config, replaced overwrites completely + ======================================== + tags: [summary, always] \ No newline at end of file diff --git a/tests/integration/targets/nd_manage_fabric/tasks/main.yaml b/tests/integration/targets/nd_manage_fabric/tasks/main.yaml new file mode 100644 index 00000000..77d2f524 --- /dev/null +++ b/tests/integration/targets/nd_manage_fabric/tasks/main.yaml @@ -0,0 +1,6 @@ +--- +- name: Run nd_manage_fabric iBGP tests + ansible.builtin.include_tasks: fabric_ibgp.yaml + +- name: Run nd_manage_fabric eBGP tests + ansible.builtin.include_tasks: fabric_ebgp.yaml diff --git a/tests/integration/targets/nd_manage_fabric/vars/main.yaml b/tests/integration/targets/nd_manage_fabric/vars/main.yaml new file mode 100644 index 00000000..61304ace --- /dev/null +++ b/tests/integration/targets/nd_manage_fabric/vars/main.yaml @@ -0,0 +1,166 @@ +--- + +test_fabric_merged: "ibgp_test_fabric_merged" +test_fabric_replaced: "ibgp_test_fabric_replaced" +test_fabric_deleted: "ibgp_test_fabric_deleted" + +ebgp_test_fabric_merged: "ebgp_test_fabric_merged" +ebgp_test_fabric_replaced: "ebgp_test_fabric_replaced" +ebgp_test_fabric_deleted: "ebgp_test_fabric_deleted" + +# Common fabric configuration for all tests +common_fabric_config: + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanIbgp + bgp_asn: "65001.55" + site_id: "65001" + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00aa" + performance_monitoring: false + replication_mode: multicast + multicast_group_subnet: "239.1.1.0/25" + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 2 + rendezvous_point_loopback_id: 254 + vpc_peer_link_vlan: "3600" + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: loopback + vpc_auto_recovery_timer: 360 + vpc_delay_restore_timer: 150 + vpc_peer_link_port_channel_id: "500" + advertise_physical_ip: false + vpc_domain_id_range: "1-1000" + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9216 + l2_host_interface_mtu: 9216 + tenant_dhcp: true + nxapi: true + nxapi_https_port: 443 + nxapi_http: false + nxapi_http_port: 80 + snmp_trap: true + anycast_border_gateway_advertise_physical_ip: false + greenfield_debug_flag: enable + tcam_allocation: true + real_time_interface_statistics_collection: false + interface_statistics_load_interval: 10 + bgp_loopback_ip_range: "10.2.0.0/22" + nve_loopback_ip_range: "10.3.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.254.0/24" + intra_fabric_subnet_range: "10.4.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.33.0.0/16" + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.5.0.0/22" + banner: "" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 + +# Common eBGP fabric configuration for all eBGP tests +common_ebgp_fabric_config: + category: fabric + location: + latitude: 37.7749 + longitude: -122.4194 + license_tier: premier + alert_suspend: disabled + security_domain: all + telemetry_collection: false + management: + type: vxlanEbgp + bgp_asn: "65001" + bgp_asn_auto_allocation: false + site_id: "65001" + bgp_as_mode: multiAS + bgp_allow_as_in_num: 1 + bgp_max_path: 4 + auto_configure_ebgp_evpn_peering: true + target_subnet_mask: 30 + anycast_gateway_mac: "2020.0000.00aa" + performance_monitoring: false + replication_mode: multicast + multicast_group_subnet: "239.1.1.0/25" + auto_generate_multicast_group_address: false + underlay_multicast_group_address_limit: 128 + tenant_routed_multicast: false + rendezvous_point_count: 2 + rendezvous_point_loopback_id: 254 + vpc_peer_link_vlan: "3600" + vpc_peer_link_enable_native_vlan: false + vpc_peer_keep_alive_option: management + vpc_auto_recovery_timer: 360 + vpc_delay_restore_timer: 150 + vpc_peer_link_port_channel_id: "500" + advertise_physical_ip: false + vpc_domain_id_range: "1-1000" + bgp_loopback_id: 0 + nve_loopback_id: 1 + vrf_template: Default_VRF_Universal + network_template: Default_Network_Universal + vrf_extension_template: Default_VRF_Extension_Universal + network_extension_template: Default_Network_Extension_Universal + l3_vni_no_vlan_default_option: false + fabric_mtu: 9216 + l2_host_interface_mtu: 9216 + tenant_dhcp: true + nxapi: false + nxapi_https_port: 443 + nxapi_http: false + nxapi_http_port: 80 + snmp_trap: true + anycast_border_gateway_advertise_physical_ip: false + greenfield_debug_flag: disable + tcam_allocation: true + real_time_interface_statistics_collection: false + interface_statistics_load_interval: 10 + bgp_loopback_ip_range: "10.2.0.0/22" + nve_loopback_ip_range: "10.3.0.0/22" + anycast_rendezvous_point_ip_range: "10.254.254.0/24" + intra_fabric_subnet_range: "10.4.0.0/16" + l2_vni_range: "30000-49000" + l3_vni_range: "50000-59000" + network_vlan_range: "2300-2999" + vrf_vlan_range: "2000-2299" + sub_interface_dot1q_range: "2-511" + vrf_lite_auto_config: manual + vrf_lite_subnet_range: "10.33.0.0/16" + vrf_lite_subnet_target_mask: 30 + auto_unique_vrf_lite_ip_prefix: false + per_vrf_loopback_auto_provision: true + per_vrf_loopback_ip_range: "10.5.0.0/22" + banner: "" + day0_bootstrap: false + local_dhcp_server: false + dhcp_protocol_version: dhcpv4 + dhcp_start_address: "" + dhcp_end_address: "" + management_gateway: "" + management_ipv4_prefix: 24 diff --git a/tests/unit/module_utils/endpoints/test_base_model.py b/tests/unit/module_utils/endpoints/test_base_model.py index a14da9d8..ce9d1e8d 100644 --- a/tests/unit/module_utils/endpoints/test_base_model.py +++ b/tests/unit/module_utils/endpoints/test_base_model.py @@ -99,7 +99,6 @@ def test_base_model_00200(): with pytest.raises(TypeError, match=match): class _BadEndpoint(NDEndpointBaseModel): - @property def path(self) -> str: return "/api/v1/test/bad" @@ -132,7 +131,6 @@ def test_base_model_00300(): """ class _MiddleABC(NDEndpointBaseModel, ABC): - @property @abstractmethod def extra(self) -> str: @@ -182,7 +180,6 @@ def test_base_model_00310(): """ class _MiddleABC2(NDEndpointBaseModel, ABC): - @property @abstractmethod def extra(self) -> str: @@ -192,7 +189,6 @@ def extra(self) -> str: with pytest.raises(TypeError, match=match): class _BadConcreteFromMiddle(_MiddleABC2): - @property def path(self) -> str: return "/api/v1/test/bad-middle" @@ -229,7 +225,6 @@ def test_base_model_00400(): with pytest.raises(TypeError, match=r'Literal\["_ExampleEndpoint"\]') as exc_info: class _ExampleEndpoint(NDEndpointBaseModel): - @property def path(self) -> str: return "/api/v1/test/example" diff --git a/tests/unit/module_utils/endpoints/test_endpoints_api_v1_infra_aaa_local_users.py b/tests/unit/module_utils/endpoints/test_endpoints_api_v1_infra_aaa_local_users.py new file mode 100644 index 00000000..71cfd9b6 --- /dev/null +++ b/tests/unit/module_utils/endpoints/test_endpoints_api_v1_infra_aaa_local_users.py @@ -0,0 +1,437 @@ +# Copyright: (c) 2026, Allen Robel (@arobel) + +# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) + +""" +Unit tests for infra_aaa_local_users.py + +Tests the ND Infra AAA endpoint classes +""" + +from __future__ import absolute_import, annotations, division, print_function + +# pylint: disable=invalid-name +__metaclass__ = type +# pylint: enable=invalid-name + +import pytest # pylint: disable=unused-import +from ansible_collections.cisco.nd.plugins.module_utils.endpoints.v1.infra.aaa_local_users import ( + EpInfraAaaLocalUsersDelete, + EpInfraAaaLocalUsersGet, + EpInfraAaaLocalUsersPost, + EpInfraAaaLocalUsersPut, +) +from ansible_collections.cisco.nd.plugins.module_utils.enums import HttpVerbEnum +from ansible_collections.cisco.nd.tests.unit.module_utils.common_utils import ( + does_not_raise, +) + +# ============================================================================= +# Test: EpInfraAaaLocalUsersGet +# ============================================================================= + + +def test_endpoints_api_v1_infra_aaa_00010(): + """ + # Summary + + Verify EpInfraAaaLocalUsersGet basic instantiation + + ## Test + + - Instance can be created + - class_name is set correctly + - verb is GET + + ## Classes and Methods + + - EpInfraAaaLocalUsersGet.__init__() + - EpInfraAaaLocalUsersGet.verb + - EpInfraAaaLocalUsersGet.class_name + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersGet() + assert instance.class_name == "EpInfraAaaLocalUsersGet" + assert instance.verb == HttpVerbEnum.GET + + +def test_endpoints_api_v1_infra_aaa_00020(): + """ + # Summary + + Verify EpInfraAaaLocalUsersGet path without login_id + + ## Test + + - path returns "/api/v1/infra/aaa/localUsers" when login_id is None + + ## Classes and Methods + + - EpInfraAaaLocalUsersGet.path + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersGet() + result = instance.path + assert result == "/api/v1/infra/aaa/localUsers" + + +def test_endpoints_api_v1_infra_aaa_00030(): + """ + # Summary + + Verify EpInfraAaaLocalUsersGet path with login_id + + ## Test + + - path returns "/api/v1/infra/aaa/localUsers/admin" when login_id is set + + ## Classes and Methods + + - EpInfraAaaLocalUsersGet.path + - EpInfraAaaLocalUsersGet.login_id + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersGet() + instance.login_id = "admin" + result = instance.path + assert result == "/api/v1/infra/aaa/localUsers/admin" + + +def test_endpoints_api_v1_infra_aaa_00040(): + """ + # Summary + + Verify EpInfraAaaLocalUsersGet login_id can be set at instantiation + + ## Test + + - login_id can be provided during instantiation + + ## Classes and Methods + + - EpInfraAaaLocalUsersGet.__init__() + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersGet(login_id="testuser") + assert instance.login_id == "testuser" + assert instance.path == "/api/v1/infra/aaa/localUsers/testuser" + + +# ============================================================================= +# Test: EpInfraAaaLocalUsersPost +# ============================================================================= + + +def test_endpoints_api_v1_infra_aaa_00100(): + """ + # Summary + + Verify EpInfraAaaLocalUsersPost basic instantiation + + ## Test + + - Instance can be created + - class_name is set correctly + - verb is POST + + ## Classes and Methods + + - EpInfraAaaLocalUsersPost.__init__() + - EpInfraAaaLocalUsersPost.verb + - EpInfraAaaLocalUsersPost.class_name + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersPost() + assert instance.class_name == "EpInfraAaaLocalUsersPost" + assert instance.verb == HttpVerbEnum.POST + + +def test_endpoints_api_v1_infra_aaa_00110(): + """ + # Summary + + Verify EpInfraAaaLocalUsersPost path + + ## Test + + - path returns "/api/v1/infra/aaa/localUsers" for POST + + ## Classes and Methods + + - EpInfraAaaLocalUsersPost.path + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersPost() + result = instance.path + assert result == "/api/v1/infra/aaa/localUsers" + + +def test_endpoints_api_v1_infra_aaa_00120(): + """ + # Summary + + Verify EpInfraAaaLocalUsersPost path with login_id + + ## Test + + - path returns "/api/v1/infra/aaa/localUsers/admin" when login_id is set + + ## Classes and Methods + + - EpInfraAaaLocalUsersPost.path + - EpInfraAaaLocalUsersPost.login_id + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersPost() + instance.login_id = "admin" + result = instance.path + assert result == "/api/v1/infra/aaa/localUsers/admin" + + +# ============================================================================= +# Test: EpInfraAaaLocalUsersPut +# ============================================================================= + + +def test_endpoints_api_v1_infra_aaa_00200(): + """ + # Summary + + Verify EpInfraAaaLocalUsersPut basic instantiation + + ## Test + + - Instance can be created + - class_name is set correctly + - verb is PUT + + ## Classes and Methods + + - EpInfraAaaLocalUsersPut.__init__() + - EpInfraAaaLocalUsersPut.verb + - EpInfraAaaLocalUsersPut.class_name + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersPut() + assert instance.class_name == "EpInfraAaaLocalUsersPut" + assert instance.verb == HttpVerbEnum.PUT + + +def test_endpoints_api_v1_infra_aaa_00210(): + """ + # Summary + + Verify EpInfraAaaLocalUsersPut path with login_id + + ## Test + + - path returns "/api/v1/infra/aaa/localUsers/admin" when login_id is set + + ## Classes and Methods + + - EpInfraAaaLocalUsersPut.path + - EpInfraAaaLocalUsersPut.login_id + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersPut() + instance.login_id = "admin" + result = instance.path + assert result == "/api/v1/infra/aaa/localUsers/admin" + + +def test_endpoints_api_v1_infra_aaa_00220(): + """ + # Summary + + Verify EpInfraAaaLocalUsersPut with complex login_id + + ## Test + + - login_id with special characters is handled correctly + + ## Classes and Methods + + - EpInfraAaaLocalUsersPut.path + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersPut(login_id="user-name_123") + assert instance.path == "/api/v1/infra/aaa/localUsers/user-name_123" + + +# ============================================================================= +# Test: EpInfraAaaLocalUsersDelete +# ============================================================================= + + +def test_endpoints_api_v1_infra_aaa_00300(): + """ + # Summary + + Verify EpInfraAaaLocalUsersDelete basic instantiation + + ## Test + + - Instance can be created + - class_name is set correctly + - verb is DELETE + + ## Classes and Methods + + - EpInfraAaaLocalUsersDelete.__init__() + - EpInfraAaaLocalUsersDelete.verb + - EpInfraAaaLocalUsersDelete.class_name + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersDelete() + assert instance.class_name == "EpInfraAaaLocalUsersDelete" + assert instance.verb == HttpVerbEnum.DELETE + + +def test_endpoints_api_v1_infra_aaa_00310(): + """ + # Summary + + Verify EpInfraAaaLocalUsersDelete path with login_id + + ## Test + + - path returns "/api/v1/infra/aaa/localUsers/admin" when login_id is set + + ## Classes and Methods + + - EpInfraAaaLocalUsersDelete.path + - EpInfraAaaLocalUsersDelete.login_id + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersDelete() + instance.login_id = "admin" + result = instance.path + assert result == "/api/v1/infra/aaa/localUsers/admin" + + +def test_endpoints_api_v1_infra_aaa_00320(): + """ + # Summary + + Verify EpInfraAaaLocalUsersDelete without login_id + + ## Test + + - path returns base path when login_id is None + + ## Classes and Methods + + - EpInfraAaaLocalUsersDelete.path + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersDelete() + result = instance.path + assert result == "/api/v1/infra/aaa/localUsers" + + +# ============================================================================= +# Test: All HTTP methods on same endpoint +# ============================================================================= + + +def test_endpoints_api_v1_infra_aaa_00400(): + """ + # Summary + + Verify all HTTP methods work correctly on same resource + + ## Test + + - GET, POST, PUT, DELETE all return correct paths for same login_id + + ## Classes and Methods + + - EpInfraAaaLocalUsersGet + - EpInfraAaaLocalUsersPost + - EpInfraAaaLocalUsersPut + - EpInfraAaaLocalUsersDelete + """ + login_id = "testuser" + + with does_not_raise(): + get_ep = EpInfraAaaLocalUsersGet(login_id=login_id) + post_ep = EpInfraAaaLocalUsersPost(login_id=login_id) + put_ep = EpInfraAaaLocalUsersPut(login_id=login_id) + delete_ep = EpInfraAaaLocalUsersDelete(login_id=login_id) + + # All should have same path when login_id is set + expected_path = "/api/v1/infra/aaa/localUsers/testuser" + assert get_ep.path == expected_path + assert post_ep.path == expected_path + assert put_ep.path == expected_path + assert delete_ep.path == expected_path + + # But different verbs + assert get_ep.verb == HttpVerbEnum.GET + assert post_ep.verb == HttpVerbEnum.POST + assert put_ep.verb == HttpVerbEnum.PUT + assert delete_ep.verb == HttpVerbEnum.DELETE + + +# ============================================================================= +# Test: Pydantic validation +# ============================================================================= + + +def test_endpoints_api_v1_infra_aaa_00500(): + """ + # Summary + + Verify Pydantic validation for login_id + + ## Test + + - Empty string is rejected for login_id (min_length=1) + + ## Classes and Methods + + - EpInfraAaaLocalUsersGet.__init__() + """ + with pytest.raises(ValueError): + EpInfraAaaLocalUsersGet(login_id="") + + +def test_endpoints_api_v1_infra_aaa_00510(): + """ + # Summary + + Verify login_id can be None + + ## Test + + - login_id accepts None as valid value + + ## Classes and Methods + + - EpInfraAaaLocalUsersGet.__init__() + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersGet(login_id=None) + assert instance.login_id is None + + +def test_endpoints_api_v1_infra_aaa_00520(): + """ + # Summary + + Verify login_id can be modified after instantiation + + ## Test + + - login_id can be changed after object creation + + ## Classes and Methods + + - EpInfraAaaLocalUsersGet.login_id + """ + with does_not_raise(): + instance = EpInfraAaaLocalUsersGet() + assert instance.login_id is None + instance.login_id = "newuser" + assert instance.login_id == "newuser" + assert instance.path == "/api/v1/infra/aaa/localUsers/newuser"