diff --git a/main/cli/nrfu/index.html b/main/cli/nrfu/index.html index 7aabf28e2..95581dd27 100644 --- a/main/cli/nrfu/index.html +++ b/main/cli/nrfu/index.html @@ -2644,7 +2644,8 @@

NRFU Command overview or 1 if any test failed. [env var: ANTA_NRFU_IGNORE_ERROR] --hide [success|failure|error|skipped] - Group result by test or device. + Hide result by type: success / failure / + error / skipped'. --dry-run Run anta nrfu command but stop before starting to execute the tests. Considers all devices as connected. [env var: diff --git a/main/getting-started/index.html b/main/getting-started/index.html index d2a2534f0..b20bd740b 100644 --- a/main/getting-started/index.html +++ b/main/getting-started/index.html @@ -2521,7 +2521,8 @@

CLI¶< or 1 if any test failed. [env var: ANTA_NRFU_IGNORE_ERROR] --hide [success|failure|error|skipped] - Group result by test or device. + Hide result by type: success / failure / + error / skipped'. --dry-run Run anta nrfu command but stop before starting to execute the tests. Considers all devices as connected. [env var: diff --git a/main/search/search_index.json b/main/search/search_index.json index d7217a671..70236ff7f 100644 --- a/main/search/search_index.json +++ b/main/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Home","text":""},{"location":"#arista-network-test-automation-anta-framework","title":"Arista Network Test Automation (ANTA) Framework","text":"Code License GitHub PyPi

ANTA is Python framework that automates tests for Arista devices.

  • ANTA provides a set of tests to validate the state of your network
  • ANTA can be used to:
  • Automate NRFU (Network Ready For Use) test on a preproduction network
  • Automate tests on a live network (periodically or on demand)
  • ANTA can be used with:
  • As a Python library in your own application
  • The ANTA CLI

"},{"location":"#install-anta-library","title":"Install ANTA library","text":"

The library will NOT install the necessary dependencies for the CLI.

# Install ANTA as a library\npip install anta\n
"},{"location":"#install-anta-cli","title":"Install ANTA CLI","text":"

If you plan to use ANTA only as a CLI tool you can use pipx to install it. pipx is a tool to install and run python applications in isolated environments. Refer to pipx instructions to install on your system. pipx installs ANTA in an isolated python environment and makes it available globally.

This is not recommended if you plan to contribute to ANTA

# Install ANTA CLI with pipx\n$ pipx install anta[cli]\n\n# Run ANTA CLI\n$ anta --help\nUsage: anta [OPTIONS] COMMAND [ARGS]...\n\n  Arista Network Test Automation (ANTA) CLI\n\nOptions:\n  --version                       Show the version and exit.\n  --log-file FILE                 Send the logs to a file. If logging level is\n                                  DEBUG, only INFO or higher will be sent to\n                                  stdout.  [env var: ANTA_LOG_FILE]\n  -l, --log-level [CRITICAL|ERROR|WARNING|INFO|DEBUG]\n                                  ANTA logging level  [env var:\n                                  ANTA_LOG_LEVEL; default: INFO]\n  --help                          Show this message and exit.\n\nCommands:\n  check  Commands to validate configuration files\n  debug  Commands to execute EOS commands on remote devices\n  exec   Commands to execute various scripts on EOS devices\n  get    Commands to get information from or generate inventories\n  nrfu   Run ANTA tests on devices\n

You can also still choose to install it with directly with pip:

pip install anta[cli]\n
"},{"location":"#documentation","title":"Documentation","text":"

The documentation is published on ANTA package website.

"},{"location":"#contribution-guide","title":"Contribution guide","text":"

Contributions are welcome. Please refer to the contribution guide

"},{"location":"#credits","title":"Credits","text":"

Thank you to Jeremy Schulman for aio-eapi.

Thank you to Ang\u00e9lique Phillipps, Colin MacGiollaE\u00e1in, Khelil Sator, Matthieu Tache, Onur Gashi, Paul Lavelle, Guillaume Mulocher and Thomas Grimonet for their contributions and guidances.

"},{"location":"contribution/","title":"Contributions","text":""},{"location":"contribution/#how-to-contribute-to-anta","title":"How to contribute to ANTA","text":"

Contribution model is based on a fork-model. Don\u2019t push to aristanetworks/anta directly. Always do a branch in your forked repository and create a PR.

To help development, open your PR as soon as possible even in draft mode. It helps other to know on what you are working on and avoid duplicate PRs.

"},{"location":"contribution/#create-a-development-environment","title":"Create a development environment","text":"

Run the following commands to create an ANTA development environment:

# Clone repository\n$ git clone https://github.com/aristanetworks/anta.git\n$ cd anta\n\n# Install ANTA in editable mode and its development tools\n$ pip install -e .[dev]\n# To also install the CLI\n$ pip install -e .[dev,cli]\n\n# Verify installation\n$ pip list -e\nPackage Version Editable project location\n------- ------- -------------------------\nanta    1.0.0   /mnt/lab/projects/anta\n

Then, tox is configured with few environments to run CI locally:

$ tox list -d\ndefault environments:\nclean  -> Erase previous coverage reports\nlint   -> Check the code style\ntype   -> Check typing\npy38   -> Run pytest with py38\npy39   -> Run pytest with py39\npy310  -> Run pytest with py310\npy311  -> Run pytest with py311\nreport -> Generate coverage report\n
"},{"location":"contribution/#code-linting","title":"Code linting","text":"
tox -e lint\n[...]\nlint: commands[0]> black --check --diff --color .\nAll done! \u2728 \ud83c\udf70 \u2728\n104 files would be left unchanged.\nlint: commands[1]> isort --check --diff --color .\nSkipped 7 files\nlint: commands[2]> flake8 --max-line-length=165 --config=/dev/null anta\nlint: commands[3]> flake8 --max-line-length=165 --config=/dev/null tests\nlint: commands[4]> pylint anta\n\n--------------------------------------------------------------------\nYour code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)\n\n.pkg: _exit> python /Users/guillaumemulocher/.pyenv/versions/3.8.13/envs/anta/lib/python3.8/site-packages/pyproject_api/_backend.py True setuptools.build_meta\n  lint: OK (19.26=setup[5.83]+cmd[1.50,0.76,1.19,1.20,8.77] seconds)\n  congratulations :) (19.56 seconds)\n
"},{"location":"contribution/#code-typing","title":"Code Typing","text":"
tox -e type\n\n[...]\ntype: commands[0]> mypy --config-file=pyproject.toml anta\nSuccess: no issues found in 52 source files\n.pkg: _exit> python /Users/guillaumemulocher/.pyenv/versions/3.8.13/envs/anta/lib/python3.8/site-packages/pyproject_api/_backend.py True setuptools.build_meta\n  type: OK (46.66=setup[24.20]+cmd[22.46] seconds)\n  congratulations :) (47.01 seconds)\n

NOTE: Typing is configured quite strictly, do not hesitate to reach out if you have any questions, struggles, nightmares.

"},{"location":"contribution/#unit-tests","title":"Unit tests","text":"

To keep high quality code, we require to provide a Pytest for every tests implemented in ANTA.

All submodule should have its own pytest section under tests/units/anta_tests/<submodule-name>.py.

"},{"location":"contribution/#how-to-write-a-unit-test-for-an-antatest-subclass","title":"How to write a unit test for an AntaTest subclass","text":"

The Python modules in the tests/units/anta_tests folder define test parameters for AntaTest subclasses unit tests. A generic test function is written for all unit tests in tests.lib.anta module.

The pytest_generate_tests function definition in conftest.py is called during test collection.

The pytest_generate_tests function will parametrize the generic test function based on the DATA data structure defined in tests.units.anta_tests modules.

See https://docs.pytest.org/en/7.3.x/how-to/parametrize.html#basic-pytest-generate-tests-example

The DATA structure is a list of dictionaries used to parametrize the test. The list elements have the following keys:

  • name (str): Test name as displayed by Pytest.
  • test (AntaTest): An AntaTest subclass imported in the test module - e.g. VerifyUptime.
  • eos_data (list[dict]): List of data mocking EOS returned data to be passed to the test.
  • inputs (dict): Dictionary to instantiate the test inputs as defined in the class from test.
  • expected (dict): Expected test result structure, a dictionary containing a key result containing one of the allowed status (Literal['success', 'failure', 'unset', 'skipped', 'error']) and optionally a key messages which is a list(str) and each message is expected to be a substring of one of the actual messages in the TestResult object.

In order for your unit tests to be correctly collected, you need to import the generic test function even if not used in the Python module.

Test example for anta.tests.system.VerifyUptime AntaTest.

# Import the generic test function\nfrom tests.lib.anta import test  # noqa: F401\n\n# Import your AntaTest\nfrom anta.tests.system import VerifyUptime\n\n# Define test parameters\nDATA: list[dict[str, Any]] = [\n   {\n        # Arbitrary test name\n        \"name\": \"success\",\n        # Must be an AntaTest definition\n        \"test\": VerifyUptime,\n        # Data returned by EOS on which the AntaTest is tested\n        \"eos_data\": [{\"upTime\": 1186689.15, \"loadAvg\": [0.13, 0.12, 0.09], \"users\": 1, \"currentTime\": 1683186659.139859}],\n        # Dictionary to instantiate VerifyUptime.Input\n        \"inputs\": {\"minimum\": 666},\n        # Expected test result\n        \"expected\": {\"result\": \"success\"},\n    },\n    {\n        \"name\": \"failure\",\n        \"test\": VerifyUptime,\n        \"eos_data\": [{\"upTime\": 665.15, \"loadAvg\": [0.13, 0.12, 0.09], \"users\": 1, \"currentTime\": 1683186659.139859}],\n        \"inputs\": {\"minimum\": 666},\n        # If the test returns messages, it needs to be expected otherwise test will fail.\n        # NB: expected messages only needs to be included in messages returned by the test. Exact match is not required.\n        \"expected\": {\"result\": \"failure\", \"messages\": [\"Device uptime is 665.15 seconds\"]},\n    },\n]\n
"},{"location":"contribution/#git-pre-commit-hook","title":"Git Pre-commit hook","text":"
pip install pre-commit\npre-commit install\n

When running a commit or a pre-commit check:

\u276f echo \"import foobaz\" > test.py && git add test.py\n\u276f pre-commit\npylint...................................................................Failed\n- hook id: pylint\n- exit code: 22\n\n************* Module test\ntest.py:1:0: C0114: Missing module docstring (missing-module-docstring)\ntest.py:1:0: E0401: Unable to import 'foobaz' (import-error)\ntest.py:1:0: W0611: Unused import foobaz (unused-import)\n

NOTE: It could happen that pre-commit and tox disagree on something, in that case please open an issue on Github so we can take a look.. It is most probably wrong configuration on our side.

"},{"location":"contribution/#configure-mypypath","title":"Configure MYPYPATH","text":"

In some cases, mypy can complain about not having MYPYPATH configured in your shell. It is especially the case when you update both an anta test and its unit test. So you can configure this environment variable with:

# Option 1: use local folder\nexport MYPYPATH=.\n\n# Option 2: use absolute path\nexport MYPYPATH=/path/to/your/local/anta/repository\n
"},{"location":"contribution/#documentation","title":"Documentation","text":"

mkdocs is used to generate the documentation. A PR should always update the documentation to avoid documentation debt.

"},{"location":"contribution/#install-documentation-requirements","title":"Install documentation requirements","text":"

Run pip to install the documentation requirements from the root of the repo:

pip install -e .[doc]\n
"},{"location":"contribution/#testing-documentation","title":"Testing documentation","text":"

You can then check locally the documentation using the following command from the root of the repo:

mkdocs serve\n

By default, mkdocs listens to http://127.0.0.1:8000/, if you need to expose the documentation to another IP or port (for instance all IPs on port 8080), use the following command:

mkdocs serve --dev-addr=0.0.0.0:8080\n
"},{"location":"contribution/#build-class-diagram","title":"Build class diagram","text":"

To build class diagram to use in API documentation, you can use pyreverse part of pylint with graphviz installed for jpeg generation.

pyreverse anta --colorized -a1 -s1 -o jpeg -m true -k --output-directory docs/imgs/uml/ -c <FQDN anta class>\n

Image will be generated under docs/imgs/uml/ and can be inserted in your documentation.

"},{"location":"contribution/#checking-links","title":"Checking links","text":"

Writing documentation is crucial but managing links can be cumbersome. To be sure there is no dead links, you can use muffet with the following command:

muffet -c 2 --color=always http://127.0.0.1:8000 -e fonts.gstatic.com -b 8192\n
"},{"location":"contribution/#continuous-integration","title":"Continuous Integration","text":"

GitHub actions is used to test git pushes and pull requests. The workflows are defined in this directory. We can view the results here.

"},{"location":"faq/","title":"FAQ","text":""},{"location":"faq/#frequently-asked-questions-faq","title":"Frequently Asked Questions (FAQ)","text":""},{"location":"faq/#a-local-os-error-occurred-while-connecting-to-a-device","title":"A local OS error occurred while connecting to a device","text":"A local OS error occurred while connecting to a device

When running ANTA, you can receive A local OS error occurred while connecting to <device> errors. The underlying OSError exception can have various reasons: [Errno 24] Too many open files or [Errno 16] Device or resource busy.

This usually means that the operating system refused to open a new file descriptor (or socket) for the ANTA process. This might be due to the hard limit for open file descriptors currently set for the ANTA process.

At startup, ANTA sets the soft limit of its process to the hard limit up to 16384. This is because the soft limit is usually 1024 and the hard limit is usually higher (depends on the system). If the hard limit of the ANTA process is still lower than the number of selected tests in ANTA, the ANTA process may request to the operating system too many file descriptors and get an error, a WARNING is displayed at startup if this is the case.

"},{"location":"faq/#solution","title":"Solution","text":"

One solution could be to raise the hard limit for the user starting the ANTA process. You can get the current hard limit for a user using the command ulimit -n -H while logged in. Create the file /etc/security/limits.d/10-anta.conf with the following content:

<user>  hard    nofile  <value>\n
The user is the one with which the ANTA process is started. The value is the new hard limit. The maximum value depends on the system. A hard limit of 16384 should be sufficient for ANTA to run in most high scale scenarios. After creating this file, log out the current session and log in again.

"},{"location":"faq/#timeout-error-in-the-logs","title":"Timeout error in the logs","text":"Timeout error in the logs

When running ANTA, you can receive <Foo>Timeout errors in the logs (could be ReadTimeout, WriteTimeout, ConnectTimeout or PoolTimeout). More details on the timeouts of the underlying library are available here: https://www.python-httpx.org/advanced/timeouts.

This might be due to the time the host on which ANTA is run takes to reach the target devices (for instance if going through firewalls, NATs, \u2026) or when a lot of tests are being run at the same time on a device (eAPI has a queue mechanism to avoid exhausting EOS resources because of a high number of simultaneous eAPI requests).

"},{"location":"faq/#solution_1","title":"Solution","text":"

Use the timeout option. As an example for the nrfu command:

anta nrfu --enable --username username --password arista --inventory inventory.yml -c nrfu.yml --timeout 50 text\n

The previous command set a couple of options for ANTA NRFU, one them being the timeout command, by default, when running ANTA from CLI, it is set to 30s. The timeout is increased to 50s to allow ANTA to wait for API calls a little longer.

"},{"location":"faq/#importerror-related-to-urllib3","title":"ImportError related to urllib3","text":"ImportError related to urllib3 when running ANTA

When running the anta --help command, some users might encounter the following error:

ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0.2k-fips  26 Jan 2017'. See: https://github.com/urllib3/urllib3/issues/2168\n

This error arises due to a compatibility issue between urllib3 v2.0 and older versions of OpenSSL.

"},{"location":"faq/#solution_2","title":"Solution","text":"
  1. Workaround: Downgrade urllib3

    If you need a quick fix, you can temporarily downgrade the urllib3 package:

    pip3 uninstall urllib3\n\npip3 install urllib3==1.26.15\n
  2. Recommended: Upgrade System or Libraries:

    As per the [urllib3 v2 migration guide](https://urllib3.readthedocs.io/en/latest/v2-migration-guide.html), the root cause of this error is an incompatibility with older OpenSSL versions. For example, users on RHEL7 might consider upgrading to RHEL8, which supports the required OpenSSL version.\n
"},{"location":"faq/#attributeerror-module-lib-has-no-attribute-openssl_add_all_algorithms","title":"AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'","text":"AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms' when running ANTA

When running the anta commands after installation, some users might encounter the following error:

AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'\n

The error is a result of incompatibility between cryptography and pyopenssl when installing asyncssh which is a requirement of ANTA.

"},{"location":"faq/#solution_3","title":"Solution","text":"
  1. Upgrade pyopenssl

    pip install -U pyopenssl>22.0\n
"},{"location":"faq/#__nscfconstantstring-initialize-error-on-osx","title":"__NSCFConstantString initialize error on OSX","text":"__NSCFConstantString initialize error on OSX

This error occurs because of added security to restrict multithreading in macOS High Sierra and later versions of macOS. https://www.wefearchange.org/2018/11/forkmacos.rst.html

"},{"location":"faq/#solution_4","title":"Solution","text":"
  1. Set the following environment variable

    export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES\n
"},{"location":"faq/#still-facing-issues","title":"Still facing issues?","text":"

If you\u2019ve tried the above solutions and continue to experience problems, please follow the troubleshooting instructions and report the issue in our GitHub repository.

"},{"location":"getting-started/","title":"Getting Started","text":""},{"location":"getting-started/#getting-started","title":"Getting Started","text":"

This section shows how to use ANTA with basic configuration. All examples are based on Arista Test Drive (ATD) topology you can access by reaching out to your preferred SE.

"},{"location":"getting-started/#installation","title":"Installation","text":"

The easiest way to install ANTA package is to run Python (>=3.9) and its pip package to install:

pip install anta[cli]\n

For more details about how to install package, please see the requirements and installation section.

"},{"location":"getting-started/#configure-arista-eos-devices","title":"Configure Arista EOS devices","text":"

For ANTA to be able to connect to your target devices, you need to configure your management interface

vrf instance MGMT\n!\ninterface Management0\n   description oob_management\n   vrf MGMT\n   ip address 192.168.0.10/24\n!\n

Then, configure access to eAPI:

!\nmanagement api http-commands\n   protocol https port 443\n   no shutdown\n   vrf MGMT\n      no shutdown\n   !\n!\n
"},{"location":"getting-started/#create-your-inventory","title":"Create your inventory","text":"

ANTA uses an inventory to list the target devices for the tests. You can create a file manually with this format:

anta_inventory:\n  hosts:\n  - host: 192.168.0.10\n    name: spine01\n    tags: ['fabric', 'spine']\n  - host: 192.168.0.11\n    name: spine02\n    tags: ['fabric', 'spine']\n  - host: 192.168.0.12\n    name: leaf01\n    tags: ['fabric', 'leaf']\n  - host: 192.168.0.13\n    name: leaf02\n    tags: ['fabric', 'leaf']\n  - host: 192.168.0.14\n    name: leaf03\n    tags: ['fabric', 'leaf']\n  - host: 192.168.0.15\n    name: leaf04\n    tags: ['fabric', 'leaf']\n

You can read more details about how to build your inventory here

"},{"location":"getting-started/#test-catalog","title":"Test Catalog","text":"

To test your network, ANTA relies on a test catalog to list all the tests to run against your inventory. A test catalog references python functions into a yaml file.

The structure to follow is like:

<anta_tests_submodule>:\n  - <anta_tests_submodule function name>:\n      <test function option>:\n        <test function option value>\n

You can read more details about how to build your catalog here

Here is an example for basic tests:

# Load anta.tests.software\nanta.tests.software:\n  - VerifyEOSVersion: # Verifies the device is running one of the allowed EOS version.\n      versions: # List of allowed EOS versions.\n        - 4.25.4M\n        - 4.26.1F\n        - '4.28.3M-28837868.4283M (engineering build)'\n  - VerifyTerminAttrVersion:\n      versions:\n        - v1.22.1\n\nanta.tests.system:\n  - VerifyUptime: # Verifies the device uptime is higher than a value.\n      minimum: 1\n  - VerifyNTP:\n  - VerifySyslog:\n\nanta.tests.mlag:\n  - VerifyMlagStatus:\n  - VerifyMlagInterfaces:\n  - VerifyMlagConfigSanity:\n\nanta.tests.configuration:\n  - VerifyZeroTouch: # Verifies ZeroTouch is disabled.\n  - VerifyRunningConfigDiffs:\n
"},{"location":"getting-started/#test-your-network","title":"Test your network","text":""},{"location":"getting-started/#cli","title":"CLI","text":"

ANTA comes with a generic CLI entrypoint to run tests in your network. It requires an inventory file as well as a test catalog.

This entrypoint has multiple options to manage test coverage and reporting.

Usage: anta [OPTIONS] COMMAND [ARGS]...\n\n  Arista Network Test Automation (ANTA) CLI.\n\nOptions:\n  --version                       Show the version and exit.\n  --log-file FILE                 Send the logs to a file. If logging level is\n                                  DEBUG, only INFO or higher will be sent to\n                                  stdout.  [env var: ANTA_LOG_FILE]\n  -l, --log-level [CRITICAL|ERROR|WARNING|INFO|DEBUG]\n                                  ANTA logging level  [env var:\n                                  ANTA_LOG_LEVEL; default: INFO]\n  --help                          Show this message and exit.\n\nCommands:\n  check  Commands to validate configuration files.\n  debug  Commands to execute EOS commands on remote devices.\n  exec   Commands to execute various scripts on EOS devices.\n  get    Commands to get information from or generate inventories.\n  nrfu   Run ANTA tests on selected inventory devices.\n
Usage: anta nrfu [OPTIONS] COMMAND [ARGS]...\n\n  Run ANTA tests on selected inventory devices.\n\nOptions:\n  -u, --username TEXT             Username to connect to EOS  [env var:\n                                  ANTA_USERNAME; required]\n  -p, --password TEXT             Password to connect to EOS that must be\n                                  provided. It can be prompted using '--\n                                  prompt' option.  [env var: ANTA_PASSWORD]\n  --enable-password TEXT          Password to access EOS Privileged EXEC mode.\n                                  It can be prompted using '--prompt' option.\n                                  Requires '--enable' option.  [env var:\n                                  ANTA_ENABLE_PASSWORD]\n  --enable                        Some commands may require EOS Privileged\n                                  EXEC mode. This option tries to access this\n                                  mode before sending a command to the device.\n                                  [env var: ANTA_ENABLE]\n  -P, --prompt                    Prompt for passwords if they are not\n                                  provided.  [env var: ANTA_PROMPT]\n  --timeout FLOAT                 Global API timeout. This value will be used\n                                  for all devices.  [env var: ANTA_TIMEOUT;\n                                  default: 30.0]\n  --insecure                      Disable SSH Host Key validation.  [env var:\n                                  ANTA_INSECURE]\n  --disable-cache                 Disable cache globally.  [env var:\n                                  ANTA_DISABLE_CACHE]\n  -i, --inventory FILE            Path to the inventory YAML file.  [env var:\n                                  ANTA_INVENTORY; required]\n  --tags TEXT                     List of tags using comma as separator:\n                                  tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  -c, --catalog FILE              Path to the test catalog file  [env var:\n                                  ANTA_CATALOG; required]\n  --catalog-format [yaml|json]    Format of the catalog file, either 'yaml' or\n                                  'json'  [env var: ANTA_CATALOG_FORMAT]\n  -d, --device TEXT               Run tests on a specific device. Can be\n                                  provided multiple times.\n  -t, --test TEXT                 Run a specific test. Can be provided\n                                  multiple times.\n  --ignore-status                 Exit code will always be 0.  [env var:\n                                  ANTA_NRFU_IGNORE_STATUS]\n  --ignore-error                  Exit code will be 0 if all tests succeeded\n                                  or 1 if any test failed.  [env var:\n                                  ANTA_NRFU_IGNORE_ERROR]\n  --hide [success|failure|error|skipped]\n                                  Group result by test or device.\n  --dry-run                       Run anta nrfu command but stop before\n                                  starting to execute the tests. Considers all\n                                  devices as connected.  [env var:\n                                  ANTA_NRFU_DRY_RUN]\n  --help                          Show this message and exit.\n\nCommands:\n  json        ANTA command to check network state with JSON result.\n  table       ANTA command to check network states with table result.\n  text        ANTA command to check network states with text result.\n  tpl-report  ANTA command to check network state with templated report.\n

To run the NRFU, you need to select an output format amongst [\u201cjson\u201d, \u201ctable\u201d, \u201ctext\u201d, \u201ctpl-report\u201d]. For a first usage, table is recommended. By default all test results for all devices are rendered but it can be changed to a report per test case or per host

"},{"location":"getting-started/#default-report-using-table","title":"Default report using table","text":"
anta nrfu \\\n    --username tom \\\n    --password arista123 \\\n    --enable \\\n    --enable-password t \\\n    --inventory .personal/inventory_atd.yml \\\n    --catalog .personal/tests-bases.yml \\\n    table --tags leaf\n\n\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Settings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 Running ANTA tests:                                  \u2502\n\u2502 - ANTA Inventory contains 6 devices (AsyncEOSDevice) \u2502\n\u2502 - Tests catalog contains 10 tests                    \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n[10:17:24] INFO     Running ANTA tests...                                                                                                           runner.py:75\n  \u2022 Running NRFU Tests...100% \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501 40/40 \u2022 0:00:02 \u2022 0:00:00\n\n                                                                       All tests results\n\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\n\u2503 Device IP \u2503 Test Name                \u2503 Test Status \u2503 Message(s)       \u2503 Test description                                                     \u2503 Test category \u2503\n\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\n\u2502 leaf01    \u2502 VerifyEOSVersion         \u2502 success     \u2502                  \u2502 Verifies the device is running one of the allowed EOS version.       \u2502 software      \u2502\n\u2502 leaf01    \u2502 VerifyTerminAttrVersion  \u2502 success     \u2502                  \u2502 Verifies the device is running one of the allowed TerminAttr         \u2502 software      \u2502\n\u2502           \u2502                          \u2502             \u2502                  \u2502 version.                                                             \u2502               \u2502\n\u2502 leaf01    \u2502 VerifyUptime             \u2502 success     \u2502                  \u2502 Verifies the device uptime is higher than a value.                   \u2502 system        \u2502\n\u2502 leaf01    \u2502 VerifyNTP                \u2502 success     \u2502                  \u2502 Verifies NTP is synchronised.                                        \u2502 system        \u2502\n\u2502 leaf01    \u2502 VerifySyslog             \u2502 success     \u2502                  \u2502 Verifies the device had no syslog message with a severity of warning \u2502 system        \u2502\n\u2502           \u2502                          \u2502             \u2502                  \u2502 (or a more severe message) during the last 7 days.                   \u2502               \u2502\n\u2502 leaf01    \u2502 VerifyMlagStatus         \u2502 skipped     \u2502 MLAG is disabled \u2502 This test verifies the health status of the MLAG configuration.      \u2502 mlag          \u2502\n\u2502 leaf01    \u2502 VerifyMlagInterfaces     \u2502 skipped     \u2502 MLAG is disabled \u2502 This test verifies there are no inactive or active-partial MLAG      \u2502 mlag          \u2502\n[...]\n\u2502 leaf04    \u2502 VerifyMlagConfigSanity   \u2502 skipped     \u2502 MLAG is disabled \u2502 This test verifies there are no MLAG config-sanity inconsistencies.  \u2502 mlag          \u2502\n\u2502 leaf04    \u2502 VerifyZeroTouch          \u2502 success     \u2502                  \u2502 Verifies ZeroTouch is disabled.                                      \u2502 configuration \u2502\n\u2502 leaf04    \u2502 VerifyRunningConfigDiffs \u2502 success     \u2502                  \u2502                                                                      \u2502 configuration \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n
"},{"location":"getting-started/#report-in-text-mode","title":"Report in text mode","text":"
$ anta nrfu \\\n    --username tom \\\n    --password arista123 \\\n    --enable \\\n    --enable-password t \\\n    --inventory .personal/inventory_atd.yml \\\n    --catalog .personal/tests-bases.yml \\\n    text --tags leaf\n\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Settings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 Running ANTA tests:                                  \u2502\n\u2502 - ANTA Inventory contains 6 devices (AsyncEOSDevice) \u2502\n\u2502 - Tests catalog contains 10 tests                    \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n[10:20:47] INFO     Running ANTA tests...                                                                                                           runner.py:75\n  \u2022 Running NRFU Tests...100% \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501 40/40 \u2022 0:00:01 \u2022 0:00:00\nleaf01 :: VerifyEOSVersion :: SUCCESS\nleaf01 :: VerifyTerminAttrVersion :: SUCCESS\nleaf01 :: VerifyUptime :: SUCCESS\nleaf01 :: VerifyNTP :: SUCCESS\nleaf01 :: VerifySyslog :: SUCCESS\nleaf01 :: VerifyMlagStatus :: SKIPPED (MLAG is disabled)\nleaf01 :: VerifyMlagInterfaces :: SKIPPED (MLAG is disabled)\nleaf01 :: VerifyMlagConfigSanity :: SKIPPED (MLAG is disabled)\n[...]\n
"},{"location":"getting-started/#report-in-json-format","title":"Report in JSON format","text":"
$ anta nrfu \\\n    --username tom \\\n    --password arista123 \\\n    --enable \\\n    --enable-password t \\\n    --inventory .personal/inventory_atd.yml \\\n    --catalog .personal/tests-bases.yml \\\n    json --tags leaf\n\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Settings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 Running ANTA tests:                                  \u2502\n\u2502 - ANTA Inventory contains 6 devices (AsyncEOSDevice) \u2502\n\u2502 - Tests catalog contains 10 tests                    \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n[10:21:51] INFO     Running ANTA tests...                                                                                                           runner.py:75\n  \u2022 Running NRFU Tests...100% \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501 40/40 \u2022 0:00:02 \u2022 0:00:00\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 JSON results of all tests                                                                                                                                    \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n[\n  {\n    \"name\": \"leaf01\",\n    \"test\": \"VerifyEOSVersion\",\n    \"categories\": [\n      \"software\"\n    ],\n    \"description\": \"Verifies the device is running one of the allowed EOS version.\",\n    \"result\": \"success\",\n    \"messages\": [],\n    \"custom_field\": \"None\",\n  },\n  {\n    \"name\": \"leaf01\",\n    \"test\": \"VerifyTerminAttrVersion\",\n    \"categories\": [\n      \"software\"\n    ],\n    \"description\": \"Verifies the device is running one of the allowed TerminAttr version.\",\n    \"result\": \"success\",\n    \"messages\": [],\n    \"custom_field\": \"None\",\n  },\n[...]\n]\n

You can find more information under the usage section of the website

"},{"location":"getting-started/#basic-usage-in-a-python-script","title":"Basic usage in a Python script","text":"
# Copyright (c) 2023-2024 Arista Networks, Inc.\n# Use of this source code is governed by the Apache License 2.0\n# that can be found in the LICENSE file.\n\"\"\"Example script for ANTA.\n\nusage:\n\npython anta_runner.py\n\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nimport logging\nimport sys\nfrom pathlib import Path\n\nfrom anta.catalog import AntaCatalog\nfrom anta.cli.nrfu.utils import anta_progress_bar\nfrom anta.inventory import AntaInventory\nfrom anta.logger import Log, setup_logging\nfrom anta.models import AntaTest\nfrom anta.result_manager import ResultManager\nfrom anta.runner import main as anta_runner\n\n# setup logging\nsetup_logging(Log.INFO, Path(\"/tmp/anta.log\"))\nLOGGER = logging.getLogger()\nSCRIPT_LOG_PREFIX = \"[bold magenta][ANTA RUNNER SCRIPT][/] \"  # For convenience purpose - there are nicer way to do this.\n\n\n# NOTE: The inventory and catalog files are not delivered with this script\nUSERNAME = \"admin\"\nPASSWORD = \"admin\"\nCATALOG_PATH = Path(\"/tmp/anta_catalog.yml\")\nINVENTORY_PATH = Path(\"/tmp/anta_inventory.yml\")\n\n# Load catalog file\ntry:\n    catalog = AntaCatalog.parse(CATALOG_PATH)\nexcept Exception:\n    LOGGER.exception(\"%s Catalog failed to load!\", SCRIPT_LOG_PREFIX)\n    sys.exit(1)\nLOGGER.info(\"%s Catalog loaded!\", SCRIPT_LOG_PREFIX)\n\n# Load inventory\ntry:\n    inventory = AntaInventory.parse(INVENTORY_PATH, username=USERNAME, password=PASSWORD)\nexcept Exception:\n    LOGGER.exception(\"%s Inventory failed to load!\", SCRIPT_LOG_PREFIX)\n    sys.exit(1)\nLOGGER.info(\"%s Inventory loaded!\", SCRIPT_LOG_PREFIX)\n\n# Create result manager object\nmanager = ResultManager()\n\n# Launch ANTA\nLOGGER.info(\"%s  Starting ANTA runner...\", SCRIPT_LOG_PREFIX)\nwith anta_progress_bar() as AntaTest.progress:\n    # Set dry_run to True to avoid connecting to the devices\n    asyncio.run(anta_runner(manager, inventory, catalog, dry_run=False))\n\nLOGGER.info(\"%s ANTA run completed!\", SCRIPT_LOG_PREFIX)\n\n# Manipulate the test result object\nfor test_result in manager.results:\n    LOGGER.info(\"%s %s:%s:%s\", SCRIPT_LOG_PREFIX, test_result.name, test_result.test, test_result.result)\n
"},{"location":"requirements-and-installation/","title":"Installation","text":""},{"location":"requirements-and-installation/#anta-requirements","title":"ANTA Requirements","text":""},{"location":"requirements-and-installation/#python-version","title":"Python version","text":"

Python 3 (>=3.9) is required:

python --version\nPython 3.11.8\n
"},{"location":"requirements-and-installation/#install-anta-package","title":"Install ANTA package","text":"

This installation will deploy tests collection, scripts and all their Python requirements.

The ANTA package and the cli require some packages that are not part of the Python standard library. They are indicated in the pyproject.toml file, under dependencies.

"},{"location":"requirements-and-installation/#install-library-from-pypi-server","title":"Install library from Pypi server","text":"
pip install anta\n

Warning

  • This command alone will not install the ANTA CLI requirements.
"},{"location":"requirements-and-installation/#install-anta-cli-as-an-application-with-pipx","title":"Install ANTA CLI as an application with pipx","text":"

pipx is a tool to install and run python applications in isolated environments. If you plan to use ANTA only as a CLI tool you can use pipx to install it. pipx installs ANTA in an isolated python environment and makes it available globally.

pipx install anta[cli]\n

Info

Please take the time to read through the installation instructions of pipx before getting started.

"},{"location":"requirements-and-installation/#install-cli-from-pypi-server","title":"Install CLI from Pypi server","text":"

Alternatively, pip install with cli extra is enough to install the ANTA CLI.

pip install anta[cli]\n
"},{"location":"requirements-and-installation/#install-anta-from-github","title":"Install ANTA from github","text":"
pip install git+https://github.com/aristanetworks/anta.git\npip install git+https://github.com/aristanetworks/anta.git#egg=anta[cli]\n\n# You can even specify the branch, tag or commit:\npip install git+https://github.com/aristanetworks/anta.git@<cool-feature-branch>\npip install git+https://github.com/aristanetworks/anta.git@<cool-feature-branch>#egg=anta[cli]\n\npip install git+https://github.com/aristanetworks/anta.git@<cool-tag>\npip install git+https://github.com/aristanetworks/anta.git@<cool-tag>#egg=anta[cli]\n\npip install git+https://github.com/aristanetworks/anta.git@<more-or-less-cool-hash>\npip install git+https://github.com/aristanetworks/anta.git@<more-or-less-cool-hash>#egg=anta[cli]\n
"},{"location":"requirements-and-installation/#check-installation","title":"Check installation","text":"

After installing ANTA, verify the installation with the following commands:

# Check ANTA has been installed in your python path\npip list | grep anta\n\n# Check scripts are in your $PATH\n# Path may differ but it means CLI is in your path\nwhich anta\n/home/tom/.pyenv/shims/anta\n

Warning

Before running the anta --version command, please be aware that some users have reported issues related to the urllib3 package. If you encounter an error at this step, please refer to our FAQ page for guidance on resolving it.

# Check ANTA version\nanta --version\nanta, version v1.0.0\n
"},{"location":"requirements-and-installation/#eos-requirements","title":"EOS Requirements","text":"

To get ANTA working, the targeted Arista EOS devices must have eAPI enabled. They need to use the following configuration (assuming you connect to the device using Management interface in MGMT VRF):

configure\n!\nvrf instance MGMT\n!\ninterface Management1\n   description oob_management\n   vrf MGMT\n   ip address 10.73.1.105/24\n!\nend\n

Enable eAPI on the MGMT vrf:

configure\n!\nmanagement api http-commands\n   protocol https port 443\n   no shutdown\n   vrf MGMT\n      no shutdown\n!\nend\n

Now the switch accepts on port 443 in the MGMT VRF HTTPS requests containing a list of CLI commands.

Run these EOS commands to verify:

show management http-server\nshow management api http-commands\n
"},{"location":"troubleshooting/","title":"Troubleshooting","text":""},{"location":"troubleshooting/#troubleshooting-anta","title":"Troubleshooting ANTA","text":"

A couple of things to check when hitting an issue with ANTA:

flowchart LR\n    A>Hitting an issue with ANTA] --> B{Is my issue <br >listed in the FAQ?}\n    B -- Yes --> C{Does the FAQ solution<br />works for me?}\n    C -- Yes --> V(((Victory)))\n    B -->|No| E{Is my problem<br />mentioned in one<br />of the open issues?}\n    C -->|No| E\n    E -- Yes --> F{Has the issue been<br />fixed in a newer<br />release or in main?}\n    F -- Yes --> U[Upgrade]\n    E -- No ---> H((Follow the steps below<br />and open a Github issue))\n    U --> I{Did it fix<br /> your problem}\n    I -- Yes --> V\n    I -- No --> H\n    F -- No ----> G((Add a comment on the <br />issue indicating you<br >are hitting this and<br />describing your setup<br /> and adding your logs.))\n\n    click B \"../faq\" \"FAQ\"\n    click E \"https://github.com/aristanetworks/anta/issues\"\n    click H \"https://github.com/aristanetworks/anta/issues\"\n    style A stroke:#f00,stroke-width:2px
"},{"location":"troubleshooting/#capturing-logs","title":"Capturing logs","text":"

To help document the issue in Github, it is important to capture some logs so the developers can understand what is affecting your system. No logs mean that the first question asked on the issue will probably be \u201cCan you share some logs please?\u201d.

ANTA provides very verbose logs when using the DEBUG level. When using DEBUG log level with a log file, the DEBUG logging level is not sent to stdout, but only to the file.

Danger

On real deployments, do not use DEBUG logging level without setting a log file at the same time.

To save the logs to a file called anta.log, use the following flags:

# Where ANTA_COMMAND is one of nrfu, debug, get, exec, check\nanta -l DEBUG \u2013log-file anta.log <ANTA_COMMAND>\n

See anta --help for more information. These have to precede the nrfu cmd.

Tip

Remember that in ANTA, each level of command has its own options and they can only be set at this level. so the -l and --log-file MUST be between anta and the ANTA_COMMAND. similarly, all the nrfu options MUST be set between the nrfu and the ANTA_NRFU_SUBCOMMAND (json, text, table or tpl-report).

As an example, for the nrfu command, it would look like:

anta -l DEBUG --log-file anta.log nrfu --enable --username username --password arista --inventory inventory.yml -c nrfu.yml text\n
"},{"location":"troubleshooting/#anta_debug-environment-variable","title":"ANTA_DEBUG environment variable","text":"Warning

Do not use this if you do not know why. This produces a lot of logs and can create confusion if you do not know what to look for.

The environment variable ANTA_DEBUG=true enable ANTA Debug Mode.

This flag is used by various functions in ANTA: when set to true, the function will display or log more information. In particular, when an Exception occurs in the code and this variable is set, the logging function used by ANTA is different to also produce the Python traceback for debugging. This typically needs to be done when opening a GitHub issue and an Exception is seen at runtime.

Example:

ANTA_DEBUG=true anta -l DEBUG --log-file anta.log nrfu --enable --username username --password arista --inventory inventory.yml -c nrfu.yml text\n
"},{"location":"troubleshooting/#troubleshooting-on-eos","title":"Troubleshooting on EOS","text":"

ANTA is using a specific ID in eAPI requests towards EOS. This allows for easier eAPI requests debugging on the device using EOS configuration trace CapiApp setting UwsgiRequestContext/4,CapiUwsgiServer/4 to set up CapiApp agent logs.

Then, you can view agent logs using:

bash tail -f /var/log/agents/CapiApp-*\n\n2024-05-15 15:32:54.056166  1429 UwsgiRequestContext  4 request content b'{\"jsonrpc\": \"2.0\", \"method\": \"runCmds\", \"params\": {\"version\": \"latest\", \"cmds\": [{\"cmd\": \"show ip route vrf default 10.255.0.3\", \"revision\": 4}], \"format\": \"json\", \"autoComplete\": false, \"expandAliases\": false}, \"id\": \"ANTA-VerifyRoutingTableEntry-132366530677328\"}'\n

"},{"location":"usage-inventory-catalog/","title":"Inventory & Tests catalog","text":""},{"location":"usage-inventory-catalog/#inventory-and-catalog","title":"Inventory and Catalog","text":"

The ANTA framework needs 2 important inputs from the user to run: a device inventory and a test catalog.

Both inputs can be defined in a file or programmatically.

"},{"location":"usage-inventory-catalog/#device-inventory","title":"Device Inventory","text":"

A device inventory is an instance of the AntaInventory class.

"},{"location":"usage-inventory-catalog/#device-inventory-file","title":"Device Inventory File","text":"

The ANTA device inventory can easily be defined as a YAML file. The file must comply with the following structure:

anta_inventory:\n  hosts:\n    - host: < ip address value >\n      port: < TCP port for eAPI. Default is 443 (Optional)>\n      name: < name to display in report. Default is host:port (Optional) >\n      tags: < list of tags to use to filter inventory during tests >\n      disable_cache: < Disable cache per hosts. Default is False. >\n  networks:\n    - network: < network using CIDR notation >\n      tags: < list of tags to use to filter inventory during tests >\n      disable_cache: < Disable cache per network. Default is False. >\n  ranges:\n    - start: < first ip address value of the range >\n      end: < last ip address value of the range >\n      tags: < list of tags to use to filter inventory during tests >\n      disable_cache: < Disable cache per range. Default is False. >\n

The inventory file must start with the anta_inventory key then define one or multiple methods:

  • hosts: define each device individually
  • networks: scan a network for devices accessible via eAPI
  • ranges: scan a range for devices accessible via eAPI

A full description of the inventory model is available in API documentation

Info

Caching can be disabled per device, network or range by setting the disable_cache key to True in the inventory file. For more details about how caching is implemented in ANTA, please refer to Caching in ANTA.

"},{"location":"usage-inventory-catalog/#example","title":"Example","text":"
---\nanta_inventory:\n  hosts:\n  - host: 192.168.0.10\n    name: spine01\n    tags: ['fabric', 'spine']\n  - host: 192.168.0.11\n    name: spine02\n    tags: ['fabric', 'spine']\n  networks:\n  - network: '192.168.110.0/24'\n    tags: ['fabric', 'leaf']\n  ranges:\n  - start: 10.0.0.9\n    end: 10.0.0.11\n    tags: ['fabric', 'l2leaf']\n
"},{"location":"usage-inventory-catalog/#test-catalog","title":"Test Catalog","text":"

A test catalog is an instance of the AntaCatalog class.

"},{"location":"usage-inventory-catalog/#test-catalog-file","title":"Test Catalog File","text":"

In addition to the inventory file, you also have to define a catalog of tests to execute against your devices. This catalog list all your tests, their inputs and their tags.

A valid test catalog file must have the following structure in either YAML or JSON:

---\n<Python module>:\n    - <AntaTest subclass>:\n        <AntaTest.Input compliant dictionary>\n

{\n  \"<Python module>\": [\n    {\n      \"<AntaTest subclass>\": <AntaTest.Input compliant dictionary>\n    }\n  ]\n}\n
"},{"location":"usage-inventory-catalog/#example_1","title":"Example","text":"
---\nanta.tests.connectivity:\n  - VerifyReachability:\n      hosts:\n        - source: Management0\n          destination: 1.1.1.1\n          vrf: MGMT\n        - source: Management0\n          destination: 8.8.8.8\n          vrf: MGMT\n      filters:\n        tags: ['leaf']\n      result_overwrite:\n        categories:\n          - \"Overwritten category 1\"\n        description: \"Test with overwritten description\"\n        custom_field: \"Test run by John Doe\"\n

or equivalent in JSON:

{\n  \"anta.tests.connectivity\": [\n    {\n      \"VerifyReachability\": {\n        \"result_overwrite\": {\n          \"description\": \"Test with overwritten description\",\n          \"categories\": [\n            \"Overwritten category 1\"\n          ],\n          \"custom_field\": \"Test run by John Doe\"\n        },\n        \"filters\": {\n          \"tags\": [\n            \"leaf\"\n          ]\n        },\n        \"hosts\": [\n          {\n            \"destination\": \"1.1.1.1\",\n            \"source\": \"Management0\",\n            \"vrf\": \"MGMT\"\n          },\n          {\n            \"destination\": \"8.8.8.8\",\n            \"source\": \"Management0\",\n            \"vrf\": \"MGMT\"\n          }\n        ]\n      }\n    }\n  ]\n}\n

It is also possible to nest Python module definition:

anta.tests:\n  connectivity:\n    - VerifyReachability:\n        hosts:\n          - source: Management0\n            destination: 1.1.1.1\n            vrf: MGMT\n          - source: Management0\n            destination: 8.8.8.8\n            vrf: MGMT\n        filters:\n          tags: ['leaf']\n        result_overwrite:\n          categories:\n            - \"Overwritten category 1\"\n          description: \"Test with overwritten description\"\n          custom_field: \"Test run by John Doe\"\n

This test catalog example is maintained with all the tests defined in the anta.tests Python module.

"},{"location":"usage-inventory-catalog/#test-tags","title":"Test tags","text":"

All tests can be defined with a list of user defined tags. These tags will be mapped with device tags: when at least one tag is defined for a test, this test will only be executed on devices with the same tag. If a test is defined in the catalog without any tags, the test will be executed on all devices.

anta.tests.system:\n  - VerifyUptime:\n      minimum: 10\n      filters:\n        tags: ['demo', 'leaf']\n  - VerifyReloadCause:\n  - VerifyCoredump:\n  - VerifyAgentLogs:\n  - VerifyCPUUtilization:\n      filters:\n        tags: ['leaf']\n

Info

When using the CLI, you can filter the NRFU execution using tags. Refer to this section of the CLI documentation.

"},{"location":"usage-inventory-catalog/#tests-available-in-anta","title":"Tests available in ANTA","text":"

All tests available as part of the ANTA framework are defined under the anta.tests Python module and are categorised per family (Python submodule). The complete list of the tests and their respective inputs is available at the tests section of this website.

To run test to verify the EOS software version, you can do:

anta.tests.software:\n  - VerifyEOSVersion:\n

It will load the test VerifyEOSVersion located in anta.tests.software. But since this test has mandatory inputs, we need to provide them as a dictionary in the YAML or JSON file:

anta.tests.software:\n  - VerifyEOSVersion:\n      # List of allowed EOS versions.\n      versions:\n        - 4.25.4M\n        - 4.26.1F\n
{\n  \"anta.tests.software\": [\n    {\n      \"VerifyEOSVersion\": {\n        \"versions\": [\n          \"4.25.4M\",\n          \"4.31.1F\"\n        ]\n      }\n    }\n  ]\n}\n

The following example is a very minimal test catalog:

---\n# Load anta.tests.software\nanta.tests.software:\n  # Verifies the device is running one of the allowed EOS version.\n  - VerifyEOSVersion:\n      # List of allowed EOS versions.\n      versions:\n        - 4.25.4M\n        - 4.26.1F\n\n# Load anta.tests.system\nanta.tests.system:\n  # Verifies the device uptime is higher than a value.\n  - VerifyUptime:\n      minimum: 1\n\n# Load anta.tests.configuration\nanta.tests.configuration:\n  # Verifies ZeroTouch is disabled.\n  - VerifyZeroTouch:\n  - VerifyRunningConfigDiffs:\n
"},{"location":"usage-inventory-catalog/#catalog-with-custom-tests","title":"Catalog with custom tests","text":"

In case you want to leverage your own tests collection, use your own Python package in the test catalog. So for instance, if my custom tests are defined in the custom.tests.system Python module, the test catalog will be:

custom.tests.system:\n  - VerifyPlatform:\n    type: ['cEOS-LAB']\n

How to create custom tests

To create your custom tests, you should refer to this documentation

"},{"location":"usage-inventory-catalog/#customize-test-description-and-categories","title":"Customize test description and categories","text":"

It might be interesting to use your own categories and customized test description to build a better report for your environment. ANTA comes with a handy feature to define your own categories and description in the report.

In your test catalog, use result_overwrite dictionary with categories and description to just overwrite this values in your report:

anta.tests.configuration:\n  - VerifyZeroTouch: # Verifies ZeroTouch is disabled.\n      result_overwrite:\n        categories: ['demo', 'pr296']\n        description: A custom test\n  - VerifyRunningConfigDiffs:\nanta.tests.interfaces:\n  - VerifyInterfaceUtilization:\n

Once you run anta nrfu table, you will see following output:

\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\n\u2503 Device IP \u2503 Test Name                  \u2503 Test Status \u2503 Message(s) \u2503 Test description                              \u2503 Test category \u2503\n\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\n\u2502 spine01   \u2502 VerifyZeroTouch            \u2502 success     \u2502            \u2502 A custom test                                 \u2502 demo, pr296   \u2502\n\u2502 spine01   \u2502 VerifyRunningConfigDiffs   \u2502 success     \u2502            \u2502                                               \u2502 configuration \u2502\n\u2502 spine01   \u2502 VerifyInterfaceUtilization \u2502 success     \u2502            \u2502 Verifies interfaces utilization is below 75%. \u2502 interfaces    \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n
"},{"location":"usage-inventory-catalog/#example-script-to-merge-catalogs","title":"Example script to merge catalogs","text":"

The following script reads all the files in intended/test_catalogs/ with names <device_name>-catalog.yml and merge them together inside one big catalog anta-catalog.yml.

#!/usr/bin/env python\nfrom anta.catalog import AntaCatalog\n\nfrom pathlib import Path\nfrom anta.models import AntaTest\n\n\nCATALOG_SUFFIX = '-catalog.yml'\nCATALOG_DIR = 'intended/test_catalogs/'\n\nif __name__ == \"__main__\":\n    catalog = AntaCatalog()\n    for file in Path(CATALOG_DIR).glob('*'+CATALOG_SUFFIX):\n        c = AntaCatalog.parse(file)\n        device = str(file).removesuffix(CATALOG_SUFFIX).removeprefix(CATALOG_DIR)\n        print(f\"Merging test catalog for device {device}\")\n        # Apply filters to all tests for this device\n        for test in c.tests:\n            test.inputs.filters = AntaTest.Input.Filters(tags=[device])\n        catalog = catalog.merge(c)\n    with open(Path('anta-catalog.yml'), \"w\") as f:\n        f.write(catalog.dump().yaml())\n
"},{"location":"advanced_usages/as-python-lib/","title":"ANTA as a Python Library","text":"

ANTA is a Python library that can be used in user applications. This section describes how you can leverage ANTA Python modules to help you create your own NRFU solution.

Tip

If you are unfamiliar with asyncio, refer to the Python documentation relevant to your Python version - https://docs.python.org/3/library/asyncio.html

"},{"location":"advanced_usages/as-python-lib/#antadevice-abstract-class","title":"AntaDevice Abstract Class","text":"

A device is represented in ANTA as a instance of a subclass of the AntaDevice abstract class. There are few abstract methods that needs to be implemented by child classes:

  • The collect() coroutine is in charge of collecting outputs of AntaCommand instances.
  • The refresh() coroutine is in charge of updating attributes of the AntaDevice instance. These attributes are used by AntaInventory to filter out unreachable devices or by AntaTest to skip devices based on their hardware models.

The copy() coroutine is used to copy files to and from the device. It does not need to be implemented if tests are not using it.

"},{"location":"advanced_usages/as-python-lib/#asynceosdevice-class","title":"AsyncEOSDevice Class","text":"

The AsyncEOSDevice class is an implementation of AntaDevice for Arista EOS. It uses the aio-eapi eAPI client and the AsyncSSH library.

  • The collect() coroutine collects AntaCommand outputs using eAPI.
  • The refresh() coroutine tries to open a TCP connection on the eAPI port and update the is_online attribute accordingly. If the TCP connection succeeds, it sends a show version command to gather the hardware model of the device and updates the established and hw_model attributes.
  • The copy() coroutine copies files to and from the device using the SCP protocol.
"},{"location":"advanced_usages/as-python-lib/#antainventory-class","title":"AntaInventory Class","text":"

The AntaInventory class is a subclass of the standard Python type dict. The keys of this dictionary are the device names, the values are AntaDevice instances.

AntaInventory provides methods to interact with the ANTA inventory:

  • The add_device() method adds an AntaDevice instance to the inventory. Adding an entry to AntaInventory with a key different from the device name is not allowed.
  • The get_inventory() returns a new AntaInventory instance with filtered out devices based on the method inputs.
  • The connect_inventory() coroutine will execute the refresh() coroutines of all the devices in the inventory.
  • The parse() static method creates an AntaInventory instance from a YAML file and returns it. The devices are AsyncEOSDevice instances.

To parse a YAML inventory file and print the devices connection status:

\"\"\"\nExample\n\"\"\"\nimport asyncio\n\nfrom anta.inventory import AntaInventory\n\n\nasync def main(inv: AntaInventory) -> None:\n    \"\"\"\n    Take an AntaInventory and:\n    1. try to connect to every device in the inventory\n    2. print a message for every device connection status\n    \"\"\"\n    await inv.connect_inventory()\n\n    for device in inv.values():\n        if device.established:\n            print(f\"Device {device.name} is online\")\n        else:\n            print(f\"Could not connect to device {device.name}\")\n\nif __name__ == \"__main__\":\n    # Create the AntaInventory instance\n    inventory = AntaInventory.parse(\n        filename=\"inv.yml\",\n        username=\"arista\",\n        password=\"@rista123\",\n    )\n\n    # Run the main coroutine\n    res = asyncio.run(main(inventory))\n
How to create your inventory file

Please visit this dedicated section for how to use inventory and catalog files.

To run an EOS commands list on the reachable devices from the inventory:

\"\"\"\nExample\n\"\"\"\n# This is needed to run the script for python < 3.10 for typing annotations\nfrom __future__ import annotations\n\nimport asyncio\nfrom pprint import pprint\n\nfrom anta.inventory import AntaInventory\nfrom anta.models import AntaCommand\n\n\nasync def main(inv: AntaInventory, commands: list[str]) -> dict[str, list[AntaCommand]]:\n    \"\"\"\n    Take an AntaInventory and a list of commands as string and:\n    1. try to connect to every device in the inventory\n    2. collect the results of the commands from each device\n\n    Returns:\n      a dictionary where key is the device name and the value is the list of AntaCommand ran towards the device\n    \"\"\"\n    await inv.connect_inventory()\n\n    # Make a list of coroutine to run commands towards each connected device\n    coros = []\n    # dict to keep track of the commands per device\n    result_dict = {}\n    for name, device in inv.get_inventory(established_only=True).items():\n        anta_commands = [AntaCommand(command=command, ofmt=\"json\") for command in commands]\n        result_dict[name] = anta_commands\n        coros.append(device.collect_commands(anta_commands))\n\n    # Run the coroutines\n    await asyncio.gather(*coros)\n\n    return result_dict\n\n\nif __name__ == \"__main__\":\n    # Create the AntaInventory instance\n    inventory = AntaInventory.parse(\n        filename=\"inv.yml\",\n        username=\"arista\",\n        password=\"@rista123\",\n    )\n\n    # Create a list of commands with json output\n    commands = [\"show version\", \"show ip bgp summary\"]\n\n    # Run the main asyncio  entry point\n    res = asyncio.run(main(inventory, commands))\n\n    pprint(res)\n

"},{"location":"advanced_usages/as-python-lib/#use-tests-from-anta","title":"Use tests from ANTA","text":"

All the test classes inherit from the same abstract Base Class AntaTest. The Class definition indicates which commands are required for the test and the user should focus only on writing the test function with optional keywords argument. The instance of the class upon creation instantiates a TestResult object that can be accessed later on to check the status of the test ([unset, skipped, success, failure, error]).

"},{"location":"advanced_usages/as-python-lib/#test-structure","title":"Test structure","text":"

All tests are built on a class named AntaTest which provides a complete toolset for a test:

  • Object creation
  • Test definition
  • TestResult definition
  • Abstracted method to collect data

This approach means each time you create a test it will be based on this AntaTest class. Besides that, you will have to provide some elements:

  • name: Name of the test
  • description: A human readable description of your test
  • categories: a list of categories to sort test.
  • commands: a list of command to run. This list must be a list of AntaCommand which is described in the next part of this document.

Here is an example of a hardware test related to device temperature:

from __future__ import annotations\n\nimport logging\nfrom typing import Any, Dict, List, Optional, cast\n\nfrom anta.models import AntaTest, AntaCommand\n\n\nclass VerifyTemperature(AntaTest):\n    \"\"\"\n    Verifies device temparture is currently OK.\n    \"\"\"\n\n    # The test name\n    name = \"VerifyTemperature\"\n    # A small description of the test, usually the first line of the class docstring\n    description = \"Verifies device temparture is currently OK\"\n    # The category of the test, usually the module name\n    categories = [\"hardware\"]\n    # The command(s) used for the test. Could be a template instead\n    commands = [AntaCommand(command=\"show system environment temperature\", ofmt=\"json\")]\n\n    # Decorator\n    @AntaTest.anta_test\n    # abstract method that must be defined by the child Test class\n    def test(self) -> None:\n        \"\"\"Run VerifyTemperature validation\"\"\"\n        command_output = cast(Dict[str, Dict[Any, Any]], self.instance_commands[0].output)\n        temperature_status = command_output[\"systemStatus\"] if \"systemStatus\" in command_output.keys() else \"\"\n        if temperature_status == \"temperatureOk\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device temperature is not OK, systemStatus: {temperature_status }\")\n

When you run the test, object will automatically call its anta.models.AntaTest.collect() method to get device output for each command if no pre-collected data was given to the test. This method does a loop to call anta.inventory.models.InventoryDevice.collect() methods which is in charge of managing device connection and how to get data.

run test offline

You can also pass eos data directly to your test if you want to validate data collected in a different workflow. An example is provided below just for information:

test = VerifyTemperature(device, eos_data=test_data[\"eos_data\"])\nasyncio.run(test.test())\n

The test function is always the same and must be defined with the @AntaTest.anta_test decorator. This function takes at least one argument which is a anta.inventory.models.InventoryDevice object. In some cases a test would rely on some additional inputs from the user, for instance the number of expected peers or some expected numbers. All parameters must come with a default value and the test function should validate the parameters values (at this stage this is the only place where validation can be done but there are future plans to make this better).

class VerifyTemperature(AntaTest):\n    ...\n    @AntaTest.anta_test\n    def test(self) -> None:\n        pass\n\nclass VerifyTransceiversManufacturers(AntaTest):\n    ...\n    @AntaTest.anta_test\n    def test(self, manufacturers: Optional[List[str]] = None) -> None:\n        # validate the manufactures parameter\n        pass\n

The test itself does not return any value, but the result is directly available from your AntaTest object and exposes a anta.result_manager.models.TestResult object with result, name of the test and optional messages:

  • name (str): Device name where the test has run.
  • test (str): Test name runs on the device.
  • categories (List[str]): List of categories the TestResult belongs to, by default the AntaTest categories.
  • description (str): TestResult description, by default the AntaTest description.
  • results (str): Result of the test. Can be one of [\u201cunset\u201d, \u201csuccess\u201d, \u201cfailure\u201d, \u201cerror\u201d, \u201cskipped\u201d].
  • message (str, optional): Message to report after the test if any.
  • custom_field (str, optional): Custom field to store a string for flexibility in integrating with ANTA
from anta.tests.hardware import VerifyTemperature\n\ntest = VerifyTemperature(device, eos_data=test_data[\"eos_data\"])\nasyncio.run(test.test())\nassert test.result.result == \"success\"\n
"},{"location":"advanced_usages/as-python-lib/#classes-for-commands","title":"Classes for commands","text":"

To make it easier to get data, ANTA defines 2 different classes to manage commands to send to devices:

"},{"location":"advanced_usages/as-python-lib/#antacommand-class","title":"AntaCommand Class","text":"

Represent a command with following information:

  • Command to run
  • Output format expected
  • eAPI version
  • Output of the command

Usage example:

from anta.models import AntaCommand\n\ncmd1 = AntaCommand(command=\"show zerotouch\")\ncmd2 = AntaCommand(command=\"show running-config diffs\", ofmt=\"text\")\n

Command revision and version

  • Most of EOS commands return a JSON structure according to a model (some commands may not be modeled hence the necessity to use text outformat sometimes.
  • The model can change across time (adding feature, \u2026 ) and when the model is changed in a non backward-compatible way, the revision number is bumped. The initial model starts with revision 1.
  • A revision applies to a particular CLI command whereas a version is global to an eAPI call. The version is internally translated to a specific revision for each CLI command in the RPC call. The currently supported version values are 1 and latest.
  • A revision takes precedence over a version (e.g. if a command is run with version=\u201dlatest\u201d and revision=1, the first revision of the model is returned)
  • By default, eAPI returns the first revision of each model to ensure that when upgrading, integrations with existing tools are not broken. This is done by using by default version=1 in eAPI calls.

By default, ANTA uses version=\"latest\" in AntaCommand, but when developing tests, the revision MUST be provided when the outformat of the command is json. As explained earlier, this is to ensure that the eAPI always returns the same output model and that the test remains always valid from the day it was created. For some commands, you may also want to run them with a different revision or version.

For instance, the VerifyBFDPeersHealth test leverages the first revision of show bfd peers:

# revision 1 as later revision introduce additional nesting for type\ncommands = [AntaCommand(command=\"show bfd peers\", revision=1)]\n
"},{"location":"advanced_usages/as-python-lib/#antatemplate-class","title":"AntaTemplate Class","text":"

Because some command can require more dynamic than just a command with no parameter provided by user, ANTA supports command template: you define a template in your test class and user provide parameters when creating test object.

class RunArbitraryTemplateCommand(AntaTest):\n    \"\"\"\n    Run an EOS command and return result\n    Based on AntaTest to build relevant output for pytest\n    \"\"\"\n\n    name = \"Run aributrary EOS command\"\n    description = \"To be used only with anta debug commands\"\n    template = AntaTemplate(template=\"show interfaces {ifd}\")\n    categories = [\"debug\"]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        errdisabled_interfaces = [interface for interface, value in response[\"interfaceStatuses\"].items() if value[\"linkStatus\"] == \"errdisabled\"]\n        ...\n\n\nparams = [{\"ifd\": \"Ethernet2\"}, {\"ifd\": \"Ethernet49/1\"}]\nrun_command1 = RunArbitraryTemplateCommand(device_anta, params)\n

In this example, test waits for interfaces to check from user setup and will only check for interfaces in params

"},{"location":"advanced_usages/caching/","title":"Caching in ANTA","text":"

ANTA is a streamlined Python framework designed for efficient interaction with network devices. This section outlines how ANTA incorporates caching mechanisms to collect command outputs from network devices.

"},{"location":"advanced_usages/caching/#configuration","title":"Configuration","text":"

By default, ANTA utilizes aiocache\u2019s memory cache backend, also called SimpleMemoryCache. This library aims for simplicity and supports asynchronous operations to go along with Python asyncio used in ANTA.

The _init_cache() method of the AntaDevice abstract class initializes the cache. Child classes can override this method to tweak the cache configuration:

def _init_cache(self) -> None:\n    \"\"\"\n    Initialize cache for the device, can be overridden by subclasses to manipulate how it works\n    \"\"\"\n    self.cache = Cache(cache_class=Cache.MEMORY, ttl=60, namespace=self.name, plugins=[HitMissRatioPlugin()])\n    self.cache_locks = defaultdict(asyncio.Lock)\n

The cache is also configured with aiocache\u2019s HitMissRatioPlugin plugin to calculate the ratio of hits the cache has and give useful statistics for logging purposes in ANTA.

"},{"location":"advanced_usages/caching/#cache-key-design","title":"Cache key design","text":"

The cache is initialized per AntaDevice and uses the following cache key design:

<device_name>:<uid>

The uid is an attribute of AntaCommand, which is a unique identifier generated from the command, version, revision and output format.

Each UID has its own asyncio lock. This design allows coroutines that need to access the cache for different UIDs to do so concurrently. The locks are managed by the self.cache_locks dictionary.

"},{"location":"advanced_usages/caching/#mechanisms","title":"Mechanisms","text":"

By default, once the cache is initialized, it is used in the collect() method of AntaDevice. The collect() method prioritizes retrieving the output of the command from the cache. If the output is not in the cache, the private _collect() method will retrieve and then store it for future access.

"},{"location":"advanced_usages/caching/#how-to-disable-caching","title":"How to disable caching","text":"

Caching is enabled by default in ANTA following the previous configuration and mechanisms.

There might be scenarios where caching is not wanted. You can disable caching in multiple ways in ANTA:

  1. Caching can be disabled globally, for ALL commands on ALL devices, using the --disable-cache global flag when invoking anta at the CLI:
    anta --disable-cache --username arista --password arista nrfu table\n
  2. Caching can be disabled per device, network or range by setting the disable_cache key to True when defining the ANTA Inventory file:

    anta_inventory:\n  hosts:\n  - host: 172.20.20.101\n    name: DC1-SPINE1\n    tags: [\"SPINE\", \"DC1\"]\n    disable_cache: True  # Set this key to True\n  - host: 172.20.20.102\n    name: DC1-SPINE2\n    tags: [\"SPINE\", \"DC1\"]\n    disable_cache: False # Optional since it's the default\n\n  networks:\n  - network: \"172.21.21.0/24\"\n    disable_cache: True\n\n  ranges:\n  - start: 172.22.22.10\n    end: 172.22.22.19\n    disable_cache: True\n
    This approach effectively disables caching for ALL commands sent to devices targeted by the disable_cache key.

  3. For tests developers, caching can be disabled for a specific AntaCommand or AntaTemplate by setting the use_cache attribute to False. That means the command output will always be collected on the device and therefore, never use caching.

"},{"location":"advanced_usages/caching/#disable-caching-in-a-child-class-of-antadevice","title":"Disable caching in a child class of AntaDevice","text":"

Since caching is implemented at the AntaDevice abstract class level, all subclasses will inherit that default behavior. As a result, if you need to disable caching in any custom implementation of AntaDevice outside of the ANTA framework, you must initialize AntaDevice with disable_cache set to True:

class AnsibleEOSDevice(AntaDevice):\n  \"\"\"\n  Implementation of an AntaDevice using Ansible HttpApi plugin for EOS.\n  \"\"\"\n  def __init__(self, name: str, connection: ConnectionBase, tags: set = None) -> None:\n      super().__init__(name, tags, disable_cache=True)\n
"},{"location":"advanced_usages/custom-tests/","title":"Developing ANTA tests","text":"

This documentation applies for both creating tests in ANTA or creating your own test package.

ANTA is not only a Python library with a CLI and a collection of built-in tests, it is also a framework you can extend by building your own tests.

"},{"location":"advanced_usages/custom-tests/#generic-approach","title":"Generic approach","text":"

A test is a Python class where a test function is defined and will be run by the framework.

ANTA provides an abstract class AntaTest. This class does the heavy lifting and provide the logic to define, collect and test data. The code below is an example of a simple test in ANTA, which is an AntaTest subclass:

from anta.models import AntaTest, AntaCommand\nfrom anta.decorators import skip_on_platforms\n\n\nclass VerifyTemperature(AntaTest):\n    \"\"\"Verifies if the device temperature is within acceptable limits.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device temperature is currently OK: 'temperatureOk'.\n    * Failure: The test will fail if the device temperature is NOT OK.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyTemperature:\n    ```\n    \"\"\"\n\n    name = \"VerifyTemperature\"\n    description = \"Verifies the device temperature.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system environment temperature\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTemperature.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        temperature_status = command_output.get(\"systemStatus\", \"\")\n        if temperature_status == \"temperatureOk\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device temperature exceeds acceptable limits. Current system status: '{temperature_status}'\")\n

AntaTest also provide more advanced capabilities like AntaCommand templating using the AntaTemplate class or test inputs definition and validation using AntaTest.Input pydantic model. This will be discussed in the sections below.

"},{"location":"advanced_usages/custom-tests/#antatest-structure","title":"AntaTest structure","text":"

Full AntaTest API documentation is available in the API documentation section

"},{"location":"advanced_usages/custom-tests/#class-attributes","title":"Class Attributes","text":"
  • name (str): Name of the test. Used during reporting.
  • description (str): A human readable description of your test.
  • categories (list[str]): A list of categories in which the test belongs.
  • commands ([list[AntaCommand | AntaTemplate]]): A list of command to collect from devices. This list must be a list of AntaCommand or AntaTemplate instances. Rendering AntaTemplate instances will be discussed later.

Info

All these class attributes are mandatory. If any attribute is missing, a NotImplementedError exception will be raised during class instantiation.

"},{"location":"advanced_usages/custom-tests/#instance-attributes","title":"Instance Attributes","text":"

Info

You can access an instance attribute in your code using the self reference. E.g. you can access the test input values using self.inputs.

Attributes:

Name Type Description device AntaDevice instance on which this test is run

inputs: AntaTest.Input instance carrying the test inputs instance_commands: List of AntaCommand instances of this test result: TestResult instance representing the result of this test logger: Python logger for this test instance

Logger object

ANTA already provides comprehensive logging at every steps of a test execution. The AntaTest class also provides a logger attribute that is a Python logger specific to the test instance. See Python documentation for more information.

AntaDevice object

Even if device is not a private attribute, you should not need to access this object in your code.

"},{"location":"advanced_usages/custom-tests/#test-inputs","title":"Test Inputs","text":"

AntaTest.Input is a pydantic model that allow test developers to define their test inputs. pydantic provides out of the box error handling for test input validation based on the type hints defined by the test developer.

The base definition of AntaTest.Input provides common test inputs for all AntaTest instances:

"},{"location":"advanced_usages/custom-tests/#input-model","title":"Input model","text":"

Full Input model documentation is available in API documentation section

Attributes:

Name Type Description result_overwrite Define fields to overwrite in the TestResult object"},{"location":"advanced_usages/custom-tests/#resultoverwrite-model","title":"ResultOverwrite model","text":"

Full ResultOverwrite model documentation is available in API documentation section

Attributes:

Name Type Description description overwrite TestResult.description

categories: overwrite TestResult.categories custom_field: a free string that will be included in the TestResult object

Note

The pydantic model is configured using the extra=forbid that will fail input validation if extra fields are provided.

"},{"location":"advanced_usages/custom-tests/#methods","title":"Methods","text":"
  • test(self) -> None: This is an abstract method that must be implemented. It contains the test logic that can access the collected command outputs using the instance_commands instance attribute, access the test inputs using the inputs instance attribute and must set the result instance attribute accordingly. It must be implemented using the AntaTest.anta_test decorator that provides logging and will collect commands before executing the test() method.
  • render(self, template: AntaTemplate) -> list[AntaCommand]: This method only needs to be implemented if AntaTemplate instances are present in the commands class attribute. It will be called for every AntaTemplate occurrence and must return a list of AntaCommand using the AntaTemplate.render() method. It can access test inputs using the inputs instance attribute.
"},{"location":"advanced_usages/custom-tests/#test-execution","title":"Test execution","text":"

Below is a high level description of the test execution flow in ANTA:

  1. ANTA will parse the test catalog to get the list of AntaTest subclasses to instantiate and their associated input values. We consider a single AntaTest subclass in the following steps.

  2. ANTA will instantiate the AntaTest subclass and a single device will be provided to the test instance. The Input model defined in the class will also be instantiated at this moment. If any ValidationError is raised, the test execution will be stopped.

  3. If there is any AntaTemplate instance in the commands class attribute, render() will be called for every occurrence. At this moment, the instance_commands attribute has been initialized. If any rendering error occurs, the test execution will be stopped.

  4. The AntaTest.anta_test decorator will collect the commands from the device and update the instance_commands attribute with the outputs. If any collection error occurs, the test execution will be stopped.

  5. The test() method is executed.

"},{"location":"advanced_usages/custom-tests/#writing-an-antatest-subclass","title":"Writing an AntaTest subclass","text":"

In this section, we will go into all the details of writing an AntaTest subclass.

"},{"location":"advanced_usages/custom-tests/#class-definition","title":"Class definition","text":"

Import anta.models.AntaTest and define your own class. Define the mandatory class attributes using anta.models.AntaCommand, anta.models.AntaTemplate or both.

Info

Caching can be disabled per AntaCommand or AntaTemplate by setting the use_cache argument to False. For more details about how caching is implemented in ANTA, please refer to Caching in ANTA.

from anta.models import AntaTest, AntaCommand, AntaTemplate\n\n\nclass <YourTestName>(AntaTest):\n    \"\"\"\n    <a docstring description of your test>\n    \"\"\"\n\n    name = \"YourTestName\"                                           # should be your class name\n    description = \"<test description in human reading format>\"\n    categories = [\"<arbitrary category>\", \"<another arbitrary category>\"]\n    commands = [\n        AntaCommand(\n            command=\"<EOS command to run>\",\n            ofmt=\"<command format output>\",\n            version=\"<eAPI version to use>\",\n            revision=\"<revision to use for the command>\",           # revision has precedence over version\n            use_cache=\"<Use cache for the command>\",\n        ),\n        AntaTemplate(\n            template=\"<Python f-string to render an EOS command>\",\n            ofmt=\"<command format output>\",\n            version=\"<eAPI version to use>\",\n            revision=\"<revision to use for the command>\",           # revision has precedence over version\n            use_cache=\"<Use cache for the command>\",\n        )\n    ]\n
"},{"location":"advanced_usages/custom-tests/#inputs-definition","title":"Inputs definition","text":"

If the user needs to provide inputs for your test, you need to define a pydantic model that defines the schema of the test inputs:

class <YourTestName>(AntaTest):\n    \"\"\"Verifies ...\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if ...\n    * Failure: The test will fail if ...\n\n    Examples\n    --------\n    ```yaml\n    your.module.path:\n      - YourTestName:\n        field_name: example_field_value\n    ```\n    \"\"\"\n    ...\n    class Input(AntaTest.Input):\n        \"\"\"Inputs for my awesome test.\"\"\"\n        <input field name>: <input field type>\n        \"\"\"<input field docstring>\"\"\"\n

To define an input field type, refer to the pydantic documentation about types. You can also leverage anta.custom_types that provides reusable types defined in ANTA tests.

Regarding required, optional and nullable fields, refer to this documentation on how to define them.

Note

All the pydantic features are supported. For instance you can define validators for complex input validation.

"},{"location":"advanced_usages/custom-tests/#template-rendering","title":"Template rendering","text":"

Define the render() method if you have AntaTemplate instances in your commands class attribute:

class <YourTestName>(AntaTest):\n    ...\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        return [template.render(<template param>=input_value) for input_value in self.inputs.<input_field>]\n

You can access test inputs and render as many AntaCommand as desired.

"},{"location":"advanced_usages/custom-tests/#test-definition","title":"Test definition","text":"

Implement the test() method with your test logic:

class <YourTestName>(AntaTest):\n    ...\n    @AntaTest.anta_test\n    def test(self) -> None:\n        pass\n

The logic usually includes the following different stages: 1. Parse the command outputs using the self.instance_commands instance attribute. 2. If needed, access the test inputs using the self.inputs instance attribute and write your conditional logic. 3. Set the result instance attribute to reflect the test result by either calling self.result.is_success() or self.result.is_failure(\"<FAILURE REASON>\"). Sometimes, setting the test result to skipped using self.result.is_skipped(\"<SKIPPED REASON>\") can make sense (e.g. testing the OSPF neighbor states but no neighbor was found). However, you should not need to catch any exception and set the test result to error since the error handling is done by the framework, see below.

The example below is based on the VerifyTemperature test.

class VerifyTemperature(AntaTest):\n    ...\n    @AntaTest.anta_test\n    def test(self) -> None:\n        # Grab output of the collected command\n        command_output = self.instance_commands[0].json_output\n\n        # Do your test: In this example we check a specific field of the JSON output from EOS\n        temperature_status = command_output[\"systemStatus\"] if \"systemStatus\" in command_output.keys() else \"\"\n        if temperature_status == \"temperatureOk\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device temperature exceeds acceptable limits. Current system status: '{temperature_status}'\")\n

As you can see there is no error handling to do in your code. Everything is packaged in the AntaTest.anta_tests decorator and below is a simple example of error captured when trying to access a dictionary with an incorrect key:

class VerifyTemperature(AntaTest):\n    ...\n    @AntaTest.anta_test\n    def test(self) -> None:\n        # Grab output of the collected command\n        command_output = self.instance_commands[0].json_output\n\n        # Access the dictionary with an incorrect key\n        command_output['incorrectKey']\n
ERROR    Exception raised for test VerifyTemperature (on device 192.168.0.10) - KeyError ('incorrectKey')\n

Get stack trace for debugging

If you want to access to the full exception stack, you can run ANTA in debug mode by setting the ANTA_DEBUG environment variable to true. Example:

$ ANTA_DEBUG=true anta nrfu --catalog test_custom.yml text\n

"},{"location":"advanced_usages/custom-tests/#test-decorators","title":"Test decorators","text":"

In addition to the required AntaTest.anta_tests decorator, ANTA offers a set of optional decorators for further test customization:

  • anta.decorators.deprecated_test: Use this to log a message of WARNING severity when a test is deprecated.
  • anta.decorators.skip_on_platforms: Use this to skip tests for functionalities that are not supported on specific platforms.
from anta.decorators import skip_on_platforms\n\nclass VerifyTemperature(AntaTest):\n    ...\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        pass\n
"},{"location":"advanced_usages/custom-tests/#access-your-custom-tests-in-the-test-catalog","title":"Access your custom tests in the test catalog","text":"

This section is required only if you are not merging your development into ANTA. Otherwise, just follow contribution guide.

For that, you need to create your own Python package as described in this hitchhiker\u2019s guide to package Python code. We assume it is well known and we won\u2019t focus on this aspect. Thus, your package must be impartable by ANTA hence available in the module search path sys.path (you can use PYTHONPATH for example).

It is very similar to what is documented in catalog section but you have to use your own package name.2

Let say the custom Python package is anta_custom and the test is defined in anta_custom.dc_project Python module, the test catalog would look like:

anta_custom.dc_project:\n  - VerifyFeatureX:\n      minimum: 1\n
And now you can run your NRFU tests with the CLI:

anta nrfu text --catalog test_custom.yml\nspine01 :: verify_dynamic_vlan :: FAILURE (Device has 0 configured, we expect at least 1)\nspine02 :: verify_dynamic_vlan :: FAILURE (Device has 0 configured, we expect at least 1)\nleaf01 :: verify_dynamic_vlan :: SUCCESS\nleaf02 :: verify_dynamic_vlan :: SUCCESS\nleaf03 :: verify_dynamic_vlan :: SUCCESS\nleaf04 :: verify_dynamic_vlan :: SUCCESS\n
"},{"location":"api/catalog/","title":"Test Catalog","text":""},{"location":"api/catalog/#anta.catalog.AntaCatalog","title":"AntaCatalog","text":"
AntaCatalog(tests: list[AntaTestDefinition] | None = None, filename: str | Path | None = None)\n

Class representing an ANTA Catalog.

It can be instantiated using its constructor or one of the static methods: parse(), from_list() or from_dict()

Source code in anta/catalog.py
def __init__(\n    self,\n    tests: list[AntaTestDefinition] | None = None,\n    filename: str | Path | None = None,\n) -> None:\n    \"\"\"Instantiate an AntaCatalog instance.\n\n    Parameters\n    ----------\n        tests: A list of AntaTestDefinition instances.\n        filename: The path from which the catalog is loaded.\n\n    \"\"\"\n    self._tests: list[AntaTestDefinition] = []\n    if tests is not None:\n        self._tests = tests\n    self._filename: Path | None = None\n    if filename is not None:\n        if isinstance(filename, Path):\n            self._filename = filename\n        else:\n            self._filename = Path(filename)\n\n    # Default indexes for faster access\n    self.tag_to_tests: defaultdict[str | None, set[AntaTestDefinition]] = defaultdict(set)\n    self.tests_without_tags: set[AntaTestDefinition] = set()\n    self.indexes_built: bool = False\n    self.final_tests_count: int = 0\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.filename","title":"filename property","text":"
filename: Path | None\n

Path of the file used to create this AntaCatalog instance.

"},{"location":"api/catalog/#anta.catalog.AntaCatalog.tests","title":"tests property writable","text":"
tests: list[AntaTestDefinition]\n

List of AntaTestDefinition in this catalog.

"},{"location":"api/catalog/#anta.catalog.AntaCatalog.build_indexes","title":"build_indexes","text":"
build_indexes(filtered_tests: set[str] | None = None) -> None\n

Indexes tests by their tags for quick access during filtering operations.

If a filtered_tests set is provided, only the tests in this set will be indexed.

This method populates two attributes: - tag_to_tests: A dictionary mapping each tag to a set of tests that contain it. - tests_without_tags: A set of tests that do not have any tags.

Once the indexes are built, the indexes_built attribute is set to True.

Source code in anta/catalog.py
def build_indexes(self, filtered_tests: set[str] | None = None) -> None:\n    \"\"\"Indexes tests by their tags for quick access during filtering operations.\n\n    If a `filtered_tests` set is provided, only the tests in this set will be indexed.\n\n    This method populates two attributes:\n    - tag_to_tests: A dictionary mapping each tag to a set of tests that contain it.\n    - tests_without_tags: A set of tests that do not have any tags.\n\n    Once the indexes are built, the `indexes_built` attribute is set to True.\n    \"\"\"\n    for test in self.tests:\n        # Skip tests that are not in the specified filtered_tests set\n        if filtered_tests and test.test.name not in filtered_tests:\n            continue\n\n        # Indexing by tag\n        if test.inputs.filters and (test_tags := test.inputs.filters.tags):\n            for tag in test_tags:\n                self.tag_to_tests[tag].add(test)\n        else:\n            self.tests_without_tags.add(test)\n\n    self.tag_to_tests[None] = self.tests_without_tags\n    self.indexes_built = True\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.dump","title":"dump","text":"
dump() -> AntaCatalogFile\n

Return an AntaCatalogFile instance from this AntaCatalog instance.

Returns:

Type Description An AntaCatalogFile instance containing tests of this AntaCatalog instance. Source code in anta/catalog.py
def dump(self) -> AntaCatalogFile:\n    \"\"\"Return an AntaCatalogFile instance from this AntaCatalog instance.\n\n    Returns\n    -------\n        An AntaCatalogFile instance containing tests of this AntaCatalog instance.\n    \"\"\"\n    root: dict[ImportString[Any], list[AntaTestDefinition]] = {}\n    for test in self.tests:\n        # Cannot use AntaTest.module property as the class is not instantiated\n        root.setdefault(test.test.__module__, []).append(test)\n    return AntaCatalogFile(root=root)\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.from_dict","title":"from_dict staticmethod","text":"
from_dict(data: RawCatalogInput, filename: str | Path | None = None) -> AntaCatalog\n

Create an AntaCatalog instance from a dictionary data structure.

See RawCatalogInput type alias for details. It is the data structure returned by yaml.load() function of a valid YAML Test Catalog file.

Source code in anta/catalog.py
@staticmethod\ndef from_dict(data: RawCatalogInput, filename: str | Path | None = None) -> AntaCatalog:\n    \"\"\"Create an AntaCatalog instance from a dictionary data structure.\n\n    See RawCatalogInput type alias for details.\n    It is the data structure returned by `yaml.load()` function of a valid\n    YAML Test Catalog file.\n\n    Parameters\n    ----------\n        data: Python dictionary used to instantiate the AntaCatalog instance\n        filename: value to be set as AntaCatalog instance attribute\n\n    \"\"\"\n    tests: list[AntaTestDefinition] = []\n    if data is None:\n        logger.warning(\"Catalog input data is empty\")\n        return AntaCatalog(filename=filename)\n\n    if not isinstance(data, dict):\n        msg = f\"Wrong input type for catalog data{f' (from {filename})' if filename is not None else ''}, must be a dict, got {type(data).__name__}\"\n        raise TypeError(msg)\n\n    try:\n        catalog_data = AntaCatalogFile(data)  # type: ignore[arg-type]\n    except ValidationError as e:\n        anta_log_exception(\n            e,\n            f\"Test catalog is invalid!{f' (from {filename})' if filename is not None else ''}\",\n            logger,\n        )\n        raise\n    for t in catalog_data.root.values():\n        tests.extend(t)\n    return AntaCatalog(tests, filename=filename)\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.from_list","title":"from_list staticmethod","text":"
from_list(data: ListAntaTestTuples) -> AntaCatalog\n

Create an AntaCatalog instance from a list data structure.

See ListAntaTestTuples type alias for details.

Source code in anta/catalog.py
@staticmethod\ndef from_list(data: ListAntaTestTuples) -> AntaCatalog:\n    \"\"\"Create an AntaCatalog instance from a list data structure.\n\n    See ListAntaTestTuples type alias for details.\n\n    Parameters\n    ----------\n        data: Python list used to instantiate the AntaCatalog instance\n\n    \"\"\"\n    tests: list[AntaTestDefinition] = []\n    try:\n        tests.extend(AntaTestDefinition(test=test, inputs=inputs) for test, inputs in data)\n    except ValidationError as e:\n        anta_log_exception(e, \"Test catalog is invalid!\", logger)\n        raise\n    return AntaCatalog(tests)\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.get_tests_by_tags","title":"get_tests_by_tags","text":"
get_tests_by_tags(tags: set[str], *, strict: bool = False) -> set[AntaTestDefinition]\n

Return all tests that match a given set of tags, according to the specified strictness.

Returns:

Type Description set[AntaTestDefinition]: A set of tests that match the given tags.

Raises:

Type Description ValueError: If the indexes have not been built prior to method call. Source code in anta/catalog.py
def get_tests_by_tags(self, tags: set[str], *, strict: bool = False) -> set[AntaTestDefinition]:\n    \"\"\"Return all tests that match a given set of tags, according to the specified strictness.\n\n    Parameters\n    ----------\n        tags: The tags to filter tests by. If empty, return all tests without tags.\n        strict: If True, returns only tests that contain all specified tags (intersection).\n                If False, returns tests that contain any of the specified tags (union).\n\n    Returns\n    -------\n        set[AntaTestDefinition]: A set of tests that match the given tags.\n\n    Raises\n    ------\n        ValueError: If the indexes have not been built prior to method call.\n    \"\"\"\n    if not self.indexes_built:\n        msg = \"Indexes have not been built yet. Call build_indexes() first.\"\n        raise ValueError(msg)\n    if not tags:\n        return self.tag_to_tests[None]\n\n    filtered_sets = [self.tag_to_tests[tag] for tag in tags if tag in self.tag_to_tests]\n    if not filtered_sets:\n        return set()\n\n    if strict:\n        return set.intersection(*filtered_sets)\n    return set.union(*filtered_sets)\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.merge","title":"merge","text":"
merge(catalog: AntaCatalog) -> AntaCatalog\n

Merge two AntaCatalog instances.

Returns:

Type Description A new AntaCatalog instance containing the tests of the two instances. Source code in anta/catalog.py
def merge(self, catalog: AntaCatalog) -> AntaCatalog:\n    \"\"\"Merge two AntaCatalog instances.\n\n    Parameters\n    ----------\n        catalog: AntaCatalog instance to merge to this instance.\n\n    Returns\n    -------\n        A new AntaCatalog instance containing the tests of the two instances.\n    \"\"\"\n    return AntaCatalog(tests=self.tests + catalog.tests)\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.parse","title":"parse staticmethod","text":"
parse(filename: str | Path, file_format: Literal['yaml', 'json'] = 'yaml') -> AntaCatalog\n

Create an AntaCatalog instance from a test catalog file.

Source code in anta/catalog.py
@staticmethod\ndef parse(filename: str | Path, file_format: Literal[\"yaml\", \"json\"] = \"yaml\") -> AntaCatalog:\n    \"\"\"Create an AntaCatalog instance from a test catalog file.\n\n    Parameters\n    ----------\n        filename: Path to test catalog YAML or JSON fil\n        file_format: Format of the file, either 'yaml' or 'json'\n\n    \"\"\"\n    if file_format not in [\"yaml\", \"json\"]:\n        message = f\"'{file_format}' is not a valid format for an AntaCatalog file. Only 'yaml' and 'json' are supported.\"\n        raise ValueError(message)\n\n    try:\n        file: Path = filename if isinstance(filename, Path) else Path(filename)\n        with file.open(encoding=\"UTF-8\") as f:\n            data = safe_load(f) if file_format == \"yaml\" else json_load(f)\n    except (TypeError, YAMLError, OSError, ValueError) as e:\n        message = f\"Unable to parse ANTA Test Catalog file '{filename}'\"\n        anta_log_exception(e, message, logger)\n        raise\n\n    return AntaCatalog.from_dict(data, filename=filename)\n
"},{"location":"api/catalog/#anta.catalog.AntaTestDefinition","title":"AntaTestDefinition","text":"
AntaTestDefinition(**data: type[AntaTest] | AntaTest.Input | dict[str, Any] | None)\n

Bases: BaseModel

Define a test with its associated inputs.

test: An AntaTest concrete subclass inputs: The associated AntaTest.Input subclass instance

https://docs.pydantic.dev/2.0/usage/validators/#using-validation-context-with-basemodel-initialization.

Source code in anta/catalog.py
def __init__(self, **data: type[AntaTest] | AntaTest.Input | dict[str, Any] | None) -> None:\n    \"\"\"Inject test in the context to allow to instantiate Input in the BeforeValidator.\n\n    https://docs.pydantic.dev/2.0/usage/validators/#using-validation-context-with-basemodel-initialization.\n    \"\"\"\n    self.__pydantic_validator__.validate_python(\n        data,\n        self_instance=self,\n        context={\"test\": data[\"test\"]},\n    )\n    super(BaseModel, self).__init__()\n
"},{"location":"api/catalog/#anta.catalog.AntaTestDefinition.check_inputs","title":"check_inputs","text":"
check_inputs() -> AntaTestDefinition\n

Check the inputs field typing.

The inputs class attribute needs to be an instance of the AntaTest.Input subclass defined in the class test.

Source code in anta/catalog.py
@model_validator(mode=\"after\")\ndef check_inputs(self) -> AntaTestDefinition:\n    \"\"\"Check the `inputs` field typing.\n\n    The `inputs` class attribute needs to be an instance of the AntaTest.Input subclass defined in the class `test`.\n    \"\"\"\n    if not isinstance(self.inputs, self.test.Input):\n        msg = f\"Test input has type {self.inputs.__class__.__qualname__} but expected type {self.test.Input.__qualname__}\"\n        raise ValueError(msg)  # noqa: TRY004 pydantic catches ValueError or AssertionError, no TypeError\n    return self\n
"},{"location":"api/catalog/#anta.catalog.AntaTestDefinition.instantiate_inputs","title":"instantiate_inputs classmethod","text":"
instantiate_inputs(data: AntaTest.Input | dict[str, Any] | None, info: ValidationInfo) -> AntaTest.Input\n

Ensure the test inputs can be instantiated and thus are valid.

If the test has no inputs, allow the user to omit providing the inputs field. If the test has inputs, allow the user to provide a valid dictionary of the input fields. This model validator will instantiate an Input class from the test class field.

Source code in anta/catalog.py
@field_validator(\"inputs\", mode=\"before\")\n@classmethod\ndef instantiate_inputs(\n    cls: type[AntaTestDefinition],\n    data: AntaTest.Input | dict[str, Any] | None,\n    info: ValidationInfo,\n) -> AntaTest.Input:\n    \"\"\"Ensure the test inputs can be instantiated and thus are valid.\n\n    If the test has no inputs, allow the user to omit providing the `inputs` field.\n    If the test has inputs, allow the user to provide a valid dictionary of the input fields.\n    This model validator will instantiate an Input class from the `test` class field.\n    \"\"\"\n    if info.context is None:\n        msg = \"Could not validate inputs as no test class could be identified\"\n        raise ValueError(msg)\n    # Pydantic guarantees at this stage that test_class is a subclass of AntaTest because of the ordering\n    # of fields in the class definition - so no need to check for this\n    test_class = info.context[\"test\"]\n    if not (isclass(test_class) and issubclass(test_class, AntaTest)):\n        msg = f\"Could not validate inputs as no test class {test_class} is not a subclass of AntaTest\"\n        raise ValueError(msg)\n\n    if isinstance(data, AntaTest.Input):\n        return data\n    try:\n        if data is None:\n            return test_class.Input()\n        if isinstance(data, dict):\n            return test_class.Input(**data)\n    except ValidationError as e:\n        inputs_msg = str(e).replace(\"\\n\", \"\\n\\t\")\n        err_type = \"wrong_test_inputs\"\n        raise PydanticCustomError(\n            err_type,\n            f\"{test_class.name} test inputs are not valid: {inputs_msg}\\n\",\n            {\"errors\": e.errors()},\n        ) from e\n    msg = f\"Could not instantiate inputs as type {type(data).__name__} is not valid\"\n    raise ValueError(msg)\n
"},{"location":"api/catalog/#anta.catalog.AntaTestDefinition.serialize_model","title":"serialize_model","text":"
serialize_model() -> dict[str, AntaTest.Input]\n

Serialize the AntaTestDefinition model.

The dictionary representing the model will be look like:

<AntaTest subclass name>:\n        <AntaTest.Input compliant dictionary>\n

Returns:

Type Description A dictionary representing the model. Source code in anta/catalog.py
@model_serializer()\ndef serialize_model(self) -> dict[str, AntaTest.Input]:\n    \"\"\"Serialize the AntaTestDefinition model.\n\n    The dictionary representing the model will be look like:\n    ```\n    <AntaTest subclass name>:\n            <AntaTest.Input compliant dictionary>\n    ```\n\n    Returns\n    -------\n        A dictionary representing the model.\n    \"\"\"\n    return {self.test.__name__: self.inputs}\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalogFile","title":"AntaCatalogFile","text":"

Bases: RootModel[dict[ImportString[Any], list[AntaTestDefinition]]]

Represents an ANTA Test Catalog File.

Example:
A valid test catalog file must have the following structure:\n```\n<Python module>:\n    - <AntaTest subclass>:\n        <AntaTest.Input compliant dictionary>\n```\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalogFile.check_tests","title":"check_tests classmethod","text":"
check_tests(data: Any) -> Any\n

Allow the user to provide a Python data structure that only has string values.

This validator will try to flatten and import Python modules, check if the tests classes are actually defined in their respective Python module and instantiate Input instances with provided value to validate test inputs.

Source code in anta/catalog.py
@model_validator(mode=\"before\")\n@classmethod\ndef check_tests(cls: type[AntaCatalogFile], data: Any) -> Any:  # noqa: ANN401\n    \"\"\"Allow the user to provide a Python data structure that only has string values.\n\n    This validator will try to flatten and import Python modules, check if the tests classes\n    are actually defined in their respective Python module and instantiate Input instances\n    with provided value to validate test inputs.\n    \"\"\"\n    if isinstance(data, dict):\n        if not data:\n            return data\n        typed_data: dict[ModuleType, list[Any]] = AntaCatalogFile.flatten_modules(data)\n        for module, tests in typed_data.items():\n            test_definitions: list[AntaTestDefinition] = []\n            for test_definition in tests:\n                if isinstance(test_definition, AntaTestDefinition):\n                    test_definitions.append(test_definition)\n                    continue\n                if not isinstance(test_definition, dict):\n                    msg = f\"Syntax error when parsing: {test_definition}\\nIt must be a dictionary. Check the test catalog.\"\n                    raise ValueError(msg)  # noqa: TRY004 pydantic catches ValueError or AssertionError, no TypeError\n                if len(test_definition) != 1:\n                    msg = (\n                        f\"Syntax error when parsing: {test_definition}\\n\"\n                        \"It must be a dictionary with a single entry. Check the indentation in the test catalog.\"\n                    )\n                    raise ValueError(msg)\n                for test_name, test_inputs in test_definition.copy().items():\n                    test: type[AntaTest] | None = getattr(module, test_name, None)\n                    if test is None:\n                        msg = (\n                            f\"{test_name} is not defined in Python module {module.__name__}\"\n                            f\"{f' (from {module.__file__})' if module.__file__ is not None else ''}\"\n                        )\n                        raise ValueError(msg)\n                    test_definitions.append(AntaTestDefinition(test=test, inputs=test_inputs))\n            typed_data[module] = test_definitions\n        return typed_data\n    return data\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalogFile.flatten_modules","title":"flatten_modules staticmethod","text":"
flatten_modules(data: dict[str, Any], package: str | None = None) -> dict[ModuleType, list[Any]]\n

Allow the user to provide a data structure with nested Python modules.

Example:
```\nanta.tests.routing:\n  generic:\n    - <AntaTestDefinition>\n  bgp:\n    - <AntaTestDefinition>\n```\n`anta.tests.routing.generic` and `anta.tests.routing.bgp` are importable Python modules.\n
Source code in anta/catalog.py
@staticmethod\ndef flatten_modules(data: dict[str, Any], package: str | None = None) -> dict[ModuleType, list[Any]]:\n    \"\"\"Allow the user to provide a data structure with nested Python modules.\n\n    Example:\n    -------\n        ```\n        anta.tests.routing:\n          generic:\n            - <AntaTestDefinition>\n          bgp:\n            - <AntaTestDefinition>\n        ```\n        `anta.tests.routing.generic` and `anta.tests.routing.bgp` are importable Python modules.\n\n    \"\"\"\n    modules: dict[ModuleType, list[Any]] = {}\n    for module_name, tests in data.items():\n        if package and not module_name.startswith(\".\"):\n            # PLW2901 - we redefine the loop variable on purpose here.\n            module_name = f\".{module_name}\"  # noqa: PLW2901\n        try:\n            module: ModuleType = importlib.import_module(name=module_name, package=package)\n        except Exception as e:  # pylint: disable=broad-exception-caught\n            # A test module is potentially user-defined code.\n            # We need to catch everything if we want to have meaningful logs\n            module_str = f\"{module_name[1:] if module_name.startswith('.') else module_name}{f' from package {package}' if package else ''}\"\n            message = f\"Module named {module_str} cannot be imported. Verify that the module exists and there is no Python syntax issues.\"\n            anta_log_exception(e, message, logger)\n            raise ValueError(message) from e\n        if isinstance(tests, dict):\n            # This is an inner Python module\n            modules.update(AntaCatalogFile.flatten_modules(data=tests, package=module.__name__))\n        elif isinstance(tests, list):\n            # This is a list of AntaTestDefinition\n            modules[module] = tests\n        else:\n            msg = f\"Syntax error when parsing: {tests}\\nIt must be a list of ANTA tests. Check the test catalog.\"\n            raise ValueError(msg)  # noqa: TRY004 pydantic catches ValueError or AssertionError, no TypeError\n    return modules\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalogFile.to_json","title":"to_json","text":"
to_json() -> str\n

Return a JSON representation string of this model.

Returns:

Type Description The JSON representation string of this model. Source code in anta/catalog.py
def to_json(self) -> str:\n    \"\"\"Return a JSON representation string of this model.\n\n    Returns\n    -------\n        The JSON representation string of this model.\n    \"\"\"\n    return self.model_dump_json(serialize_as_any=True, exclude_unset=True, indent=2)\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalogFile.yaml","title":"yaml","text":"
yaml() -> str\n

Return a YAML representation string of this model.

Returns:

Type Description The YAML representation string of this model. Source code in anta/catalog.py
def yaml(self) -> str:\n    \"\"\"Return a YAML representation string of this model.\n\n    Returns\n    -------\n        The YAML representation string of this model.\n    \"\"\"\n    # TODO: Pydantic and YAML serialization/deserialization is not supported natively.\n    # This could be improved.\n    # https://github.com/pydantic/pydantic/issues/1043\n    # Explore if this worth using this: https://github.com/NowanIlfideme/pydantic-yaml\n    return safe_dump(safe_load(self.model_dump_json(serialize_as_any=True, exclude_unset=True)), indent=2, width=math.inf)\n
"},{"location":"api/device/","title":"Device","text":""},{"location":"api/device/#antadevice-base-class","title":"AntaDevice base class","text":""},{"location":"api/device/#uml-representation","title":"UML representation","text":""},{"location":"api/device/#anta.device.AntaDevice","title":"AntaDevice","text":"
AntaDevice(name: str, tags: set[str] | None = None, *, disable_cache: bool = False)\n

Bases: ABC

Abstract class representing a device in ANTA.

An implementation of this class must override the abstract coroutines _collect() and refresh().

Attributes:

Name Type Description name Device name

is_online: True if the device IP is reachable and a port can be open. established: True if remote command execution succeeds. hw_model: Hardware model of the device. tags: Tags for this device. cache: In-memory cache from aiocache library for this device (None if cache is disabled). cache_locks: Dictionary mapping keys to asyncio locks to guarantee exclusive access to the cache if not disabled.

Source code in anta/device.py
def __init__(self, name: str, tags: set[str] | None = None, *, disable_cache: bool = False) -> None:\n    \"\"\"Initialize an AntaDevice.\n\n    Parameters\n    ----------\n        name: Device name.\n        tags: Tags for this device.\n        disable_cache: Disable caching for all commands for this device.\n\n    \"\"\"\n    self.name: str = name\n    self.hw_model: str | None = None\n    self.tags: set[str] = tags if tags is not None else set()\n    # A device always has its own name as tag\n    self.tags.add(self.name)\n    self.is_online: bool = False\n    self.established: bool = False\n    self.cache: Cache | None = None\n    self.cache_locks: defaultdict[str, asyncio.Lock] | None = None\n\n    # Initialize cache if not disabled\n    if not disable_cache:\n        self._init_cache()\n
"},{"location":"api/device/#anta.device.AntaDevice.cache_statistics","title":"cache_statistics property","text":"
cache_statistics: dict[str, Any] | None\n

Returns the device cache statistics for logging purposes.

"},{"location":"api/device/#anta.device.AntaDevice.__hash__","title":"__hash__","text":"
__hash__() -> int\n

Implement hashing for AntaDevice objects.

Source code in anta/device.py
def __hash__(self) -> int:\n    \"\"\"Implement hashing for AntaDevice objects.\"\"\"\n    return hash(self._keys)\n
"},{"location":"api/device/#anta.device.AntaDevice.collect","title":"collect async","text":"
collect(command: AntaCommand, *, collection_id: str | None = None) -> None\n

Collect the output for a specified command.

When caching is activated on both the device and the command, this method prioritizes retrieving the output from the cache. In cases where the output isn\u2019t cached yet, it will be freshly collected and then stored in the cache for future access. The method employs asynchronous locks based on the command\u2019s UID to guarantee exclusive access to the cache.

When caching is NOT enabled, either at the device or command level, the method directly collects the output via the private _collect method without interacting with the cache.

Source code in anta/device.py
async def collect(self, command: AntaCommand, *, collection_id: str | None = None) -> None:\n    \"\"\"Collect the output for a specified command.\n\n    When caching is activated on both the device and the command,\n    this method prioritizes retrieving the output from the cache. In cases where the output isn't cached yet,\n    it will be freshly collected and then stored in the cache for future access.\n    The method employs asynchronous locks based on the command's UID to guarantee exclusive access to the cache.\n\n    When caching is NOT enabled, either at the device or command level, the method directly collects the output\n    via the private `_collect` method without interacting with the cache.\n\n    Parameters\n    ----------\n        command: The command to collect.\n        collection_id: An identifier used to build the eAPI request ID.\n    \"\"\"\n    # Need to ignore pylint no-member as Cache is a proxy class and pylint is not smart enough\n    # https://github.com/pylint-dev/pylint/issues/7258\n    if self.cache is not None and self.cache_locks is not None and command.use_cache:\n        async with self.cache_locks[command.uid]:\n            cached_output = await self.cache.get(command.uid)  # pylint: disable=no-member\n\n            if cached_output is not None:\n                logger.debug(\"Cache hit for %s on %s\", command.command, self.name)\n                command.output = cached_output\n            else:\n                await self._collect(command=command, collection_id=collection_id)\n                await self.cache.set(command.uid, command.output)  # pylint: disable=no-member\n    else:\n        await self._collect(command=command, collection_id=collection_id)\n
"},{"location":"api/device/#anta.device.AntaDevice.collect_commands","title":"collect_commands async","text":"
collect_commands(commands: list[AntaCommand], *, collection_id: str | None = None) -> None\n

Collect multiple commands.

Source code in anta/device.py
async def collect_commands(self, commands: list[AntaCommand], *, collection_id: str | None = None) -> None:\n    \"\"\"Collect multiple commands.\n\n    Parameters\n    ----------\n        commands: The commands to collect.\n        collection_id: An identifier used to build the eAPI request ID.\n    \"\"\"\n    await asyncio.gather(*(self.collect(command=command, collection_id=collection_id) for command in commands))\n
"},{"location":"api/device/#anta.device.AntaDevice.copy","title":"copy async","text":"
copy(sources: list[Path], destination: Path, direction: Literal['to', 'from'] = 'from') -> None\n

Copy files to and from the device, usually through SCP.

It is not mandatory to implement this for a valid AntaDevice subclass.

Source code in anta/device.py
async def copy(self, sources: list[Path], destination: Path, direction: Literal[\"to\", \"from\"] = \"from\") -> None:\n    \"\"\"Copy files to and from the device, usually through SCP.\n\n    It is not mandatory to implement this for a valid AntaDevice subclass.\n\n    Parameters\n    ----------\n        sources: List of files to copy to or from the device.\n        destination: Local or remote destination when copying the files. Can be a folder.\n        direction: Defines if this coroutine copies files to or from the device.\n\n    \"\"\"\n    _ = (sources, destination, direction)\n    msg = f\"copy() method has not been implemented in {self.__class__.__name__} definition\"\n    raise NotImplementedError(msg)\n
"},{"location":"api/device/#anta.device.AntaDevice.refresh","title":"refresh abstractmethod async","text":"
refresh() -> None\n

Update attributes of an AntaDevice instance.

This coroutine must update the following attributes of AntaDevice: - is_online: When the device IP is reachable and a port can be open - established: When a command execution succeeds - hw_model: The hardware model of the device

Source code in anta/device.py
@abstractmethod\nasync def refresh(self) -> None:\n    \"\"\"Update attributes of an AntaDevice instance.\n\n    This coroutine must update the following attributes of AntaDevice:\n        - `is_online`: When the device IP is reachable and a port can be open\n        - `established`: When a command execution succeeds\n        - `hw_model`: The hardware model of the device\n    \"\"\"\n
"},{"location":"api/device/#async-eos-device-class","title":"Async EOS device class","text":""},{"location":"api/device/#uml-representation_1","title":"UML representation","text":""},{"location":"api/device/#anta.device.AsyncEOSDevice","title":"AsyncEOSDevice","text":"
AsyncEOSDevice(host: str, username: str, password: str, name: str | None = None, enable_password: str | None = None, port: int | None = None, ssh_port: int | None = 22, tags: set[str] | None = None, timeout: float | None = None, proto: Literal['http', 'https'] = 'https', *, enable: bool = False, insecure: bool = False, disable_cache: bool = False)\n

Bases: AntaDevice

Implementation of AntaDevice for EOS using aio-eapi.

Attributes:

Name Type Description name Device name

is_online: True if the device IP is reachable and a port can be open established: True if remote command execution succeeds hw_model: Hardware model of the device tags: Tags for this device

Source code in anta/device.py
def __init__(\n    self,\n    host: str,\n    username: str,\n    password: str,\n    name: str | None = None,\n    enable_password: str | None = None,\n    port: int | None = None,\n    ssh_port: int | None = 22,\n    tags: set[str] | None = None,\n    timeout: float | None = None,\n    proto: Literal[\"http\", \"https\"] = \"https\",\n    *,\n    enable: bool = False,\n    insecure: bool = False,\n    disable_cache: bool = False,\n) -> None:\n    \"\"\"Instantiate an AsyncEOSDevice.\n\n    Parameters\n    ----------\n        host: Device FQDN or IP.\n        username: Username to connect to eAPI and SSH.\n        password: Password to connect to eAPI and SSH.\n        name: Device name.\n        enable: Collect commands using privileged mode.\n        enable_password: Password used to gain privileged access on EOS.\n        port: eAPI port. Defaults to 80 is proto is 'http' or 443 if proto is 'https'.\n        ssh_port: SSH port.\n        tags: Tags for this device.\n        timeout: Timeout value in seconds for outgoing API calls.\n        insecure: Disable SSH Host Key validation.\n        proto: eAPI protocol. Value can be 'http' or 'https'.\n        disable_cache: Disable caching for all commands for this device.\n\n    \"\"\"\n    if host is None:\n        message = \"'host' is required to create an AsyncEOSDevice\"\n        logger.error(message)\n        raise ValueError(message)\n    if name is None:\n        name = f\"{host}{f':{port}' if port else ''}\"\n    super().__init__(name, tags, disable_cache=disable_cache)\n    if username is None:\n        message = f\"'username' is required to instantiate device '{self.name}'\"\n        logger.error(message)\n        raise ValueError(message)\n    if password is None:\n        message = f\"'password' is required to instantiate device '{self.name}'\"\n        logger.error(message)\n        raise ValueError(message)\n    self.enable = enable\n    self._enable_password = enable_password\n    self._session: asynceapi.Device = asynceapi.Device(host=host, port=port, username=username, password=password, proto=proto, timeout=timeout)\n    ssh_params: dict[str, Any] = {}\n    if insecure:\n        ssh_params[\"known_hosts\"] = None\n    self._ssh_opts: SSHClientConnectionOptions = SSHClientConnectionOptions(\n        host=host, port=ssh_port, username=username, password=password, client_keys=CLIENT_KEYS, **ssh_params\n    )\n
"},{"location":"api/device/#anta.device.AsyncEOSDevice.copy","title":"copy async","text":"
copy(sources: list[Path], destination: Path, direction: Literal['to', 'from'] = 'from') -> None\n

Copy files to and from the device using asyncssh.scp().

Source code in anta/device.py
async def copy(self, sources: list[Path], destination: Path, direction: Literal[\"to\", \"from\"] = \"from\") -> None:\n    \"\"\"Copy files to and from the device using asyncssh.scp().\n\n    Parameters\n    ----------\n        sources: List of files to copy to or from the device.\n        destination: Local or remote destination when copying the files. Can be a folder.\n        direction: Defines if this coroutine copies files to or from the device.\n\n    \"\"\"\n    async with asyncssh.connect(\n        host=self._ssh_opts.host,\n        port=self._ssh_opts.port,\n        tunnel=self._ssh_opts.tunnel,\n        family=self._ssh_opts.family,\n        local_addr=self._ssh_opts.local_addr,\n        options=self._ssh_opts,\n    ) as conn:\n        src: list[tuple[SSHClientConnection, Path]] | list[Path]\n        dst: tuple[SSHClientConnection, Path] | Path\n        if direction == \"from\":\n            src = [(conn, file) for file in sources]\n            dst = destination\n            for file in sources:\n                message = f\"Copying '{file}' from device {self.name} to '{destination}' locally\"\n                logger.info(message)\n\n        elif direction == \"to\":\n            src = sources\n            dst = conn, destination\n            for file in src:\n                message = f\"Copying '{file}' to device {self.name} to '{destination}' remotely\"\n                logger.info(message)\n\n        else:\n            logger.critical(\"'direction' argument to copy() function is invalid: %s\", direction)\n\n            return\n        await asyncssh.scp(src, dst)\n
"},{"location":"api/device/#anta.device.AsyncEOSDevice.refresh","title":"refresh async","text":"
refresh() -> None\n

Update attributes of an AsyncEOSDevice instance.

This coroutine must update the following attributes of AsyncEOSDevice: - is_online: When a device IP is reachable and a port can be open - established: When a command execution succeeds - hw_model: The hardware model of the device

Source code in anta/device.py
async def refresh(self) -> None:\n    \"\"\"Update attributes of an AsyncEOSDevice instance.\n\n    This coroutine must update the following attributes of AsyncEOSDevice:\n    - is_online: When a device IP is reachable and a port can be open\n    - established: When a command execution succeeds\n    - hw_model: The hardware model of the device\n    \"\"\"\n    logger.debug(\"Refreshing device %s\", self.name)\n    self.is_online = await self._session.check_connection()\n    if self.is_online:\n        show_version = AntaCommand(command=\"show version\")\n        await self._collect(show_version)\n        if not show_version.collected:\n            logger.warning(\"Cannot get hardware information from device %s\", self.name)\n        else:\n            self.hw_model = show_version.json_output.get(\"modelName\", None)\n            if self.hw_model is None:\n                logger.critical(\"Cannot parse 'show version' returned by device %s\", self.name)\n    else:\n        logger.warning(\"Could not connect to device %s: cannot open eAPI port\", self.name)\n\n    self.established = bool(self.is_online and self.hw_model)\n
"},{"location":"api/inventory/","title":"Inventory module","text":""},{"location":"api/inventory/#anta.inventory.AntaInventory","title":"AntaInventory","text":"

Bases: dict[str, AntaDevice]

Inventory abstraction for ANTA framework.

"},{"location":"api/inventory/#anta.inventory.AntaInventory.devices","title":"devices property","text":"
devices: list[AntaDevice]\n

List of AntaDevice in this inventory.

"},{"location":"api/inventory/#anta.inventory.AntaInventory.__setitem__","title":"__setitem__","text":"
__setitem__(key: str, value: AntaDevice) -> None\n

Set a device in the inventory.

Source code in anta/inventory/__init__.py
def __setitem__(self, key: str, value: AntaDevice) -> None:\n    \"\"\"Set a device in the inventory.\"\"\"\n    if key != value.name:\n        msg = f\"The key must be the device name for device '{value.name}'. Use AntaInventory.add_device().\"\n        raise RuntimeError(msg)\n    return super().__setitem__(key, value)\n
"},{"location":"api/inventory/#anta.inventory.AntaInventory.add_device","title":"add_device","text":"
add_device(device: AntaDevice) -> None\n

Add a device to final inventory.

Source code in anta/inventory/__init__.py
def add_device(self, device: AntaDevice) -> None:\n    \"\"\"Add a device to final inventory.\n\n    Parameters\n    ----------\n        device: Device object to be added\n\n    \"\"\"\n    self[device.name] = device\n
"},{"location":"api/inventory/#anta.inventory.AntaInventory.connect_inventory","title":"connect_inventory async","text":"
connect_inventory() -> None\n

Run refresh() coroutines for all AntaDevice objects in this inventory.

Source code in anta/inventory/__init__.py
async def connect_inventory(self) -> None:\n    \"\"\"Run `refresh()` coroutines for all AntaDevice objects in this inventory.\"\"\"\n    logger.debug(\"Refreshing devices...\")\n    results = await asyncio.gather(\n        *(device.refresh() for device in self.values()),\n        return_exceptions=True,\n    )\n    for r in results:\n        if isinstance(r, Exception):\n            message = \"Error when refreshing inventory\"\n            anta_log_exception(r, message, logger)\n
"},{"location":"api/inventory/#anta.inventory.AntaInventory.get_inventory","title":"get_inventory","text":"
get_inventory(*, established_only: bool = False, tags: set[str] | None = None, devices: set[str] | None = None) -> AntaInventory\n

Return a filtered inventory.

Returns:

Type Description An inventory with filtered AntaDevice objects. Source code in anta/inventory/__init__.py
def get_inventory(self, *, established_only: bool = False, tags: set[str] | None = None, devices: set[str] | None = None) -> AntaInventory:\n    \"\"\"Return a filtered inventory.\n\n    Parameters\n    ----------\n        established_only: Whether or not to include only established devices.\n        tags: Tags to filter devices.\n        devices: Names to filter devices.\n\n    Returns\n    -------\n        An inventory with filtered AntaDevice objects.\n    \"\"\"\n\n    def _filter_devices(device: AntaDevice) -> bool:\n        \"\"\"Select the devices based on the inputs `tags`, `devices` and `established_only`.\"\"\"\n        if tags is not None and all(tag not in tags for tag in device.tags):\n            return False\n        if devices is None or device.name in devices:\n            return bool(not established_only or device.established)\n        return False\n\n    filtered_devices: list[AntaDevice] = list(filter(_filter_devices, self.values()))\n    result = AntaInventory()\n    for device in filtered_devices:\n        result.add_device(device)\n    return result\n
"},{"location":"api/inventory/#anta.inventory.AntaInventory.parse","title":"parse staticmethod","text":"
parse(filename: str | Path, username: str, password: str, enable_password: str | None = None, timeout: float | None = None, *, enable: bool = False, insecure: bool = False, disable_cache: bool = False) -> AntaInventory\n

Create an AntaInventory instance from an inventory file.

The inventory devices are AsyncEOSDevice instances.

Raises:

Type Description InventoryRootKeyError: Root key of inventory is missing.

InventoryIncorrectSchemaError: Inventory file is not following AntaInventory Schema.

Source code in anta/inventory/__init__.py
@staticmethod\ndef parse(\n    filename: str | Path,\n    username: str,\n    password: str,\n    enable_password: str | None = None,\n    timeout: float | None = None,\n    *,\n    enable: bool = False,\n    insecure: bool = False,\n    disable_cache: bool = False,\n) -> AntaInventory:\n    \"\"\"Create an AntaInventory instance from an inventory file.\n\n    The inventory devices are AsyncEOSDevice instances.\n\n    Parameters\n    ----------\n        filename: Path to device inventory YAML file.\n        username: Username to use to connect to devices.\n        password: Password to use to connect to devices.\n        enable_password: Enable password to use if required.\n        timeout: Timeout value in seconds for outgoing API calls.\n        enable: Whether or not the commands need to be run in enable mode towards the devices.\n        insecure: Disable SSH Host Key validation.\n        disable_cache: Disable cache globally.\n\n    Raises\n    ------\n        InventoryRootKeyError: Root key of inventory is missing.\n        InventoryIncorrectSchemaError: Inventory file is not following AntaInventory Schema.\n\n    \"\"\"\n    inventory = AntaInventory()\n    kwargs: dict[str, Any] = {\n        \"username\": username,\n        \"password\": password,\n        \"enable\": enable,\n        \"enable_password\": enable_password,\n        \"timeout\": timeout,\n        \"insecure\": insecure,\n        \"disable_cache\": disable_cache,\n    }\n    if username is None:\n        message = \"'username' is required to create an AntaInventory\"\n        logger.error(message)\n        raise ValueError(message)\n    if password is None:\n        message = \"'password' is required to create an AntaInventory\"\n        logger.error(message)\n        raise ValueError(message)\n\n    try:\n        filename = Path(filename)\n        with filename.open(encoding=\"UTF-8\") as file:\n            data = safe_load(file)\n    except (TypeError, YAMLError, OSError) as e:\n        message = f\"Unable to parse ANTA Device Inventory file '{filename}'\"\n        anta_log_exception(e, message, logger)\n        raise\n\n    if AntaInventory.INVENTORY_ROOT_KEY not in data:\n        exc = InventoryRootKeyError(f\"Inventory root key ({AntaInventory.INVENTORY_ROOT_KEY}) is not defined in your inventory\")\n        anta_log_exception(exc, f\"Device inventory is invalid! (from {filename})\", logger)\n        raise exc\n\n    try:\n        inventory_input = AntaInventoryInput(**data[AntaInventory.INVENTORY_ROOT_KEY])\n    except ValidationError as e:\n        anta_log_exception(e, f\"Device inventory is invalid! (from {filename})\", logger)\n        raise\n\n    # Read data from input\n    AntaInventory._parse_hosts(inventory_input, inventory, **kwargs)\n    AntaInventory._parse_networks(inventory_input, inventory, **kwargs)\n    AntaInventory._parse_ranges(inventory_input, inventory, **kwargs)\n\n    return inventory\n
"},{"location":"api/inventory/#anta.inventory.exceptions","title":"exceptions","text":"

Manage Exception in Inventory module.

"},{"location":"api/inventory/#anta.inventory.exceptions.InventoryIncorrectSchemaError","title":"InventoryIncorrectSchemaError","text":"

Bases: Exception

Error when user data does not follow ANTA schema.

"},{"location":"api/inventory/#anta.inventory.exceptions.InventoryRootKeyError","title":"InventoryRootKeyError","text":"

Bases: Exception

Error raised when inventory root key is not found.

"},{"location":"api/inventory.models.input/","title":"Inventory models","text":""},{"location":"api/inventory.models.input/#anta.inventory.models.AntaInventoryInput","title":"AntaInventoryInput","text":"

Bases: BaseModel

Device inventory input model.

"},{"location":"api/inventory.models.input/#anta.inventory.models.AntaInventoryInput.yaml","title":"yaml","text":"
yaml() -> str\n

Return a YAML representation string of this model.

Returns:

Type Description The YAML representation string of this model. Source code in anta/inventory/models.py
def yaml(self) -> str:\n    \"\"\"Return a YAML representation string of this model.\n\n    Returns\n    -------\n        The YAML representation string of this model.\n    \"\"\"\n    # TODO: Pydantic and YAML serialization/deserialization is not supported natively.\n    # This could be improved.\n    # https://github.com/pydantic/pydantic/issues/1043\n    # Explore if this worth using this: https://github.com/NowanIlfideme/pydantic-yaml\n    return yaml.safe_dump(yaml.safe_load(self.model_dump_json(serialize_as_any=True, exclude_unset=True)), indent=2, width=math.inf)\n
"},{"location":"api/inventory.models.input/#anta.inventory.models.AntaInventoryHost","title":"AntaInventoryHost","text":"

Bases: BaseModel

Host entry of AntaInventoryInput.

Attributes:

Name Type Description host IP Address or FQDN of the device.

port: Custom eAPI port to use. name: Custom name of the device. tags: Tags of the device. disable_cache: Disable cache for this device.

"},{"location":"api/inventory.models.input/#anta.inventory.models.AntaInventoryNetwork","title":"AntaInventoryNetwork","text":"

Bases: BaseModel

Network entry of AntaInventoryInput.

Attributes:

Name Type Description network Subnet to use for scanning.

tags: Tags of the devices in this network. disable_cache: Disable cache for all devices in this network.

"},{"location":"api/inventory.models.input/#anta.inventory.models.AntaInventoryRange","title":"AntaInventoryRange","text":"

Bases: BaseModel

IP Range entry of AntaInventoryInput.

Attributes:

Name Type Description start IPv4 or IPv6 address for the beginning of the range.

stop: IPv4 or IPv6 address for the end of the range. tags: Tags of the devices in this IP range. disable_cache: Disable cache for all devices in this IP range.

"},{"location":"api/models/","title":"Test models","text":""},{"location":"api/models/#test-definition","title":"Test definition","text":""},{"location":"api/models/#uml-diagram","title":"UML Diagram","text":""},{"location":"api/models/#anta.models.AntaTest","title":"AntaTest","text":"
AntaTest(device: AntaDevice, inputs: dict[str, Any] | AntaTest.Input | None = None, eos_data: list[dict[Any, Any] | str] | None = None)\n

Bases: ABC

Abstract class defining a test in ANTA.

The goal of this class is to handle the heavy lifting and make writing a test as simple as possible.

Examples

The following is an example of an AntaTest subclass implementation:

    class VerifyReachability(AntaTest):\n        name = \"VerifyReachability\"\n        description = \"Test the network reachability to one or many destination IP(s).\"\n        categories = [\"connectivity\"]\n        commands = [AntaTemplate(template=\"ping vrf {vrf} {dst} source {src} repeat 2\")]\n\n        class Input(AntaTest.Input):\n            hosts: list[Host]\n            class Host(BaseModel):\n                dst: IPv4Address\n                src: IPv4Address\n                vrf: str = \"default\"\n\n        def render(self, template: AntaTemplate) -> list[AntaCommand]:\n            return [template.render(dst=host.dst, src=host.src, vrf=host.vrf) for host in self.inputs.hosts]\n\n        @AntaTest.anta_test\n        def test(self) -> None:\n            failures = []\n            for command in self.instance_commands:\n                src, dst = command.params.src, command.params.dst\n                if \"2 received\" not in command.json_output[\"messages\"][0]:\n                    failures.append((str(src), str(dst)))\n            if not failures:\n                self.result.is_success()\n            else:\n                self.result.is_failure(f\"Connectivity test failed for the following source-destination pairs: {failures}\")\n

Attributes:

Name Type Description device AntaDevice instance on which this test is run

inputs: AntaTest.Input instance carrying the test inputs instance_commands: List of AntaCommand instances of this test result: TestResult instance representing the result of this test logger: Python logger for this test instance

Source code in anta/models.py
def __init__(\n    self,\n    device: AntaDevice,\n    inputs: dict[str, Any] | AntaTest.Input | None = None,\n    eos_data: list[dict[Any, Any] | str] | None = None,\n) -> None:\n    \"\"\"AntaTest Constructor.\n\n    Parameters\n    ----------\n        device: AntaDevice instance on which the test will be run\n        inputs: dictionary of attributes used to instantiate the AntaTest.Input instance\n        eos_data: Populate outputs of the test commands instead of collecting from devices.\n                  This list must have the same length and order than the `instance_commands` instance attribute.\n    \"\"\"\n    self.logger: logging.Logger = logging.getLogger(f\"{self.module}.{self.__class__.__name__}\")\n    self.device: AntaDevice = device\n    self.inputs: AntaTest.Input\n    self.instance_commands: list[AntaCommand] = []\n    self.result: TestResult = TestResult(\n        name=device.name,\n        test=self.name,\n        categories=self.categories,\n        description=self.description,\n    )\n    self._init_inputs(inputs)\n    if self.result.result == \"unset\":\n        self._init_commands(eos_data)\n
"},{"location":"api/models/#anta.models.AntaTest.blocked","title":"blocked property","text":"
blocked: bool\n

Check if CLI commands contain a blocked keyword.

"},{"location":"api/models/#anta.models.AntaTest.collected","title":"collected property","text":"
collected: bool\n

Return True if all commands for this test have been collected.

"},{"location":"api/models/#anta.models.AntaTest.failed_commands","title":"failed_commands property","text":"
failed_commands: list[AntaCommand]\n

Return a list of all the commands that have failed.

"},{"location":"api/models/#anta.models.AntaTest.module","title":"module property","text":"
module: str\n

Return the Python module in which this AntaTest class is defined.

"},{"location":"api/models/#anta.models.AntaTest.Input","title":"Input","text":"

Bases: BaseModel

Class defining inputs for a test in ANTA.

Examples

A valid test catalog will look like the following:

<Python module>:\n- <AntaTest subclass>:\n    result_overwrite:\n        categories:\n        - \"Overwritten category 1\"\n        description: \"Test with overwritten description\"\n        custom_field: \"Test run by John Doe\"\n

Attributes:

Name Type Description result_overwrite Define fields to overwrite in the TestResult object"},{"location":"api/models/#anta.models.AntaTest.Input.Filters","title":"Filters","text":"

Bases: BaseModel

Runtime filters to map tests with list of tags or devices.

Attributes:

Name Type Description tags Tag of devices on which to run the test."},{"location":"api/models/#anta.models.AntaTest.Input.ResultOverwrite","title":"ResultOverwrite","text":"

Bases: BaseModel

Test inputs model to overwrite result fields.

Attributes:

Name Type Description description overwrite TestResult.description

categories: overwrite TestResult.categories custom_field: a free string that will be included in the TestResult object

"},{"location":"api/models/#anta.models.AntaTest.Input.__hash__","title":"__hash__","text":"
__hash__() -> int\n

Implement generic hashing for AntaTest.Input.

This will work in most cases but this does not consider 2 lists with different ordering as equal.

Source code in anta/models.py
def __hash__(self) -> int:\n    \"\"\"Implement generic hashing for AntaTest.Input.\n\n    This will work in most cases but this does not consider 2 lists with different ordering as equal.\n    \"\"\"\n    return hash(self.model_dump_json())\n
"},{"location":"api/models/#anta.models.AntaTest.anta_test","title":"anta_test staticmethod","text":"
anta_test(function: F) -> Callable[..., Coroutine[Any, Any, TestResult]]\n

Decorate the test() method in child classes.

This decorator implements (in this order):

  1. Instantiate the command outputs if eos_data is provided to the test() method
  2. Collect the commands from the device
  3. Run the test() method
  4. Catches any exception in test() user code and set the result instance attribute
Source code in anta/models.py
@staticmethod\ndef anta_test(function: F) -> Callable[..., Coroutine[Any, Any, TestResult]]:\n    \"\"\"Decorate the `test()` method in child classes.\n\n    This decorator implements (in this order):\n\n    1. Instantiate the command outputs if `eos_data` is provided to the `test()` method\n    2. Collect the commands from the device\n    3. Run the `test()` method\n    4. Catches any exception in `test()` user code and set the `result` instance attribute\n    \"\"\"\n\n    @wraps(function)\n    async def wrapper(\n        self: AntaTest,\n        eos_data: list[dict[Any, Any] | str] | None = None,\n        **kwargs: dict[str, Any],\n    ) -> TestResult:\n        \"\"\"Inner function for the anta_test decorator.\n\n        Parameters\n        ----------\n            self: The test instance.\n            eos_data: Populate outputs of the test commands instead of collecting from devices.\n                      This list must have the same length and order than the `instance_commands` instance attribute.\n            kwargs: Any keyword argument to pass to the test.\n\n        Returns\n        -------\n            result: TestResult instance attribute populated with error status if any\n\n        \"\"\"\n        if self.result.result != \"unset\":\n            return self.result\n\n        # Data\n        if eos_data is not None:\n            self.save_commands_data(eos_data)\n            self.logger.debug(\"Test %s initialized with input data %s\", self.name, eos_data)\n\n        # If some data is missing, try to collect\n        if not self.collected:\n            await self.collect()\n            if self.result.result != \"unset\":\n                AntaTest.update_progress()\n                return self.result\n\n            if cmds := self.failed_commands:\n                unsupported_commands = [f\"'{c.command}' is not supported on {self.device.hw_model}\" for c in cmds if not c.supported]\n                if unsupported_commands:\n                    msg = f\"Test {self.name} has been skipped because it is not supported on {self.device.hw_model}: {GITHUB_SUGGESTION}\"\n                    self.logger.warning(msg)\n                    self.result.is_skipped(\"\\n\".join(unsupported_commands))\n                else:\n                    self.result.is_error(message=\"\\n\".join([f\"{c.command} has failed: {', '.join(c.errors)}\" for c in cmds]))\n                AntaTest.update_progress()\n                return self.result\n\n        try:\n            function(self, **kwargs)\n        except Exception as e:  # pylint: disable=broad-exception-caught\n            # test() is user-defined code.\n            # We need to catch everything if we want the AntaTest object\n            # to live until the reporting\n            message = f\"Exception raised for test {self.name} (on device {self.device.name})\"\n            anta_log_exception(e, message, self.logger)\n            self.result.is_error(message=exc_to_str(e))\n\n        # TODO: find a correct way to time test execution\n        AntaTest.update_progress()\n        return self.result\n\n    return wrapper\n
"},{"location":"api/models/#anta.models.AntaTest.collect","title":"collect async","text":"
collect() -> None\n

Collect outputs of all commands of this test class from the device of this test instance.

Source code in anta/models.py
async def collect(self) -> None:\n    \"\"\"Collect outputs of all commands of this test class from the device of this test instance.\"\"\"\n    try:\n        if self.blocked is False:\n            await self.device.collect_commands(self.instance_commands, collection_id=self.name)\n    except Exception as e:  # pylint: disable=broad-exception-caught\n        # device._collect() is user-defined code.\n        # We need to catch everything if we want the AntaTest object\n        # to live until the reporting\n        message = f\"Exception raised while collecting commands for test {self.name} (on device {self.device.name})\"\n        anta_log_exception(e, message, self.logger)\n        self.result.is_error(message=exc_to_str(e))\n
"},{"location":"api/models/#anta.models.AntaTest.render","title":"render","text":"
render(template: AntaTemplate) -> list[AntaCommand]\n

Render an AntaTemplate instance of this AntaTest using the provided AntaTest.Input instance at self.inputs.

This is not an abstract method because it does not need to be implemented if there is no AntaTemplate for this test.

Source code in anta/models.py
def render(self, template: AntaTemplate) -> list[AntaCommand]:\n    \"\"\"Render an AntaTemplate instance of this AntaTest using the provided AntaTest.Input instance at self.inputs.\n\n    This is not an abstract method because it does not need to be implemented if there is\n    no AntaTemplate for this test.\n    \"\"\"\n    _ = template\n    msg = f\"AntaTemplate are provided but render() method has not been implemented for {self.module}.{self.__class__.__name__}\"\n    raise NotImplementedError(msg)\n
"},{"location":"api/models/#anta.models.AntaTest.save_commands_data","title":"save_commands_data","text":"
save_commands_data(eos_data: list[dict[str, Any] | str]) -> None\n

Populate output of all AntaCommand instances in instance_commands.

Source code in anta/models.py
def save_commands_data(self, eos_data: list[dict[str, Any] | str]) -> None:\n    \"\"\"Populate output of all AntaCommand instances in `instance_commands`.\"\"\"\n    if len(eos_data) > len(self.instance_commands):\n        self.result.is_error(message=\"Test initialization error: Trying to save more data than there are commands for the test\")\n        return\n    if len(eos_data) < len(self.instance_commands):\n        self.result.is_error(message=\"Test initialization error: Trying to save less data than there are commands for the test\")\n        return\n    for index, data in enumerate(eos_data or []):\n        self.instance_commands[index].output = data\n
"},{"location":"api/models/#anta.models.AntaTest.test","title":"test abstractmethod","text":"
test() -> Coroutine[Any, Any, TestResult]\n

Core of the test logic.

This is an abstractmethod that must be implemented by child classes. It must set the correct status of the result instance attribute with the appropriate outcome of the test.

Examples

It must be implemented using the AntaTest.anta_test decorator:

@AntaTest.anta_test\ndef test(self) -> None:\n    self.result.is_success()\n    for command in self.instance_commands:\n        if not self._test_command(command): # _test_command() is an arbitrary test logic\n            self.result.is_failure(\"Failure reason\")\n

Source code in anta/models.py
@abstractmethod\ndef test(self) -> Coroutine[Any, Any, TestResult]:\n    \"\"\"Core of the test logic.\n\n    This is an abstractmethod that must be implemented by child classes.\n    It must set the correct status of the `result` instance attribute with the appropriate outcome of the test.\n\n    Examples\n    --------\n    It must be implemented using the `AntaTest.anta_test` decorator:\n        ```python\n        @AntaTest.anta_test\n        def test(self) -> None:\n            self.result.is_success()\n            for command in self.instance_commands:\n                if not self._test_command(command): # _test_command() is an arbitrary test logic\n                    self.result.is_failure(\"Failure reason\")\n        ```\n\n    \"\"\"\n
"},{"location":"api/models/#command-definition","title":"Command definition","text":""},{"location":"api/models/#uml-diagram_1","title":"UML Diagram","text":"

Warning

CLI commands are protected to avoid execution of critical commands such as reload or write erase.

  • Reload command: ^reload\\s*\\w*
  • Configure mode: ^conf\\w*\\s*(terminal|session)*
  • Write: ^wr\\w*\\s*\\w+
"},{"location":"api/models/#anta.models.AntaCommand","title":"AntaCommand","text":"

Bases: BaseModel

Class to define a command.

Info

eAPI models are revisioned, this means that if a model is modified in a non-backwards compatible way, then its revision will be bumped up (revisions are numbers, default value is 1).

By default an eAPI request will return revision 1 of the model instance, this ensures that older management software will not suddenly stop working when a switch is upgraded. A revision applies to a particular CLI command whereas a version is global and is internally translated to a specific revision for each CLI command in the RPC.

Revision has precedence over version.

Attributes:

Name Type Description command Device command

version: eAPI version - valid values are 1 or \u201clatest\u201d. revision: eAPI revision of the command. Valid values are 1 to 99. Revision has precedence over version. ofmt: eAPI output - json or text. output: Output of the command. Only defined if there was no errors. template: AntaTemplate object used to render this command. errors: If the command execution fails, eAPI returns a list of strings detailing the error(s). params: Pydantic Model containing the variables values used to render the template. use_cache: Enable or disable caching for this AntaCommand if the AntaDevice supports it.

"},{"location":"api/models/#anta.models.AntaCommand.collected","title":"collected property","text":"
collected: bool\n

Return True if the command has been collected, False otherwise.

A command that has not been collected could have returned an error. See error property.

"},{"location":"api/models/#anta.models.AntaCommand.error","title":"error property","text":"
error: bool\n

Return True if the command returned an error, False otherwise.

"},{"location":"api/models/#anta.models.AntaCommand.json_output","title":"json_output property","text":"
json_output: dict[str, Any]\n

Get the command output as JSON.

"},{"location":"api/models/#anta.models.AntaCommand.requires_privileges","title":"requires_privileges property","text":"
requires_privileges: bool\n

Return True if the command requires privileged mode, False otherwise.

Raises:

Type Description RuntimeError

If the command has not been collected and has not returned an error. AntaDevice.collect() must be called before this property.

"},{"location":"api/models/#anta.models.AntaCommand.supported","title":"supported property","text":"
supported: bool\n

Return True if the command is supported on the device hardware platform, False otherwise.

Raises:

Type Description RuntimeError

If the command has not been collected and has not returned an error. AntaDevice.collect() must be called before this property.

"},{"location":"api/models/#anta.models.AntaCommand.text_output","title":"text_output property","text":"
text_output: str\n

Get the command output as a string.

"},{"location":"api/models/#anta.models.AntaCommand.uid","title":"uid property","text":"
uid: str\n

Generate a unique identifier for this command.

"},{"location":"api/models/#template-definition","title":"Template definition","text":""},{"location":"api/models/#uml-diagram_2","title":"UML Diagram","text":""},{"location":"api/models/#anta.models.AntaTemplate","title":"AntaTemplate","text":"
AntaTemplate(template: str, version: Literal[1, 'latest'] = 'latest', revision: Revision | None = None, ofmt: Literal['json', 'text'] = 'json', *, use_cache: bool = True)\n

Class to define a command template as Python f-string.

Can render a command from parameters.

Attributes:

Name Type Description template Python f-string. Example: 'show vlan {vlan_id}'

version: eAPI version - valid values are 1 or \u201clatest\u201d. revision: Revision of the command. Valid values are 1 to 99. Revision has precedence over version. ofmt: eAPI output - json or text. use_cache: Enable or disable caching for this AntaTemplate if the AntaDevice supports it.

Source code in anta/models.py
def __init__(  # noqa: PLR0913\n    self,\n    template: str,\n    version: Literal[1, \"latest\"] = \"latest\",\n    revision: Revision | None = None,\n    ofmt: Literal[\"json\", \"text\"] = \"json\",\n    *,\n    use_cache: bool = True,\n) -> None:\n    # pylint: disable=too-many-arguments\n    self.template = template\n    self.version = version\n    self.revision = revision\n    self.ofmt = ofmt\n    self.use_cache = use_cache\n\n    # Create a AntaTemplateParams model to elegantly store AntaTemplate variables\n    field_names = [fname for _, fname, _, _ in Formatter().parse(self.template) if fname]\n    # Extracting the type from the params based on the expected field_names from the template\n    fields: dict[str, Any] = {key: (Any, ...) for key in field_names}\n    self.params_schema = create_model(\n        \"AntaParams\",\n        __base__=AntaParamsBaseModel,\n        **fields,\n    )\n
"},{"location":"api/models/#anta.models.AntaTemplate.__repr__","title":"__repr__","text":"
__repr__() -> str\n

Return the representation of the class.

Copying pydantic model style, excluding params_schema

Source code in anta/models.py
def __repr__(self) -> str:\n    \"\"\"Return the representation of the class.\n\n    Copying pydantic model style, excluding `params_schema`\n    \"\"\"\n    return \" \".join(f\"{a}={v!r}\" for a, v in vars(self).items() if a != \"params_schema\")\n
"},{"location":"api/models/#anta.models.AntaTemplate.render","title":"render","text":"
render(**params: str | int | bool) -> AntaCommand\n

Render an AntaCommand from an AntaTemplate instance.

Keep the parameters used in the AntaTemplate instance.

Returns:

Type Description The rendered AntaCommand.

This AntaCommand instance have a template attribute that references this AntaTemplate instance.

Raises:

Type Description AntaTemplateRenderError

If a parameter is missing to render the AntaTemplate instance.

Source code in anta/models.py
def render(self, **params: str | int | bool) -> AntaCommand:\n    \"\"\"Render an AntaCommand from an AntaTemplate instance.\n\n    Keep the parameters used in the AntaTemplate instance.\n\n    Parameters\n    ----------\n        params: dictionary of variables with string values to render the Python f-string\n\n    Returns\n    -------\n        The rendered AntaCommand.\n        This AntaCommand instance have a template attribute that references this\n        AntaTemplate instance.\n\n    Raises\n    ------\n        AntaTemplateRenderError\n            If a parameter is missing to render the AntaTemplate instance.\n    \"\"\"\n    try:\n        command = self.template.format(**params)\n    except (KeyError, SyntaxError) as e:\n        raise AntaTemplateRenderError(self, e.args[0]) from e\n    return AntaCommand(\n        command=command,\n        ofmt=self.ofmt,\n        version=self.version,\n        revision=self.revision,\n        template=self,\n        params=self.params_schema(**params),\n        use_cache=self.use_cache,\n    )\n
"},{"location":"api/report_manager/","title":"Report Manager","text":""},{"location":"api/report_manager/#anta.reporter.ReportTable","title":"ReportTable","text":"

TableReport Generate a Table based on TestResult.

"},{"location":"api/report_manager/#anta.reporter.ReportTable.report_all","title":"report_all","text":"
report_all(manager: ResultManager, title: str = 'All tests results') -> Table\n

Create a table report with all tests for one or all devices.

Create table with full output: Host / Test / Status / Message

Returns:

Type Description A fully populated rich `Table` Source code in anta/reporter/__init__.py
def report_all(self, manager: ResultManager, title: str = \"All tests results\") -> Table:\n    \"\"\"Create a table report with all tests for one or all devices.\n\n    Create table with full output: Host / Test / Status / Message\n\n    Parameters\n    ----------\n        manager: A ResultManager instance.\n        title: Title for the report. Defaults to 'All tests results'.\n\n    Returns\n    -------\n        A fully populated rich `Table`\n\n    \"\"\"\n    table = Table(title=title, show_lines=True)\n    headers = [\"Device\", \"Test Name\", \"Test Status\", \"Message(s)\", \"Test description\", \"Test category\"]\n    table = self._build_headers(headers=headers, table=table)\n\n    def add_line(result: TestResult) -> None:\n        state = self._color_result(result.result)\n        message = self._split_list_to_txt_list(result.messages) if len(result.messages) > 0 else \"\"\n        categories = \", \".join(result.categories)\n        table.add_row(str(result.name), result.test, state, message, result.description, categories)\n\n    for result in manager.results:\n        add_line(result)\n    return table\n
"},{"location":"api/report_manager/#anta.reporter.ReportTable.report_summary_devices","title":"report_summary_devices","text":"
report_summary_devices(manager: ResultManager, devices: list[str] | None = None, title: str = 'Summary per device') -> Table\n

Create a table report with result aggregated per device.

Create table with full output: Host | Number of success | Number of failure | Number of error | List of nodes in error or failure

Returns:

Type Description A fully populated rich `Table`. Source code in anta/reporter/__init__.py
def report_summary_devices(\n    self,\n    manager: ResultManager,\n    devices: list[str] | None = None,\n    title: str = \"Summary per device\",\n) -> Table:\n    \"\"\"Create a table report with result aggregated per device.\n\n    Create table with full output: Host | Number of success | Number of failure | Number of error | List of nodes in error or failure\n\n    Parameters\n    ----------\n        manager: A ResultManager instance.\n        devices: List of device names to include. None to select all devices.\n        title: Title of the report.\n\n    Returns\n    -------\n        A fully populated rich `Table`.\n    \"\"\"\n    table = Table(title=title, show_lines=True)\n    headers = [\n        \"Device\",\n        \"# of success\",\n        \"# of skipped\",\n        \"# of failure\",\n        \"# of errors\",\n        \"List of failed or error test cases\",\n    ]\n    table = self._build_headers(headers=headers, table=table)\n    for device in manager.get_devices():\n        if devices is None or device in devices:\n            results = manager.filter_by_devices({device}).results\n            nb_failure = len([result for result in results if result.result == \"failure\"])\n            nb_error = len([result for result in results if result.result == \"error\"])\n            list_failure = [result.test for result in results if result.result in [\"failure\", \"error\"]]\n            nb_success = len([result for result in results if result.result == \"success\"])\n            nb_skipped = len([result for result in results if result.result == \"skipped\"])\n            table.add_row(\n                device,\n                str(nb_success),\n                str(nb_skipped),\n                str(nb_failure),\n                str(nb_error),\n                str(list_failure),\n            )\n    return table\n
"},{"location":"api/report_manager/#anta.reporter.ReportTable.report_summary_tests","title":"report_summary_tests","text":"
report_summary_tests(manager: ResultManager, tests: list[str] | None = None, title: str = 'Summary per test') -> Table\n

Create a table report with result aggregated per test.

Create table with full output: Test | Number of success | Number of failure | Number of error | List of nodes in error or failure

Returns:

Type Description A fully populated rich `Table`. Source code in anta/reporter/__init__.py
def report_summary_tests(\n    self,\n    manager: ResultManager,\n    tests: list[str] | None = None,\n    title: str = \"Summary per test\",\n) -> Table:\n    \"\"\"Create a table report with result aggregated per test.\n\n    Create table with full output: Test | Number of success | Number of failure | Number of error | List of nodes in error or failure\n\n    Parameters\n    ----------\n        manager: A ResultManager instance.\n        tests: List of test names to include. None to select all tests.\n        title: Title of the report.\n\n    Returns\n    -------\n        A fully populated rich `Table`.\n    \"\"\"\n    table = Table(title=title, show_lines=True)\n    headers = [\n        \"Test Case\",\n        \"# of success\",\n        \"# of skipped\",\n        \"# of failure\",\n        \"# of errors\",\n        \"List of failed or error nodes\",\n    ]\n    table = self._build_headers(headers=headers, table=table)\n    for test in manager.get_tests():\n        if tests is None or test in tests:\n            results = manager.filter_by_tests({test}).results\n            nb_failure = len([result for result in results if result.result == \"failure\"])\n            nb_error = len([result for result in results if result.result == \"error\"])\n            list_failure = [result.name for result in results if result.result in [\"failure\", \"error\"]]\n            nb_success = len([result for result in results if result.result == \"success\"])\n            nb_skipped = len([result for result in results if result.result == \"skipped\"])\n            table.add_row(\n                test,\n                str(nb_success),\n                str(nb_skipped),\n                str(nb_failure),\n                str(nb_error),\n                str(list_failure),\n            )\n    return table\n
"},{"location":"api/result_manager/","title":"Result Manager module","text":""},{"location":"api/result_manager/#result-manager-definition","title":"Result Manager definition","text":""},{"location":"api/result_manager/#uml-diagram","title":"UML Diagram","text":""},{"location":"api/result_manager/#anta.result_manager.ResultManager","title":"ResultManager","text":"
ResultManager()\n

Helper to manage Test Results and generate reports.

Examples
Create Inventory:\n\n    inventory_anta = AntaInventory.parse(\n        filename='examples/inventory.yml',\n        username='ansible',\n        password='ansible',\n    )\n\nCreate Result Manager:\n\n    manager = ResultManager()\n\nRun tests for all connected devices:\n\n    for device in inventory_anta.get_inventory().devices:\n        manager.add(\n            VerifyNTP(device=device).test()\n        )\n        manager.add(\n            VerifyEOSVersion(device=device).test(version='4.28.3M')\n        )\n\nPrint result in native format:\n\n    manager.results\n    [\n        TestResult(\n            name=\"pf1\",\n            test=\"VerifyZeroTouch\",\n            categories=[\"configuration\"],\n            description=\"Verifies ZeroTouch is disabled\",\n            result=\"success\",\n            messages=[],\n            custom_field=None,\n        ),\n        TestResult(\n            name=\"pf1\",\n            test='VerifyNTP',\n            categories=[\"software\"],\n            categories=['system'],\n            description='Verifies if NTP is synchronised.',\n            result='failure',\n            messages=[\"The device is not synchronized with the configured NTP server(s): 'NTP is disabled.'\"],\n            custom_field=None,\n        ),\n    ]\n

The status of the class is initialized to \u201cunset\u201d

Then when adding a test with a status that is NOT \u2018error\u2019 the following table shows the updated status:

Current Status Added test Status Updated Status unset Any Any skipped unset, skipped skipped skipped success success skipped failure failure success unset, skipped, success success success failure failure failure unset, skipped success, failure failure

If the status of the added test is error, the status is untouched and the error_status is set to True.

Source code in anta/result_manager/__init__.py
def __init__(self) -> None:\n    \"\"\"Class constructor.\n\n    The status of the class is initialized to \"unset\"\n\n    Then when adding a test with a status that is NOT 'error' the following\n    table shows the updated status:\n\n    | Current Status |         Added test Status       | Updated Status |\n    | -------------- | ------------------------------- | -------------- |\n    |      unset     |              Any                |       Any      |\n    |     skipped    |         unset, skipped          |     skipped    |\n    |     skipped    |            success              |     success    |\n    |     skipped    |            failure              |     failure    |\n    |     success    |     unset, skipped, success     |     success    |\n    |     success    |            failure              |     failure    |\n    |     failure    | unset, skipped success, failure |     failure    |\n\n    If the status of the added test is error, the status is untouched and the\n    error_status is set to True.\n    \"\"\"\n    self._result_entries: list[TestResult] = []\n    self.status: TestStatus = \"unset\"\n    self.error_status = False\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.json","title":"json property","text":"
json: str\n

Get a JSON representation of the results.

"},{"location":"api/result_manager/#anta.result_manager.ResultManager.results","title":"results property writable","text":"
results: list[TestResult]\n

Get the list of TestResult.

"},{"location":"api/result_manager/#anta.result_manager.ResultManager.add","title":"add","text":"
add(result: TestResult) -> None\n

Add a result to the ResultManager instance.

Source code in anta/result_manager/__init__.py
def add(self, result: TestResult) -> None:\n    \"\"\"Add a result to the ResultManager instance.\n\n    Parameters\n    ----------\n        result: TestResult to add to the ResultManager instance.\n    \"\"\"\n\n    def _update_status(test_status: TestStatus) -> None:\n        result_validator: TypeAdapter[TestStatus] = TypeAdapter(TestStatus)\n        result_validator.validate_python(test_status)\n        if test_status == \"error\":\n            self.error_status = True\n            return\n        if self.status == \"unset\" or self.status == \"skipped\" and test_status in {\"success\", \"failure\"}:\n            self.status = test_status\n        elif self.status == \"success\" and test_status == \"failure\":\n            self.status = \"failure\"\n\n    self._result_entries.append(result)\n    _update_status(result.result)\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.filter","title":"filter","text":"
filter(hide: set[TestStatus]) -> ResultManager\n

Get a filtered ResultManager based on test status.

Returns:

Type Description A filtered `ResultManager`. Source code in anta/result_manager/__init__.py
def filter(self, hide: set[TestStatus]) -> ResultManager:\n    \"\"\"Get a filtered ResultManager based on test status.\n\n    Parameters\n    ----------\n        hide: set of TestStatus literals to select tests to hide based on their status.\n\n    Returns\n    -------\n        A filtered `ResultManager`.\n    \"\"\"\n    manager = ResultManager()\n    manager.results = [test for test in self._result_entries if test.result not in hide]\n    return manager\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.filter_by_devices","title":"filter_by_devices","text":"
filter_by_devices(devices: set[str]) -> ResultManager\n

Get a filtered ResultManager that only contains specific devices.

Returns:

Type Description A filtered `ResultManager`. Source code in anta/result_manager/__init__.py
def filter_by_devices(self, devices: set[str]) -> ResultManager:\n    \"\"\"Get a filtered ResultManager that only contains specific devices.\n\n    Parameters\n    ----------\n        devices: Set of device names to filter the results.\n\n    Returns\n    -------\n        A filtered `ResultManager`.\n    \"\"\"\n    manager = ResultManager()\n    manager.results = [result for result in self._result_entries if result.name in devices]\n    return manager\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.filter_by_tests","title":"filter_by_tests","text":"
filter_by_tests(tests: set[str]) -> ResultManager\n

Get a filtered ResultManager that only contains specific tests.

Returns:

Type Description A filtered `ResultManager`. Source code in anta/result_manager/__init__.py
def filter_by_tests(self, tests: set[str]) -> ResultManager:\n    \"\"\"Get a filtered ResultManager that only contains specific tests.\n\n    Parameters\n    ----------\n        tests: Set of test names to filter the results.\n\n    Returns\n    -------\n        A filtered `ResultManager`.\n    \"\"\"\n    manager = ResultManager()\n    manager.results = [result for result in self._result_entries if result.test in tests]\n    return manager\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.get_devices","title":"get_devices","text":"
get_devices() -> set[str]\n

Get the set of all the device names.

Returns:

Type Description Set of device names. Source code in anta/result_manager/__init__.py
def get_devices(self) -> set[str]:\n    \"\"\"Get the set of all the device names.\n\n    Returns\n    -------\n        Set of device names.\n    \"\"\"\n    return {str(result.name) for result in self._result_entries}\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.get_status","title":"get_status","text":"
get_status(*, ignore_error: bool = False) -> str\n

Return the current status including error_status if ignore_error is False.

Source code in anta/result_manager/__init__.py
def get_status(self, *, ignore_error: bool = False) -> str:\n    \"\"\"Return the current status including error_status if ignore_error is False.\"\"\"\n    return \"error\" if self.error_status and not ignore_error else self.status\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.get_tests","title":"get_tests","text":"
get_tests() -> set[str]\n

Get the set of all the test names.

Returns:

Type Description Set of test names. Source code in anta/result_manager/__init__.py
def get_tests(self) -> set[str]:\n    \"\"\"Get the set of all the test names.\n\n    Returns\n    -------\n        Set of test names.\n    \"\"\"\n    return {str(result.test) for result in self._result_entries}\n
"},{"location":"api/result_manager_models/","title":"Result Manager models","text":""},{"location":"api/result_manager_models/#test-result-model","title":"Test Result model","text":""},{"location":"api/result_manager_models/#uml-diagram","title":"UML Diagram","text":""},{"location":"api/result_manager_models/#anta.result_manager.models.TestResult","title":"TestResult","text":"

Bases: BaseModel

Describe the result of a test from a single device.

Attributes:

Name Type Description name Device name where the test has run.

test: Test name runs on the device. categories: List of categories the TestResult belongs to, by default the AntaTest categories. description: TestResult description, by default the AntaTest description. result: Result of the test. Can be one of \u201cunset\u201d, \u201csuccess\u201d, \u201cfailure\u201d, \u201cerror\u201d or \u201cskipped\u201d. messages: Message to report after the test if any. custom_field: Custom field to store a string for flexibility in integrating with ANTA

"},{"location":"api/result_manager_models/#anta.result_manager.models.TestResult.is_error","title":"is_error","text":"
is_error(message: str | None = None) -> None\n

Set status to error.

Source code in anta/result_manager/models.py
def is_error(self, message: str | None = None) -> None:\n    \"\"\"Set status to error.\n\n    Parameters\n    ----------\n        message: Optional message related to the test\n\n    \"\"\"\n    self._set_status(\"error\", message)\n
"},{"location":"api/result_manager_models/#anta.result_manager.models.TestResult.is_failure","title":"is_failure","text":"
is_failure(message: str | None = None) -> None\n

Set status to failure.

Source code in anta/result_manager/models.py
def is_failure(self, message: str | None = None) -> None:\n    \"\"\"Set status to failure.\n\n    Parameters\n    ----------\n        message: Optional message related to the test\n\n    \"\"\"\n    self._set_status(\"failure\", message)\n
"},{"location":"api/result_manager_models/#anta.result_manager.models.TestResult.is_skipped","title":"is_skipped","text":"
is_skipped(message: str | None = None) -> None\n

Set status to skipped.

Source code in anta/result_manager/models.py
def is_skipped(self, message: str | None = None) -> None:\n    \"\"\"Set status to skipped.\n\n    Parameters\n    ----------\n        message: Optional message related to the test\n\n    \"\"\"\n    self._set_status(\"skipped\", message)\n
"},{"location":"api/result_manager_models/#anta.result_manager.models.TestResult.is_success","title":"is_success","text":"
is_success(message: str | None = None) -> None\n

Set status to success.

Source code in anta/result_manager/models.py
def is_success(self, message: str | None = None) -> None:\n    \"\"\"Set status to success.\n\n    Parameters\n    ----------\n        message: Optional message related to the test\n\n    \"\"\"\n    self._set_status(\"success\", message)\n
"},{"location":"api/runner/","title":"Runner","text":""},{"location":"api/runner/#anta.runner","title":"runner","text":"

ANTA runner function.

"},{"location":"api/runner/#anta.runner.adjust_rlimit_nofile","title":"adjust_rlimit_nofile","text":"
adjust_rlimit_nofile() -> tuple[int, int]\n

Adjust the maximum number of open file descriptors for the ANTA process.

The limit is set to the lower of the current hard limit and the value of the ANTA_NOFILE environment variable.

If the ANTA_NOFILE environment variable is not set or is invalid, DEFAULT_NOFILE is used.

Returns:

Type Description tuple[int, int]: The new soft and hard limits for open file descriptors. Source code in anta/runner.py
def adjust_rlimit_nofile() -> tuple[int, int]:\n    \"\"\"Adjust the maximum number of open file descriptors for the ANTA process.\n\n    The limit is set to the lower of the current hard limit and the value of the ANTA_NOFILE environment variable.\n\n    If the `ANTA_NOFILE` environment variable is not set or is invalid, `DEFAULT_NOFILE` is used.\n\n    Returns\n    -------\n        tuple[int, int]: The new soft and hard limits for open file descriptors.\n    \"\"\"\n    try:\n        nofile = int(os.environ.get(\"ANTA_NOFILE\", DEFAULT_NOFILE))\n    except ValueError as exception:\n        logger.warning(\"The ANTA_NOFILE environment variable value is invalid: %s\\nDefault to %s.\", exc_to_str(exception), DEFAULT_NOFILE)\n        nofile = DEFAULT_NOFILE\n\n    limits = resource.getrlimit(resource.RLIMIT_NOFILE)\n    logger.debug(\"Initial limit numbers for open file descriptors for the current ANTA process: Soft Limit: %s | Hard Limit: %s\", limits[0], limits[1])\n    nofile = min(limits[1], nofile)\n    logger.debug(\"Setting soft limit for open file descriptors for the current ANTA process to %s\", nofile)\n    resource.setrlimit(resource.RLIMIT_NOFILE, (nofile, limits[1]))\n    return resource.getrlimit(resource.RLIMIT_NOFILE)\n
"},{"location":"api/runner/#anta.runner.get_coroutines","title":"get_coroutines","text":"
get_coroutines(selected_tests: defaultdict[AntaDevice, set[AntaTestDefinition]]) -> list[Coroutine[Any, Any, TestResult]]\n

Get the coroutines for the ANTA run.

Returns:

Type Description The list of coroutines to run. Source code in anta/runner.py
def get_coroutines(selected_tests: defaultdict[AntaDevice, set[AntaTestDefinition]]) -> list[Coroutine[Any, Any, TestResult]]:\n    \"\"\"Get the coroutines for the ANTA run.\n\n    Parameters\n    ----------\n        selected_tests: A mapping of devices to the tests to run. The selected tests are generated by the `prepare_tests` function.\n\n    Returns\n    -------\n        The list of coroutines to run.\n    \"\"\"\n    coros = []\n    for device, test_definitions in selected_tests.items():\n        for test in test_definitions:\n            try:\n                test_instance = test.test(device=device, inputs=test.inputs)\n                coros.append(test_instance.test())\n            except Exception as e:  # noqa: PERF203, pylint: disable=broad-exception-caught\n                # An AntaTest instance is potentially user-defined code.\n                # We need to catch everything and exit gracefully with an error message.\n                message = \"\\n\".join(\n                    [\n                        f\"There is an error when creating test {test.test.module}.{test.test.__name__}.\",\n                        f\"If this is not a custom test implementation: {GITHUB_SUGGESTION}\",\n                    ],\n                )\n                anta_log_exception(e, message, logger)\n    return coros\n
"},{"location":"api/runner/#anta.runner.log_cache_statistics","title":"log_cache_statistics","text":"
log_cache_statistics(devices: list[AntaDevice]) -> None\n

Log cache statistics for each device in the inventory.

Source code in anta/runner.py
def log_cache_statistics(devices: list[AntaDevice]) -> None:\n    \"\"\"Log cache statistics for each device in the inventory.\n\n    Parameters\n    ----------\n        devices: List of devices in the inventory.\n    \"\"\"\n    for device in devices:\n        if device.cache_statistics is not None:\n            msg = (\n                f\"Cache statistics for '{device.name}': \"\n                f\"{device.cache_statistics['cache_hits']} hits / {device.cache_statistics['total_commands_sent']} \"\n                f\"command(s) ({device.cache_statistics['cache_hit_ratio']})\"\n            )\n            logger.info(msg)\n        else:\n            logger.info(\"Caching is not enabled on %s\", device.name)\n
"},{"location":"api/runner/#anta.runner.main","title":"main async","text":"
main(manager: ResultManager, inventory: AntaInventory, catalog: AntaCatalog, devices: set[str] | None = None, tests: set[str] | None = None, tags: set[str] | None = None, *, established_only: bool = True, dry_run: bool = False) -> None\n

Run ANTA.

Use this as an entrypoint to the test framework in your script. ResultManager object gets updated with the test results.

Source code in anta/runner.py
@cprofile()\nasync def main(  # noqa: PLR0913\n    manager: ResultManager,\n    inventory: AntaInventory,\n    catalog: AntaCatalog,\n    devices: set[str] | None = None,\n    tests: set[str] | None = None,\n    tags: set[str] | None = None,\n    *,\n    established_only: bool = True,\n    dry_run: bool = False,\n) -> None:\n    # pylint: disable=too-many-arguments\n    \"\"\"Run ANTA.\n\n    Use this as an entrypoint to the test framework in your script.\n    ResultManager object gets updated with the test results.\n\n    Parameters\n    ----------\n        manager: ResultManager object to populate with the test results.\n        inventory: AntaInventory object that includes the device(s).\n        catalog: AntaCatalog object that includes the list of tests.\n        devices: Devices on which to run tests. None means all devices. These may come from the `--device / -d` CLI option in NRFU.\n        tests: Tests to run against devices. None means all tests. These may come from the `--test / -t` CLI option in NRFU.\n        tags: Tags to filter devices from the inventory. These may come from the `--tags` CLI option in NRFU.\n        established_only: Include only established device(s).\n        dry_run: Build the list of coroutine to run and stop before test execution.\n    \"\"\"\n    # Adjust the maximum number of open file descriptors for the ANTA process\n    limits = adjust_rlimit_nofile()\n\n    if not catalog.tests:\n        logger.info(\"The list of tests is empty, exiting\")\n        return\n\n    with Catchtime(logger=logger, message=\"Preparing ANTA NRFU Run\"):\n        # Setup the inventory\n        selected_inventory = inventory if dry_run else await setup_inventory(inventory, tags, devices, established_only=established_only)\n        if selected_inventory is None:\n            return\n\n        with Catchtime(logger=logger, message=\"Preparing the tests\"):\n            selected_tests = prepare_tests(selected_inventory, catalog, tests, tags)\n            if selected_tests is None:\n                return\n\n        run_info = (\n            \"--- ANTA NRFU Run Information ---\\n\"\n            f\"Number of devices: {len(inventory)} ({len(selected_inventory)} established)\\n\"\n            f\"Total number of selected tests: {catalog.final_tests_count}\\n\"\n            f\"Maximum number of open file descriptors for the current ANTA process: {limits[0]}\\n\"\n            \"---------------------------------\"\n        )\n\n        logger.info(run_info)\n\n        if catalog.final_tests_count > limits[0]:\n            logger.warning(\n                \"The number of concurrent tests is higher than the open file descriptors limit for this ANTA process.\\n\"\n                \"Errors may occur while running the tests.\\n\"\n                \"Please consult the ANTA FAQ.\"\n            )\n\n        coroutines = get_coroutines(selected_tests)\n\n    if dry_run:\n        logger.info(\"Dry-run mode, exiting before running the tests.\")\n        for coro in coroutines:\n            coro.close()\n        return\n\n    if AntaTest.progress is not None:\n        AntaTest.nrfu_task = AntaTest.progress.add_task(\"Running NRFU Tests...\", total=len(coroutines))\n\n    with Catchtime(logger=logger, message=\"Running ANTA tests\"):\n        test_results = await asyncio.gather(*coroutines)\n        for r in test_results:\n            manager.add(r)\n\n    log_cache_statistics(selected_inventory.devices)\n
"},{"location":"api/runner/#anta.runner.prepare_tests","title":"prepare_tests","text":"
prepare_tests(inventory: AntaInventory, catalog: AntaCatalog, tests: set[str] | None, tags: set[str] | None) -> defaultdict[AntaDevice, set[AntaTestDefinition]] | None\n

Prepare the tests to run.

Returns:

Type Description A mapping of devices to the tests to run or None if there are no tests to run. Source code in anta/runner.py
def prepare_tests(\n    inventory: AntaInventory, catalog: AntaCatalog, tests: set[str] | None, tags: set[str] | None\n) -> defaultdict[AntaDevice, set[AntaTestDefinition]] | None:\n    \"\"\"Prepare the tests to run.\n\n    Parameters\n    ----------\n        inventory: AntaInventory object that includes the device(s).\n        catalog: AntaCatalog object that includes the list of tests.\n        tests: Tests to run against devices. None means all tests.\n        tags: Tags to filter devices from the inventory.\n\n    Returns\n    -------\n        A mapping of devices to the tests to run or None if there are no tests to run.\n    \"\"\"\n    # Build indexes for the catalog. If `tests` is set, filter the indexes based on these tests\n    catalog.build_indexes(filtered_tests=tests)\n\n    # Using a set to avoid inserting duplicate tests\n    device_to_tests: defaultdict[AntaDevice, set[AntaTestDefinition]] = defaultdict(set)\n\n    # Create AntaTestRunner tuples from the tags\n    for device in inventory.devices:\n        if tags:\n            # If there are CLI tags, only execute tests with matching tags\n            device_to_tests[device].update(catalog.get_tests_by_tags(tags))\n        else:\n            # If there is no CLI tags, execute all tests that do not have any tags\n            device_to_tests[device].update(catalog.tag_to_tests[None])\n\n            # Then add the tests with matching tags from device tags\n            device_to_tests[device].update(catalog.get_tests_by_tags(device.tags))\n\n        catalog.final_tests_count += len(device_to_tests[device])\n\n    if catalog.final_tests_count == 0:\n        msg = (\n            f\"There are no tests{f' matching the tags {tags} ' if tags else ' '}to run in the current test catalog and device inventory, please verify your inputs.\"\n        )\n        logger.warning(msg)\n        return None\n\n    return device_to_tests\n
"},{"location":"api/runner/#anta.runner.setup_inventory","title":"setup_inventory async","text":"
setup_inventory(inventory: AntaInventory, tags: set[str] | None, devices: set[str] | None, *, established_only: bool) -> AntaInventory | None\n

Set up the inventory for the ANTA run.

Returns:

Type Description AntaInventory | None: The filtered inventory or None if there are no devices to run tests on. Source code in anta/runner.py
async def setup_inventory(inventory: AntaInventory, tags: set[str] | None, devices: set[str] | None, *, established_only: bool) -> AntaInventory | None:\n    \"\"\"Set up the inventory for the ANTA run.\n\n    Parameters\n    ----------\n        inventory: AntaInventory object that includes the device(s).\n        tags: Tags to filter devices from the inventory.\n        devices: Devices on which to run tests. None means all devices.\n\n    Returns\n    -------\n        AntaInventory | None: The filtered inventory or None if there are no devices to run tests on.\n    \"\"\"\n    if len(inventory) == 0:\n        logger.info(\"The inventory is empty, exiting\")\n        return None\n\n    # Filter the inventory based on the CLI provided tags and devices if any\n    selected_inventory = inventory.get_inventory(tags=tags, devices=devices) if tags or devices else inventory\n\n    with Catchtime(logger=logger, message=\"Connecting to devices\"):\n        # Connect to the devices\n        await selected_inventory.connect_inventory()\n\n    # Remove devices that are unreachable\n    selected_inventory = selected_inventory.get_inventory(established_only=established_only)\n\n    # If there are no devices in the inventory after filtering, exit\n    if not selected_inventory.devices:\n        msg = f'No reachable device {f\"matching the tags {tags} \" if tags else \"\"}was found.{f\" Selected devices: {devices} \" if devices is not None else \"\"}'\n        logger.warning(msg)\n        return None\n\n    return selected_inventory\n
"},{"location":"api/tests.aaa/","title":"AAA","text":""},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAcctConsoleMethods","title":"VerifyAcctConsoleMethods","text":"

Verifies the AAA accounting console method lists for different accounting types (system, exec, commands, dot1x).

Expected Results
  • Success: The test will pass if the provided AAA accounting console method list is matching in the configured accounting types.
  • Failure: The test will fail if the provided AAA accounting console method list is NOT matching in the configured accounting types.
Examples
anta.tests.aaa:\n  - VerifyAcctConsoleMethods:\n      methods:\n        - local\n        - none\n        - logging\n      types:\n        - system\n        - exec\n        - commands\n        - dot1x\n
Source code in anta/tests/aaa.py
class VerifyAcctConsoleMethods(AntaTest):\n    \"\"\"Verifies the AAA accounting console method lists for different accounting types (system, exec, commands, dot1x).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided AAA accounting console method list is matching in the configured accounting types.\n    * Failure: The test will fail if the provided AAA accounting console method list is NOT matching in the configured accounting types.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyAcctConsoleMethods:\n          methods:\n            - local\n            - none\n            - logging\n          types:\n            - system\n            - exec\n            - commands\n            - dot1x\n    ```\n    \"\"\"\n\n    name = \"VerifyAcctConsoleMethods\"\n    description = \"Verifies the AAA accounting console method lists for different accounting types (system, exec, commands, dot1x).\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show aaa methods accounting\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAcctConsoleMethods test.\"\"\"\n\n        methods: list[AAAAuthMethod]\n        \"\"\"List of AAA accounting console methods. Methods should be in the right order.\"\"\"\n        types: set[Literal[\"commands\", \"exec\", \"system\", \"dot1x\"]]\n        \"\"\"List of accounting console types to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAcctConsoleMethods.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        not_matching = []\n        not_configured = []\n        for k, v in command_output.items():\n            acct_type = k.replace(\"AcctMethods\", \"\")\n            if acct_type not in self.inputs.types:\n                # We do not need to verify this accounting type\n                continue\n            for methods in v.values():\n                if \"consoleAction\" not in methods:\n                    not_configured.append(acct_type)\n                if methods[\"consoleMethods\"] != self.inputs.methods:\n                    not_matching.append(acct_type)\n        if not_configured:\n            self.result.is_failure(f\"AAA console accounting is not configured for {not_configured}\")\n            return\n        if not not_matching:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"AAA accounting console methods {self.inputs.methods} are not matching for {not_matching}\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAcctConsoleMethods-attributes","title":"Inputs","text":"Name Type Description Default methods list[AAAAuthMethod] List of AAA accounting console methods. Methods should be in the right order. - types set[Literal['commands', 'exec', 'system', 'dot1x']] List of accounting console types to verify. -"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAcctDefaultMethods","title":"VerifyAcctDefaultMethods","text":"

Verifies the AAA accounting default method lists for different accounting types (system, exec, commands, dot1x).

Expected Results
  • Success: The test will pass if the provided AAA accounting default method list is matching in the configured accounting types.
  • Failure: The test will fail if the provided AAA accounting default method list is NOT matching in the configured accounting types.
Examples
anta.tests.aaa:\n  - VerifyAcctDefaultMethods:\n      methods:\n        - local\n        - none\n        - logging\n      types:\n        - system\n        - exec\n        - commands\n        - dot1x\n
Source code in anta/tests/aaa.py
class VerifyAcctDefaultMethods(AntaTest):\n    \"\"\"Verifies the AAA accounting default method lists for different accounting types (system, exec, commands, dot1x).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided AAA accounting default method list is matching in the configured accounting types.\n    * Failure: The test will fail if the provided AAA accounting default method list is NOT matching in the configured accounting types.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyAcctDefaultMethods:\n          methods:\n            - local\n            - none\n            - logging\n          types:\n            - system\n            - exec\n            - commands\n            - dot1x\n    ```\n    \"\"\"\n\n    name = \"VerifyAcctDefaultMethods\"\n    description = \"Verifies the AAA accounting default method lists for different accounting types (system, exec, commands, dot1x).\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show aaa methods accounting\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAcctDefaultMethods test.\"\"\"\n\n        methods: list[AAAAuthMethod]\n        \"\"\"List of AAA accounting methods. Methods should be in the right order.\"\"\"\n        types: set[Literal[\"commands\", \"exec\", \"system\", \"dot1x\"]]\n        \"\"\"List of accounting types to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAcctDefaultMethods.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        not_matching = []\n        not_configured = []\n        for k, v in command_output.items():\n            acct_type = k.replace(\"AcctMethods\", \"\")\n            if acct_type not in self.inputs.types:\n                # We do not need to verify this accounting type\n                continue\n            for methods in v.values():\n                if \"defaultAction\" not in methods:\n                    not_configured.append(acct_type)\n                if methods[\"defaultMethods\"] != self.inputs.methods:\n                    not_matching.append(acct_type)\n        if not_configured:\n            self.result.is_failure(f\"AAA default accounting is not configured for {not_configured}\")\n            return\n        if not not_matching:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"AAA accounting default methods {self.inputs.methods} are not matching for {not_matching}\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAcctDefaultMethods-attributes","title":"Inputs","text":"Name Type Description Default methods list[AAAAuthMethod] List of AAA accounting methods. Methods should be in the right order. - types set[Literal['commands', 'exec', 'system', 'dot1x']] List of accounting types to verify. -"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAuthenMethods","title":"VerifyAuthenMethods","text":"

Verifies the AAA authentication method lists for different authentication types (login, enable, dot1x).

Expected Results
  • Success: The test will pass if the provided AAA authentication method list is matching in the configured authentication types.
  • Failure: The test will fail if the provided AAA authentication method list is NOT matching in the configured authentication types.
Examples
anta.tests.aaa:\n  - VerifyAuthenMethods:\n    methods:\n      - local\n      - none\n      - logging\n    types:\n      - login\n      - enable\n      - dot1x\n
Source code in anta/tests/aaa.py
class VerifyAuthenMethods(AntaTest):\n    \"\"\"Verifies the AAA authentication method lists for different authentication types (login, enable, dot1x).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided AAA authentication method list is matching in the configured authentication types.\n    * Failure: The test will fail if the provided AAA authentication method list is NOT matching in the configured authentication types.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyAuthenMethods:\n        methods:\n          - local\n          - none\n          - logging\n        types:\n          - login\n          - enable\n          - dot1x\n    ```\n    \"\"\"\n\n    name = \"VerifyAuthenMethods\"\n    description = \"Verifies the AAA authentication method lists for different authentication types (login, enable, dot1x).\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show aaa methods authentication\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAuthenMethods test.\"\"\"\n\n        methods: list[AAAAuthMethod]\n        \"\"\"List of AAA authentication methods. Methods should be in the right order.\"\"\"\n        types: set[Literal[\"login\", \"enable\", \"dot1x\"]]\n        \"\"\"List of authentication types to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAuthenMethods.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        not_matching: list[str] = []\n        for k, v in command_output.items():\n            auth_type = k.replace(\"AuthenMethods\", \"\")\n            if auth_type not in self.inputs.types:\n                # We do not need to verify this accounting type\n                continue\n            if auth_type == \"login\":\n                if \"login\" not in v:\n                    self.result.is_failure(\"AAA authentication methods are not configured for login console\")\n                    return\n                if v[\"login\"][\"methods\"] != self.inputs.methods:\n                    self.result.is_failure(f\"AAA authentication methods {self.inputs.methods} are not matching for login console\")\n                    return\n            not_matching.extend(auth_type for methods in v.values() if methods[\"methods\"] != self.inputs.methods)\n\n        if not not_matching:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"AAA authentication methods {self.inputs.methods} are not matching for {not_matching}\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAuthenMethods-attributes","title":"Inputs","text":"Name Type Description Default methods list[AAAAuthMethod] List of AAA authentication methods. Methods should be in the right order. - types set[Literal['login', 'enable', 'dot1x']] List of authentication types to verify. -"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAuthzMethods","title":"VerifyAuthzMethods","text":"

Verifies the AAA authorization method lists for different authorization types (commands, exec).

Expected Results
  • Success: The test will pass if the provided AAA authorization method list is matching in the configured authorization types.
  • Failure: The test will fail if the provided AAA authorization method list is NOT matching in the configured authorization types.
Examples
anta.tests.aaa:\n  - VerifyAuthzMethods:\n      methods:\n        - local\n        - none\n        - logging\n      types:\n        - commands\n        - exec\n
Source code in anta/tests/aaa.py
class VerifyAuthzMethods(AntaTest):\n    \"\"\"Verifies the AAA authorization method lists for different authorization types (commands, exec).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided AAA authorization method list is matching in the configured authorization types.\n    * Failure: The test will fail if the provided AAA authorization method list is NOT matching in the configured authorization types.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyAuthzMethods:\n          methods:\n            - local\n            - none\n            - logging\n          types:\n            - commands\n            - exec\n    ```\n    \"\"\"\n\n    name = \"VerifyAuthzMethods\"\n    description = \"Verifies the AAA authorization method lists for different authorization types (commands, exec).\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show aaa methods authorization\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAuthzMethods test.\"\"\"\n\n        methods: list[AAAAuthMethod]\n        \"\"\"List of AAA authorization methods. Methods should be in the right order.\"\"\"\n        types: set[Literal[\"commands\", \"exec\"]]\n        \"\"\"List of authorization types to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAuthzMethods.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        not_matching: list[str] = []\n        for k, v in command_output.items():\n            authz_type = k.replace(\"AuthzMethods\", \"\")\n            if authz_type not in self.inputs.types:\n                # We do not need to verify this accounting type\n                continue\n            not_matching.extend(authz_type for methods in v.values() if methods[\"methods\"] != self.inputs.methods)\n\n        if not not_matching:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"AAA authorization methods {self.inputs.methods} are not matching for {not_matching}\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAuthzMethods-attributes","title":"Inputs","text":"Name Type Description Default methods list[AAAAuthMethod] List of AAA authorization methods. Methods should be in the right order. - types set[Literal['commands', 'exec']] List of authorization types to verify. -"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyTacacsServerGroups","title":"VerifyTacacsServerGroups","text":"

Verifies if the provided TACACS server group(s) are configured.

Expected Results
  • Success: The test will pass if the provided TACACS server group(s) are configured.
  • Failure: The test will fail if one or all the provided TACACS server group(s) are NOT configured.
Examples
anta.tests.aaa:\n  - VerifyTacacsServerGroups:\n      groups:\n        - TACACS-GROUP1\n        - TACACS-GROUP2\n
Source code in anta/tests/aaa.py
class VerifyTacacsServerGroups(AntaTest):\n    \"\"\"Verifies if the provided TACACS server group(s) are configured.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided TACACS server group(s) are configured.\n    * Failure: The test will fail if one or all the provided TACACS server group(s) are NOT configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyTacacsServerGroups:\n          groups:\n            - TACACS-GROUP1\n            - TACACS-GROUP2\n    ```\n    \"\"\"\n\n    name = \"VerifyTacacsServerGroups\"\n    description = \"Verifies if the provided TACACS server group(s) are configured.\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show tacacs\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyTacacsServerGroups test.\"\"\"\n\n        groups: list[str]\n        \"\"\"List of TACACS server groups.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTacacsServerGroups.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        tacacs_groups = command_output[\"groups\"]\n        if not tacacs_groups:\n            self.result.is_failure(\"No TACACS server group(s) are configured\")\n            return\n        not_configured = [group for group in self.inputs.groups if group not in tacacs_groups]\n        if not not_configured:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"TACACS server group(s) {not_configured} are not configured\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyTacacsServerGroups-attributes","title":"Inputs","text":"Name Type Description Default groups list[str] List of TACACS server groups. -"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyTacacsServers","title":"VerifyTacacsServers","text":"

Verifies TACACS servers are configured for a specified VRF.

Expected Results
  • Success: The test will pass if the provided TACACS servers are configured in the specified VRF.
  • Failure: The test will fail if the provided TACACS servers are NOT configured in the specified VRF.
Examples
anta.tests.aaa:\n  - VerifyTacacsServers:\n      servers:\n        - 10.10.10.21\n        - 10.10.10.22\n      vrf: MGMT\n
Source code in anta/tests/aaa.py
class VerifyTacacsServers(AntaTest):\n    \"\"\"Verifies TACACS servers are configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided TACACS servers are configured in the specified VRF.\n    * Failure: The test will fail if the provided TACACS servers are NOT configured in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyTacacsServers:\n          servers:\n            - 10.10.10.21\n            - 10.10.10.22\n          vrf: MGMT\n    ```\n    \"\"\"\n\n    name = \"VerifyTacacsServers\"\n    description = \"Verifies TACACS servers are configured for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show tacacs\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyTacacsServers test.\"\"\"\n\n        servers: list[IPv4Address]\n        \"\"\"List of TACACS servers.\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF to transport TACACS messages. Defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTacacsServers.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        tacacs_servers = command_output[\"tacacsServers\"]\n        if not tacacs_servers:\n            self.result.is_failure(\"No TACACS servers are configured\")\n            return\n        not_configured = [\n            str(server)\n            for server in self.inputs.servers\n            if not any(\n                str(server) == tacacs_server[\"serverInfo\"][\"hostname\"] and self.inputs.vrf == tacacs_server[\"serverInfo\"][\"vrf\"] for tacacs_server in tacacs_servers\n            )\n        ]\n        if not not_configured:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"TACACS servers {not_configured} are not configured in VRF {self.inputs.vrf}\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyTacacsServers-attributes","title":"Inputs","text":"Name Type Description Default servers list[IPv4Address] List of TACACS servers. - vrf str The name of the VRF to transport TACACS messages. Defaults to `default`. 'default'"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyTacacsSourceIntf","title":"VerifyTacacsSourceIntf","text":"

Verifies TACACS source-interface for a specified VRF.

Expected Results
  • Success: The test will pass if the provided TACACS source-interface is configured in the specified VRF.
  • Failure: The test will fail if the provided TACACS source-interface is NOT configured in the specified VRF.
Examples
anta.tests.aaa:\n  - VerifyTacacsSourceIntf:\n      intf: Management0\n      vrf: MGMT\n
Source code in anta/tests/aaa.py
class VerifyTacacsSourceIntf(AntaTest):\n    \"\"\"Verifies TACACS source-interface for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided TACACS source-interface is configured in the specified VRF.\n    * Failure: The test will fail if the provided TACACS source-interface is NOT configured in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyTacacsSourceIntf:\n          intf: Management0\n          vrf: MGMT\n    ```\n    \"\"\"\n\n    name = \"VerifyTacacsSourceIntf\"\n    description = \"Verifies TACACS source-interface for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show tacacs\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyTacacsSourceIntf test.\"\"\"\n\n        intf: str\n        \"\"\"Source-interface to use as source IP of TACACS messages.\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF to transport TACACS messages. Defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTacacsSourceIntf.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        try:\n            if command_output[\"srcIntf\"][self.inputs.vrf] == self.inputs.intf:\n                self.result.is_success()\n            else:\n                self.result.is_failure(f\"Wrong source-interface configured in VRF {self.inputs.vrf}\")\n        except KeyError:\n            self.result.is_failure(f\"Source-interface {self.inputs.intf} is not configured in VRF {self.inputs.vrf}\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyTacacsSourceIntf-attributes","title":"Inputs","text":"Name Type Description Default intf str Source-interface to use as source IP of TACACS messages. - vrf str The name of the VRF to transport TACACS messages. Defaults to `default`. 'default'"},{"location":"api/tests.avt/","title":"Adaptive Virtual Topology","text":""},{"location":"api/tests.avt/#anta.tests.avt.VerifyAVTPathHealth","title":"VerifyAVTPathHealth","text":"

Verifies the status of all Adaptive Virtual Topology (AVT) paths for all VRFs.

Expected Results
  • Success: The test will pass if all AVT paths for all VRFs are active and valid.
  • Failure: The test will fail if the AVT path is not configured or if any AVT path under any VRF is either inactive or invalid.
Examples
anta.tests.avt:\n  - VerifyAVTPathHealth:\n
Source code in anta/tests/avt.py
class VerifyAVTPathHealth(AntaTest):\n    \"\"\"\n    Verifies the status of all Adaptive Virtual Topology (AVT) paths for all VRFs.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all AVT paths for all VRFs are active and valid.\n    * Failure: The test will fail if the AVT path is not configured or if any AVT path under any VRF is either inactive or invalid.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.avt:\n      - VerifyAVTPathHealth:\n    ```\n    \"\"\"\n\n    name = \"VerifyAVTPathHealth\"\n    description = \"Verifies the status of all AVT paths for all VRFs.\"\n    categories: ClassVar[list[str]] = [\"avt\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show adaptive-virtual-topology path\")]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAVTPathHealth.\"\"\"\n        # Initialize the test result as success\n        self.result.is_success()\n\n        # Get the command output\n        command_output = self.instance_commands[0].json_output.get(\"vrfs\", {})\n\n        # Check if AVT is configured\n        if not command_output:\n            self.result.is_failure(\"Adaptive virtual topology paths are not configured.\")\n            return\n\n        # Iterate over each VRF\n        for vrf, vrf_data in command_output.items():\n            # Iterate over each AVT path\n            for profile, avt_path in vrf_data.get(\"avts\", {}).items():\n                for path, flags in avt_path.get(\"avtPaths\", {}).items():\n                    # Get the status of the AVT path\n                    valid = flags[\"flags\"][\"valid\"]\n                    active = flags[\"flags\"][\"active\"]\n\n                    # Check the status of the AVT path\n                    if not valid and not active:\n                        self.result.is_failure(f\"AVT path {path} for profile {profile} in VRF {vrf} is invalid and not active.\")\n                    elif not valid:\n                        self.result.is_failure(f\"AVT path {path} for profile {profile} in VRF {vrf} is invalid.\")\n                    elif not active:\n                        self.result.is_failure(f\"AVT path {path} for profile {profile} in VRF {vrf} is not active.\")\n
"},{"location":"api/tests.avt/#anta.tests.avt.VerifyAVTRole","title":"VerifyAVTRole","text":"

Verifies the Adaptive Virtual Topology (AVT) role of a device.

Expected Results
  • Success: The test will pass if the AVT role of the device matches the expected role.
  • Failure: The test will fail if the AVT is not configured or if the AVT role does not match the expected role.
Examples
anta.tests.avt:\n  - VerifyAVTRole:\n      role: edge\n
Source code in anta/tests/avt.py
class VerifyAVTRole(AntaTest):\n    \"\"\"\n    Verifies the Adaptive Virtual Topology (AVT) role of a device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the AVT role of the device matches the expected role.\n    * Failure: The test will fail if the AVT is not configured or if the AVT role does not match the expected role.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.avt:\n      - VerifyAVTRole:\n          role: edge\n    ```\n    \"\"\"\n\n    name = \"VerifyAVTRole\"\n    description = \"Verifies the AVT role of a device.\"\n    categories: ClassVar[list[str]] = [\"avt\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show adaptive-virtual-topology path\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAVTRole test.\"\"\"\n\n        role: str\n        \"\"\"Expected AVT role of the device.\"\"\"\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAVTRole.\"\"\"\n        # Initialize the test result as success\n        self.result.is_success()\n\n        # Get the command output\n        command_output = self.instance_commands[0].json_output\n\n        # Check if the AVT role matches the expected role\n        if self.inputs.role != command_output.get(\"role\"):\n            self.result.is_failure(f\"Expected AVT role as `{self.inputs.role}`, but found `{command_output.get('role')}` instead.\")\n
"},{"location":"api/tests.avt/#anta.tests.avt.VerifyAVTRole-attributes","title":"Inputs","text":"Name Type Description Default role str Expected AVT role of the device. -"},{"location":"api/tests.avt/#anta.tests.avt.VerifyAVTSpecificPath","title":"VerifyAVTSpecificPath","text":"

Verifies the status and type of an Adaptive Virtual Topology (AVT) path for a specified VRF.

Expected Results
  • Success: The test will pass if all AVT paths for the specified VRF are active, valid, and match the specified type (direct/multihop) if provided. If multiple paths are configured, the test will pass only if all the paths are valid and active.
  • Failure: The test will fail if no AVT paths are configured for the specified VRF, or if any configured path is not active, valid, or does not match the specified type.
Examples
anta.tests.avt:\n  - VerifyAVTSpecificPath:\n      avt_paths:\n        - avt_name: CONTROL-PLANE-PROFILE\n          vrf: default\n          destination: 10.101.255.2\n          next_hop: 10.101.255.1\n          path_type: direct\n
Source code in anta/tests/avt.py
class VerifyAVTSpecificPath(AntaTest):\n    \"\"\"\n    Verifies the status and type of an Adaptive Virtual Topology (AVT) path for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all AVT paths for the specified VRF are active, valid, and match the specified type (direct/multihop) if provided.\n               If multiple paths are configured, the test will pass only if all the paths are valid and active.\n    * Failure: The test will fail if no AVT paths are configured for the specified VRF, or if any configured path is not active, valid,\n               or does not match the specified type.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.avt:\n      - VerifyAVTSpecificPath:\n          avt_paths:\n            - avt_name: CONTROL-PLANE-PROFILE\n              vrf: default\n              destination: 10.101.255.2\n              next_hop: 10.101.255.1\n              path_type: direct\n    ```\n    \"\"\"\n\n    name = \"VerifyAVTSpecificPath\"\n    description = \"Verifies the status and type of an AVT path for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"avt\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaTemplate(template=\"show adaptive-virtual-topology path vrf {vrf} avt {avt_name} destination {destination}\")\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAVTSpecificPath test.\"\"\"\n\n        avt_paths: list[AVTPaths]\n        \"\"\"List of AVT paths to verify.\"\"\"\n\n        class AVTPaths(BaseModel):\n            \"\"\"Model for the details of AVT paths.\"\"\"\n\n            vrf: str = \"default\"\n            \"\"\"The VRF for the AVT path. Defaults to 'default' if not provided.\"\"\"\n            avt_name: str\n            \"\"\"Name of the adaptive virtual topology.\"\"\"\n            destination: IPv4Address\n            \"\"\"The IPv4 address of the AVT peer.\"\"\"\n            next_hop: IPv4Address\n            \"\"\"The IPv4 address of the next hop for the AVT peer.\"\"\"\n            path_type: str | None = None\n            \"\"\"The type of the AVT path. If not provided, both 'direct' and 'multihop' paths are considered.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each input AVT path/peer.\"\"\"\n        return [template.render(vrf=path.vrf, avt_name=path.avt_name, destination=path.destination) for path in self.inputs.avt_paths]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAVTSpecificPath.\"\"\"\n        # Assume the test is successful until a failure is detected\n        self.result.is_success()\n\n        # Process each command in the instance\n        for command, input_avt in zip(self.instance_commands, self.inputs.avt_paths):\n            # Extract the command output and parameters\n            vrf = command.params.vrf\n            avt_name = command.params.avt_name\n            peer = str(command.params.destination)\n\n            command_output = command.json_output.get(\"vrfs\", {})\n\n            # If no AVT is configured, mark the test as failed and skip to the next command\n            if not command_output:\n                self.result.is_failure(f\"AVT configuration for peer '{peer}' under topology '{avt_name}' in VRF '{vrf}' is not found.\")\n                continue\n\n            # Extract the AVT paths\n            avt_paths = get_value(command_output, f\"{vrf}.avts.{avt_name}.avtPaths\")\n            next_hop, input_path_type = str(input_avt.next_hop), input_avt.path_type\n\n            nexthop_path_found = path_type_found = False\n\n            # Check each AVT path\n            for path, path_data in avt_paths.items():\n                # If the path does not match the expected next hop, skip to the next path\n                if path_data.get(\"nexthopAddr\") != next_hop:\n                    continue\n\n                nexthop_path_found = True\n                path_type = \"direct\" if get_value(path_data, \"flags.directPath\") else \"multihop\"\n\n                # If the path type does not match the expected path type, skip to the next path\n                if input_path_type and path_type != input_path_type:\n                    continue\n\n                path_type_found = True\n                valid = get_value(path_data, \"flags.valid\")\n                active = get_value(path_data, \"flags.active\")\n\n                # Check the path status and type against the expected values\n                if not all([valid, active]):\n                    failure_reasons = []\n                    if not get_value(path_data, \"flags.active\"):\n                        failure_reasons.append(\"inactive\")\n                    if not get_value(path_data, \"flags.valid\"):\n                        failure_reasons.append(\"invalid\")\n                    # Construct the failure message prefix\n                    failed_log = f\"AVT path '{path}' for topology '{avt_name}' in VRF '{vrf}'\"\n                    self.result.is_failure(f\"{failed_log} is {', '.join(failure_reasons)}.\")\n\n            # If no matching next hop or path type was found, mark the test as failed\n            if not nexthop_path_found or not path_type_found:\n                self.result.is_failure(\n                    f\"No '{input_path_type}' path found with next-hop address '{next_hop}' for AVT peer '{peer}' under topology '{avt_name}' in VRF '{vrf}'.\"\n                )\n
"},{"location":"api/tests.avt/#anta.tests.avt.VerifyAVTSpecificPath-attributes","title":"Inputs","text":"Name Type Description Default avt_paths list[AVTPaths] List of AVT paths to verify. -"},{"location":"api/tests.avt/#anta.tests.avt.VerifyAVTSpecificPath-attributes","title":"AVTPaths","text":"Name Type Description Default vrf str The VRF for the AVT path. Defaults to 'default' if not provided. 'default' avt_name str Name of the adaptive virtual topology. - destination IPv4Address The IPv4 address of the AVT peer. - next_hop IPv4Address The IPv4 address of the next hop for the AVT peer. - path_type str | None The type of the AVT path. If not provided, both 'direct' and 'multihop' paths are considered. None"},{"location":"api/tests.bfd/","title":"BFD","text":""},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDPeersHealth","title":"VerifyBFDPeersHealth","text":"

Verifies the health of IPv4 BFD peers across all VRFs.

It checks that no BFD peer is in the down state and that the discriminator value of the remote system is not zero.

Optionally, it can also verify that BFD peers have not been down before a specified threshold of hours.

Expected Results
  • Success: The test will pass if all IPv4 BFD peers are up, the discriminator value of each remote system is non-zero, and the last downtime of each peer is above the defined threshold.
  • Failure: The test will fail if any IPv4 BFD peer is down, the discriminator value of any remote system is zero, or the last downtime of any peer is below the defined threshold.
Examples
anta.tests.bfd:\n  - VerifyBFDPeersHealth:\n      down_threshold: 2\n
Source code in anta/tests/bfd.py
class VerifyBFDPeersHealth(AntaTest):\n    \"\"\"Verifies the health of IPv4 BFD peers across all VRFs.\n\n    It checks that no BFD peer is in the down state and that the discriminator value of the remote system is not zero.\n\n    Optionally, it can also verify that BFD peers have not been down before a specified threshold of hours.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all IPv4 BFD peers are up, the discriminator value of each remote system is non-zero,\n               and the last downtime of each peer is above the defined threshold.\n    * Failure: The test will fail if any IPv4 BFD peer is down, the discriminator value of any remote system is zero,\n               or the last downtime of any peer is below the defined threshold.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.bfd:\n      - VerifyBFDPeersHealth:\n          down_threshold: 2\n    ```\n    \"\"\"\n\n    name = \"VerifyBFDPeersHealth\"\n    description = \"Verifies the health of all IPv4 BFD peers.\"\n    categories: ClassVar[list[str]] = [\"bfd\"]\n    # revision 1 as later revision introduces additional nesting for type\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"show bfd peers\", revision=1),\n        AntaCommand(command=\"show clock\", revision=1),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBFDPeersHealth test.\"\"\"\n\n        down_threshold: int | None = Field(default=None, gt=0)\n        \"\"\"Optional down threshold in hours to check if a BFD peer was down before those hours or not.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBFDPeersHealth.\"\"\"\n        # Initialize failure strings\n        down_failures = []\n        up_failures = []\n\n        # Extract the current timestamp and command output\n        clock_output = self.instance_commands[1].json_output\n        current_timestamp = clock_output[\"utcTime\"]\n        bfd_output = self.instance_commands[0].json_output\n\n        # set the initial result\n        self.result.is_success()\n\n        # Check if any IPv4 BFD peer is configured\n        ipv4_neighbors_exist = any(vrf_data[\"ipv4Neighbors\"] for vrf_data in bfd_output[\"vrfs\"].values())\n        if not ipv4_neighbors_exist:\n            self.result.is_failure(\"No IPv4 BFD peers are configured for any VRF.\")\n            return\n\n        # Iterate over IPv4 BFD peers\n        for vrf, vrf_data in bfd_output[\"vrfs\"].items():\n            for peer, neighbor_data in vrf_data[\"ipv4Neighbors\"].items():\n                for peer_data in neighbor_data[\"peerStats\"].values():\n                    peer_status = peer_data[\"status\"]\n                    remote_disc = peer_data[\"remoteDisc\"]\n                    remote_disc_info = f\" with remote disc {remote_disc}\" if remote_disc == 0 else \"\"\n                    last_down = peer_data[\"lastDown\"]\n                    hours_difference = (\n                        datetime.fromtimestamp(current_timestamp, tz=timezone.utc) - datetime.fromtimestamp(last_down, tz=timezone.utc)\n                    ).total_seconds() / 3600\n\n                    # Check if peer status is not up\n                    if peer_status != \"up\":\n                        down_failures.append(f\"{peer} is {peer_status} in {vrf} VRF{remote_disc_info}.\")\n\n                    # Check if the last down is within the threshold\n                    elif self.inputs.down_threshold and hours_difference < self.inputs.down_threshold:\n                        up_failures.append(f\"{peer} in {vrf} VRF was down {round(hours_difference)} hours ago{remote_disc_info}.\")\n\n                    # Check if remote disc is 0\n                    elif remote_disc == 0:\n                        up_failures.append(f\"{peer} in {vrf} VRF has remote disc {remote_disc}.\")\n\n        # Check if there are any failures\n        if down_failures:\n            down_failures_str = \"\\n\".join(down_failures)\n            self.result.is_failure(f\"Following BFD peers are not up:\\n{down_failures_str}\")\n        if up_failures:\n            up_failures_str = \"\\n\".join(up_failures)\n            self.result.is_failure(f\"\\nFollowing BFD peers were down:\\n{up_failures_str}\")\n
"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDPeersHealth-attributes","title":"Inputs","text":"Name Type Description Default down_threshold int | None Optional down threshold in hours to check if a BFD peer was down before those hours or not. Field(default=None, gt=0)"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDPeersIntervals","title":"VerifyBFDPeersIntervals","text":"

Verifies the timers of the IPv4 BFD peers in the specified VRF.

Expected Results
  • Success: The test will pass if the timers of the IPv4 BFD peers are correct in the specified VRF.
  • Failure: The test will fail if the IPv4 BFD peers are not found or their timers are incorrect in the specified VRF.
Examples
anta.tests.bfd:\n  - VerifyBFDPeersIntervals:\n      bfd_peers:\n        - peer_address: 192.0.255.8\n          vrf: default\n          tx_interval: 1200\n          rx_interval: 1200\n          multiplier: 3\n        - peer_address: 192.0.255.7\n          vrf: default\n          tx_interval: 1200\n          rx_interval: 1200\n          multiplier: 3\n
Source code in anta/tests/bfd.py
class VerifyBFDPeersIntervals(AntaTest):\n    \"\"\"Verifies the timers of the IPv4 BFD peers in the specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the timers of the IPv4 BFD peers are correct in the specified VRF.\n    * Failure: The test will fail if the IPv4 BFD peers are not found or their timers are incorrect in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.bfd:\n      - VerifyBFDPeersIntervals:\n          bfd_peers:\n            - peer_address: 192.0.255.8\n              vrf: default\n              tx_interval: 1200\n              rx_interval: 1200\n              multiplier: 3\n            - peer_address: 192.0.255.7\n              vrf: default\n              tx_interval: 1200\n              rx_interval: 1200\n              multiplier: 3\n    ```\n    \"\"\"\n\n    name = \"VerifyBFDPeersIntervals\"\n    description = \"Verifies the timers of the IPv4 BFD peers in the specified VRF.\"\n    categories: ClassVar[list[str]] = [\"bfd\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bfd peers detail\", revision=4)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBFDPeersIntervals test.\"\"\"\n\n        bfd_peers: list[BFDPeer]\n        \"\"\"List of BFD peers.\"\"\"\n\n        class BFDPeer(BaseModel):\n            \"\"\"Model for an IPv4 BFD peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BFD peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BFD peer. If not provided, it defaults to `default`.\"\"\"\n            tx_interval: BfdInterval\n            \"\"\"Tx interval of BFD peer in milliseconds.\"\"\"\n            rx_interval: BfdInterval\n            \"\"\"Rx interval of BFD peer in milliseconds.\"\"\"\n            multiplier: BfdMultiplier\n            \"\"\"Multiplier of BFD peer.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBFDPeersIntervals.\"\"\"\n        failures: dict[Any, Any] = {}\n\n        # Iterating over BFD peers\n        for bfd_peers in self.inputs.bfd_peers:\n            peer = str(bfd_peers.peer_address)\n            vrf = bfd_peers.vrf\n\n            # Converting milliseconds intervals into actual value\n            tx_interval = bfd_peers.tx_interval * 1000\n            rx_interval = bfd_peers.rx_interval * 1000\n            multiplier = bfd_peers.multiplier\n            bfd_output = get_value(\n                self.instance_commands[0].json_output,\n                f\"vrfs..{vrf}..ipv4Neighbors..{peer}..peerStats..\",\n                separator=\"..\",\n            )\n\n            # Check if BFD peer configured\n            if not bfd_output:\n                failures[peer] = {vrf: \"Not Configured\"}\n                continue\n\n            bfd_details = bfd_output.get(\"peerStatsDetail\", {})\n            intervals_ok = (\n                bfd_details.get(\"operTxInterval\") == tx_interval and bfd_details.get(\"operRxInterval\") == rx_interval and bfd_details.get(\"detectMult\") == multiplier\n            )\n\n            # Check timers of BFD peer\n            if not intervals_ok:\n                failures[peer] = {\n                    vrf: {\n                        \"tx_interval\": bfd_details.get(\"operTxInterval\"),\n                        \"rx_interval\": bfd_details.get(\"operRxInterval\"),\n                        \"multiplier\": bfd_details.get(\"detectMult\"),\n                    }\n                }\n\n        # Check if any failures\n        if not failures:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BFD peers are not configured or timers are not correct:\\n{failures}\")\n
"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDPeersIntervals-attributes","title":"Inputs","text":"Name Type Description Default bfd_peers list[BFDPeer] List of BFD peers. -"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDPeersIntervals-attributes","title":"BFDPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BFD peer. - vrf str Optional VRF for BFD peer. If not provided, it defaults to `default`. 'default' tx_interval BfdInterval Tx interval of BFD peer in milliseconds. - rx_interval BfdInterval Rx interval of BFD peer in milliseconds. - multiplier BfdMultiplier Multiplier of BFD peer. -"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDSpecificPeers","title":"VerifyBFDSpecificPeers","text":"

Verifies if the IPv4 BFD peer\u2019s sessions are UP and remote disc is non-zero in the specified VRF.

Expected Results
  • Success: The test will pass if IPv4 BFD peers are up and remote disc is non-zero in the specified VRF.
  • Failure: The test will fail if IPv4 BFD peers are not found, the status is not UP or remote disc is zero in the specified VRF.
Examples
anta.tests.bfd:\n  - VerifyBFDSpecificPeers:\n      bfd_peers:\n        - peer_address: 192.0.255.8\n          vrf: default\n        - peer_address: 192.0.255.7\n          vrf: default\n
Source code in anta/tests/bfd.py
class VerifyBFDSpecificPeers(AntaTest):\n    \"\"\"Verifies if the IPv4 BFD peer's sessions are UP and remote disc is non-zero in the specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if IPv4 BFD peers are up and remote disc is non-zero in the specified VRF.\n    * Failure: The test will fail if IPv4 BFD peers are not found, the status is not UP or remote disc is zero in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.bfd:\n      - VerifyBFDSpecificPeers:\n          bfd_peers:\n            - peer_address: 192.0.255.8\n              vrf: default\n            - peer_address: 192.0.255.7\n              vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyBFDSpecificPeers\"\n    description = \"Verifies the IPv4 BFD peer's sessions and remote disc in the specified VRF.\"\n    categories: ClassVar[list[str]] = [\"bfd\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bfd peers\", revision=4)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBFDSpecificPeers test.\"\"\"\n\n        bfd_peers: list[BFDPeer]\n        \"\"\"List of IPv4 BFD peers.\"\"\"\n\n        class BFDPeer(BaseModel):\n            \"\"\"Model for an IPv4 BFD peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BFD peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BFD peer. If not provided, it defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBFDSpecificPeers.\"\"\"\n        failures: dict[Any, Any] = {}\n\n        # Iterating over BFD peers\n        for bfd_peer in self.inputs.bfd_peers:\n            peer = str(bfd_peer.peer_address)\n            vrf = bfd_peer.vrf\n            bfd_output = get_value(\n                self.instance_commands[0].json_output,\n                f\"vrfs..{vrf}..ipv4Neighbors..{peer}..peerStats..\",\n                separator=\"..\",\n            )\n\n            # Check if BFD peer configured\n            if not bfd_output:\n                failures[peer] = {vrf: \"Not Configured\"}\n                continue\n\n            # Check BFD peer status and remote disc\n            if not (bfd_output.get(\"status\") == \"up\" and bfd_output.get(\"remoteDisc\") != 0):\n                failures[peer] = {\n                    vrf: {\n                        \"status\": bfd_output.get(\"status\"),\n                        \"remote_disc\": bfd_output.get(\"remoteDisc\"),\n                    }\n                }\n\n        if not failures:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BFD peers are not configured, status is not up or remote disc is zero:\\n{failures}\")\n
"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDSpecificPeers-attributes","title":"Inputs","text":"Name Type Description Default bfd_peers list[BFDPeer] List of IPv4 BFD peers. -"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDSpecificPeers-attributes","title":"BFDPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BFD peer. - vrf str Optional VRF for BFD peer. If not provided, it defaults to `default`. 'default'"},{"location":"api/tests.configuration/","title":"Configuration","text":""},{"location":"api/tests.configuration/#anta.tests.configuration.VerifyRunningConfigDiffs","title":"VerifyRunningConfigDiffs","text":"

Verifies there is no difference between the running-config and the startup-config.

Expected Results
  • Success: The test will pass if there is no difference between the running-config and the startup-config.
  • Failure: The test will fail if there is a difference between the running-config and the startup-config.
Examples
anta.tests.configuration:\n  - VerifyRunningConfigDiffs:\n
Source code in anta/tests/configuration.py
class VerifyRunningConfigDiffs(AntaTest):\n    \"\"\"Verifies there is no difference between the running-config and the startup-config.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there is no difference between the running-config and the startup-config.\n    * Failure: The test will fail if there is a difference between the running-config and the startup-config.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.configuration:\n      - VerifyRunningConfigDiffs:\n    ```\n    \"\"\"\n\n    name = \"VerifyRunningConfigDiffs\"\n    description = \"Verifies there is no difference between the running-config and the startup-config\"\n    categories: ClassVar[list[str]] = [\"configuration\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show running-config diffs\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyRunningConfigDiffs.\"\"\"\n        command_output = self.instance_commands[0].text_output\n        if command_output == \"\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(command_output)\n
"},{"location":"api/tests.configuration/#anta.tests.configuration.VerifyRunningConfigLines","title":"VerifyRunningConfigLines","text":"

Verifies the given regular expression patterns are present in the running-config.

Warning

Since this uses regular expression searches on the whole running-config, it can drastically impact performance and should only be used if no other test is available.

If possible, try using another ANTA test that is more specific.

Expected Results
  • Success: The test will pass if all the patterns are found in the running-config.
  • Failure: The test will fail if any of the patterns are NOT found in the running-config.
Examples
anta.tests.configuration:\n  - VerifyRunningConfigLines:\n        regex_patterns:\n            - \"^enable password.*$\"\n            - \"bla bla\"\n
Source code in anta/tests/configuration.py
class VerifyRunningConfigLines(AntaTest):\n    \"\"\"Verifies the given regular expression patterns are present in the running-config.\n\n    !!! warning\n        Since this uses regular expression searches on the whole running-config, it can\n        drastically impact performance and should only be used if no other test is available.\n\n        If possible, try using another ANTA test that is more specific.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all the patterns are found in the running-config.\n    * Failure: The test will fail if any of the patterns are NOT found in the running-config.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.configuration:\n      - VerifyRunningConfigLines:\n            regex_patterns:\n                - \"^enable password.*$\"\n                - \"bla bla\"\n    ```\n    \"\"\"\n\n    name = \"VerifyRunningConfigLines\"\n    description = \"Search the Running-Config for the given RegEx patterns.\"\n    categories: ClassVar[list[str]] = [\"configuration\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show running-config\", ofmt=\"text\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyRunningConfigLines test.\"\"\"\n\n        regex_patterns: list[RegexString]\n        \"\"\"List of regular expressions.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyRunningConfigLines.\"\"\"\n        failure_msgs = []\n        command_output = self.instance_commands[0].text_output\n\n        for pattern in self.inputs.regex_patterns:\n            re_search = re.compile(pattern, flags=re.MULTILINE)\n\n            if not re_search.search(command_output):\n                failure_msgs.append(f\"'{pattern}'\")\n\n        if not failure_msgs:\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"Following patterns were not found: \" + \",\".join(failure_msgs))\n
"},{"location":"api/tests.configuration/#anta.tests.configuration.VerifyRunningConfigLines-attributes","title":"Inputs","text":"Name Type Description Default regex_patterns list[RegexString] List of regular expressions. -"},{"location":"api/tests.configuration/#anta.tests.configuration.VerifyZeroTouch","title":"VerifyZeroTouch","text":"

Verifies ZeroTouch is disabled.

Expected Results
  • Success: The test will pass if ZeroTouch is disabled.
  • Failure: The test will fail if ZeroTouch is enabled.
Examples
anta.tests.configuration:\n  - VerifyZeroTouch:\n
Source code in anta/tests/configuration.py
class VerifyZeroTouch(AntaTest):\n    \"\"\"Verifies ZeroTouch is disabled.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if ZeroTouch is disabled.\n    * Failure: The test will fail if ZeroTouch is enabled.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.configuration:\n      - VerifyZeroTouch:\n    ```\n    \"\"\"\n\n    name = \"VerifyZeroTouch\"\n    description = \"Verifies ZeroTouch is disabled\"\n    categories: ClassVar[list[str]] = [\"configuration\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show zerotouch\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyZeroTouch.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"mode\"] == \"disabled\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"ZTP is NOT disabled\")\n
"},{"location":"api/tests.connectivity/","title":"Connectivity","text":""},{"location":"api/tests.connectivity/#anta.tests.connectivity.VerifyLLDPNeighbors","title":"VerifyLLDPNeighbors","text":"

Verifies that the provided LLDP neighbors are present and connected with the correct configuration.

Expected Results
  • Success: The test will pass if each of the provided LLDP neighbors is present and connected to the specified port and device.
  • Failure: The test will fail if any of the following conditions are met:
    • The provided LLDP neighbor is not found.
    • The system name or port of the LLDP neighbor does not match the provided information.
Examples
anta.tests.connectivity:\n  - VerifyLLDPNeighbors:\n      neighbors:\n        - port: Ethernet1\n          neighbor_device: DC1-SPINE1\n          neighbor_port: Ethernet1\n        - port: Ethernet2\n          neighbor_device: DC1-SPINE2\n          neighbor_port: Ethernet1\n
Source code in anta/tests/connectivity.py
class VerifyLLDPNeighbors(AntaTest):\n    \"\"\"Verifies that the provided LLDP neighbors are present and connected with the correct configuration.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if each of the provided LLDP neighbors is present and connected to the specified port and device.\n    * Failure: The test will fail if any of the following conditions are met:\n        - The provided LLDP neighbor is not found.\n        - The system name or port of the LLDP neighbor does not match the provided information.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.connectivity:\n      - VerifyLLDPNeighbors:\n          neighbors:\n            - port: Ethernet1\n              neighbor_device: DC1-SPINE1\n              neighbor_port: Ethernet1\n            - port: Ethernet2\n              neighbor_device: DC1-SPINE2\n              neighbor_port: Ethernet1\n    ```\n    \"\"\"\n\n    name = \"VerifyLLDPNeighbors\"\n    description = \"Verifies that the provided LLDP neighbors are connected properly.\"\n    categories: ClassVar[list[str]] = [\"connectivity\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show lldp neighbors detail\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyLLDPNeighbors test.\"\"\"\n\n        neighbors: list[Neighbor]\n        \"\"\"List of LLDP neighbors.\"\"\"\n\n        class Neighbor(BaseModel):\n            \"\"\"Model for an LLDP neighbor.\"\"\"\n\n            port: Interface\n            \"\"\"LLDP port.\"\"\"\n            neighbor_device: str\n            \"\"\"LLDP neighbor device.\"\"\"\n            neighbor_port: Interface\n            \"\"\"LLDP neighbor port.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLLDPNeighbors.\"\"\"\n        failures: dict[str, list[str]] = {}\n\n        output = self.instance_commands[0].json_output[\"lldpNeighbors\"]\n\n        for neighbor in self.inputs.neighbors:\n            if neighbor.port not in output:\n                failures.setdefault(\"Port(s) not configured\", []).append(neighbor.port)\n                continue\n\n            if len(lldp_neighbor_info := output[neighbor.port][\"lldpNeighborInfo\"]) == 0:\n                failures.setdefault(\"No LLDP neighbor(s) on port(s)\", []).append(neighbor.port)\n                continue\n\n            if not any(\n                info[\"systemName\"] == neighbor.neighbor_device and info[\"neighborInterfaceInfo\"][\"interfaceId_v2\"] == neighbor.neighbor_port\n                for info in lldp_neighbor_info\n            ):\n                neighbors = \"\\n      \".join(\n                    [\n                        f\"{neighbor[0]}_{neighbor[1]}\"\n                        for neighbor in [(info[\"systemName\"], info[\"neighborInterfaceInfo\"][\"interfaceId_v2\"]) for info in lldp_neighbor_info]\n                    ]\n                )\n                failures.setdefault(\"Wrong LLDP neighbor(s) on port(s)\", []).append(f\"{neighbor.port}\\n      {neighbors}\")\n\n        if not failures:\n            self.result.is_success()\n        else:\n            failure_messages = []\n            for failure_type, ports in failures.items():\n                ports_str = \"\\n   \".join(ports)\n                failure_messages.append(f\"{failure_type}:\\n   {ports_str}\")\n            self.result.is_failure(\"\\n\".join(failure_messages))\n
"},{"location":"api/tests.connectivity/#anta.tests.connectivity.VerifyLLDPNeighbors-attributes","title":"Inputs","text":"Name Type Description Default neighbors list[Neighbor] List of LLDP neighbors. -"},{"location":"api/tests.connectivity/#anta.tests.connectivity.VerifyLLDPNeighbors-attributes","title":"Neighbor","text":"Name Type Description Default port Interface LLDP port. - neighbor_device str LLDP neighbor device. - neighbor_port Interface LLDP neighbor port. -"},{"location":"api/tests.connectivity/#anta.tests.connectivity.VerifyReachability","title":"VerifyReachability","text":"

Test network reachability to one or many destination IP(s).

Expected Results
  • Success: The test will pass if all destination IP(s) are reachable.
  • Failure: The test will fail if one or many destination IP(s) are unreachable.
Examples
anta.tests.connectivity:\n  - VerifyReachability:\n      hosts:\n        - source: Management0\n          destination: 1.1.1.1\n          vrf: MGMT\n        - source: Management0\n          destination: 8.8.8.8\n          vrf: MGMT\n
Source code in anta/tests/connectivity.py
class VerifyReachability(AntaTest):\n    \"\"\"Test network reachability to one or many destination IP(s).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all destination IP(s) are reachable.\n    * Failure: The test will fail if one or many destination IP(s) are unreachable.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.connectivity:\n      - VerifyReachability:\n          hosts:\n            - source: Management0\n              destination: 1.1.1.1\n              vrf: MGMT\n            - source: Management0\n              destination: 8.8.8.8\n              vrf: MGMT\n    ```\n    \"\"\"\n\n    name = \"VerifyReachability\"\n    description = \"Test the network reachability to one or many destination IP(s).\"\n    categories: ClassVar[list[str]] = [\"connectivity\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"ping vrf {vrf} {destination} source {source} repeat {repeat}\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyReachability test.\"\"\"\n\n        hosts: list[Host]\n        \"\"\"List of host to ping.\"\"\"\n\n        class Host(BaseModel):\n            \"\"\"Model for a remote host to ping.\"\"\"\n\n            destination: IPv4Address\n            \"\"\"IPv4 address to ping.\"\"\"\n            source: IPv4Address | Interface\n            \"\"\"IPv4 address source IP or egress interface to use.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"VRF context. Defaults to `default`.\"\"\"\n            repeat: int = 2\n            \"\"\"Number of ping repetition. Defaults to 2.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each host in the input list.\"\"\"\n        return [template.render(destination=host.destination, source=host.source, vrf=host.vrf, repeat=host.repeat) for host in self.inputs.hosts]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyReachability.\"\"\"\n        failures = []\n        for command in self.instance_commands:\n            src = command.params.source\n            dst = command.params.destination\n            repeat = command.params.repeat\n\n            if f\"{repeat} received\" not in command.json_output[\"messages\"][0]:\n                failures.append((str(src), str(dst)))\n\n        if not failures:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Connectivity test failed for the following source-destination pairs: {failures}\")\n
"},{"location":"api/tests.connectivity/#anta.tests.connectivity.VerifyReachability-attributes","title":"Inputs","text":"Name Type Description Default hosts list[Host] List of host to ping. -"},{"location":"api/tests.connectivity/#anta.tests.connectivity.VerifyReachability-attributes","title":"Host","text":"Name Type Description Default destination IPv4Address IPv4 address to ping. - source IPv4Address | Interface IPv4 address source IP or egress interface to use. - vrf str VRF context. Defaults to `default`. 'default' repeat int Number of ping repetition. Defaults to 2. 2"},{"location":"api/tests.field_notices/","title":"Field Notices","text":""},{"location":"api/tests.field_notices/#anta.tests.field_notices.VerifyFieldNotice44Resolution","title":"VerifyFieldNotice44Resolution","text":"

Verifies if the device is using an Aboot version that fixes the bug discussed in the Field Notice 44.

Aboot manages system settings prior to EOS initialization.

Reference: https://www.arista.com/en/support/advisories-notices/field-notice/8756-field-notice-44

Expected Results
  • Success: The test will pass if the device is using an Aboot version that fixes the bug discussed in the Field Notice 44.
  • Failure: The test will fail if the device is not using an Aboot version that fixes the bug discussed in the Field Notice 44.
Examples
anta.tests.field_notices:\n  - VerifyFieldNotice44Resolution:\n
Source code in anta/tests/field_notices.py
class VerifyFieldNotice44Resolution(AntaTest):\n    \"\"\"Verifies if the device is using an Aboot version that fixes the bug discussed in the Field Notice 44.\n\n    Aboot manages system settings prior to EOS initialization.\n\n    Reference: https://www.arista.com/en/support/advisories-notices/field-notice/8756-field-notice-44\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is using an Aboot version that fixes the bug discussed in the Field Notice 44.\n    * Failure: The test will fail if the device is not using an Aboot version that fixes the bug discussed in the Field Notice 44.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.field_notices:\n      - VerifyFieldNotice44Resolution:\n    ```\n    \"\"\"\n\n    name = \"VerifyFieldNotice44Resolution\"\n    description = \"Verifies that the device is using the correct Aboot version per FN0044.\"\n    categories: ClassVar[list[str]] = [\"field notices\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show version detail\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyFieldNotice44Resolution.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        devices = [\n            \"DCS-7010T-48\",\n            \"DCS-7010T-48-DC\",\n            \"DCS-7050TX-48\",\n            \"DCS-7050TX-64\",\n            \"DCS-7050TX-72\",\n            \"DCS-7050TX-72Q\",\n            \"DCS-7050TX-96\",\n            \"DCS-7050TX2-128\",\n            \"DCS-7050SX-64\",\n            \"DCS-7050SX-72\",\n            \"DCS-7050SX-72Q\",\n            \"DCS-7050SX2-72Q\",\n            \"DCS-7050SX-96\",\n            \"DCS-7050SX2-128\",\n            \"DCS-7050QX-32S\",\n            \"DCS-7050QX2-32S\",\n            \"DCS-7050SX3-48YC12\",\n            \"DCS-7050CX3-32S\",\n            \"DCS-7060CX-32S\",\n            \"DCS-7060CX2-32S\",\n            \"DCS-7060SX2-48YC6\",\n            \"DCS-7160-48YC6\",\n            \"DCS-7160-48TC6\",\n            \"DCS-7160-32CQ\",\n            \"DCS-7280SE-64\",\n            \"DCS-7280SE-68\",\n            \"DCS-7280SE-72\",\n            \"DCS-7150SC-24-CLD\",\n            \"DCS-7150SC-64-CLD\",\n            \"DCS-7020TR-48\",\n            \"DCS-7020TRA-48\",\n            \"DCS-7020SR-24C2\",\n            \"DCS-7020SRG-24C2\",\n            \"DCS-7280TR-48C6\",\n            \"DCS-7280TRA-48C6\",\n            \"DCS-7280SR-48C6\",\n            \"DCS-7280SRA-48C6\",\n            \"DCS-7280SRAM-48C6\",\n            \"DCS-7280SR2K-48C6-M\",\n            \"DCS-7280SR2-48YC6\",\n            \"DCS-7280SR2A-48YC6\",\n            \"DCS-7280SRM-40CX2\",\n            \"DCS-7280QR-C36\",\n            \"DCS-7280QRA-C36S\",\n        ]\n        variants = [\"-SSD-F\", \"-SSD-R\", \"-M-F\", \"-M-R\", \"-F\", \"-R\"]\n\n        model = command_output[\"modelName\"]\n        for variant in variants:\n            model = model.replace(variant, \"\")\n        if model not in devices:\n            self.result.is_skipped(\"device is not impacted by FN044\")\n            return\n\n        for component in command_output[\"details\"][\"components\"]:\n            if component[\"name\"] == \"Aboot\":\n                aboot_version = component[\"version\"].split(\"-\")[2]\n                break\n        else:\n            self.result.is_failure(\"Aboot component not found\")\n            return\n\n        self.result.is_success()\n        incorrect_aboot_version = (\n            aboot_version.startswith(\"4.0.\")\n            and int(aboot_version.split(\".\")[2]) < 7\n            or aboot_version.startswith(\"4.1.\")\n            and int(aboot_version.split(\".\")[2]) < 1\n            or (\n                aboot_version.startswith(\"6.0.\")\n                and int(aboot_version.split(\".\")[2]) < 9\n                or aboot_version.startswith(\"6.1.\")\n                and int(aboot_version.split(\".\")[2]) < 7\n            )\n        )\n        if incorrect_aboot_version:\n            self.result.is_failure(f\"device is running incorrect version of aboot ({aboot_version})\")\n
"},{"location":"api/tests.field_notices/#anta.tests.field_notices.VerifyFieldNotice72Resolution","title":"VerifyFieldNotice72Resolution","text":"

Verifies if the device is potentially exposed to Field Notice 72, and if the issue has been mitigated.

Reference: https://www.arista.com/en/support/advisories-notices/field-notice/17410-field-notice-0072

Expected Results
  • Success: The test will pass if the device is not exposed to FN72 and the issue has been mitigated.
  • Failure: The test will fail if the device is exposed to FN72 and the issue has not been mitigated.
Examples
anta.tests.field_notices:\n  - VerifyFieldNotice72Resolution:\n
Source code in anta/tests/field_notices.py
class VerifyFieldNotice72Resolution(AntaTest):\n    \"\"\"Verifies if the device is potentially exposed to Field Notice 72, and if the issue has been mitigated.\n\n    Reference: https://www.arista.com/en/support/advisories-notices/field-notice/17410-field-notice-0072\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is not exposed to FN72 and the issue has been mitigated.\n    * Failure: The test will fail if the device is exposed to FN72 and the issue has not been mitigated.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.field_notices:\n      - VerifyFieldNotice72Resolution:\n    ```\n    \"\"\"\n\n    name = \"VerifyFieldNotice72Resolution\"\n    description = \"Verifies if the device is exposed to FN0072, and if the issue has been mitigated.\"\n    categories: ClassVar[list[str]] = [\"field notices\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show version detail\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyFieldNotice72Resolution.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        devices = [\"DCS-7280SR3-48YC8\", \"DCS-7280SR3K-48YC8\"]\n        variants = [\"-SSD-F\", \"-SSD-R\", \"-M-F\", \"-M-R\", \"-F\", \"-R\"]\n        model = command_output[\"modelName\"]\n\n        for variant in variants:\n            model = model.replace(variant, \"\")\n        if model not in devices:\n            self.result.is_skipped(\"Platform is not impacted by FN072\")\n            return\n\n        serial = command_output[\"serialNumber\"]\n        number = int(serial[3:7])\n\n        if \"JPE\" not in serial and \"JAS\" not in serial:\n            self.result.is_skipped(\"Device not exposed\")\n            return\n\n        if model == \"DCS-7280SR3-48YC8\" and \"JPE\" in serial and number >= 2131:\n            self.result.is_skipped(\"Device not exposed\")\n            return\n\n        if model == \"DCS-7280SR3-48YC8\" and \"JAS\" in serial and number >= 2041:\n            self.result.is_skipped(\"Device not exposed\")\n            return\n\n        if model == \"DCS-7280SR3K-48YC8\" and \"JPE\" in serial and number >= 2134:\n            self.result.is_skipped(\"Device not exposed\")\n            return\n\n        if model == \"DCS-7280SR3K-48YC8\" and \"JAS\" in serial and number >= 2041:\n            self.result.is_skipped(\"Device not exposed\")\n            return\n\n        # Because each of the if checks above will return if taken, we only run the long check if we get this far\n        for entry in command_output[\"details\"][\"components\"]:\n            if entry[\"name\"] == \"FixedSystemvrm1\":\n                if int(entry[\"version\"]) < 7:\n                    self.result.is_failure(\"Device is exposed to FN72\")\n                else:\n                    self.result.is_success(\"FN72 is mitigated\")\n                return\n        # We should never hit this point\n        self.result.is_error(\"Error in running test - FixedSystemvrm1 not found\")\n
"},{"location":"api/tests.greent/","title":"GreenT","text":""},{"location":"api/tests.greent/#anta.tests.greent.VerifyGreenT","title":"VerifyGreenT","text":"

Verifies if a GreenT (GRE Encapsulated Telemetry) policy other than the default is created.

Expected Results
  • Success: The test will pass if a GreenT policy is created other than the default one.
  • Failure: The test will fail if no other GreenT policy is created.
Examples
anta.tests.greent:\n  - VerifyGreenTCounters:\n
Source code in anta/tests/greent.py
class VerifyGreenT(AntaTest):\n    \"\"\"Verifies if a GreenT (GRE Encapsulated Telemetry) policy other than the default is created.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if a GreenT policy is created other than the default one.\n    * Failure: The test will fail if no other GreenT policy is created.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.greent:\n      - VerifyGreenTCounters:\n    ```\n    \"\"\"\n\n    name = \"VerifyGreenT\"\n    description = \"Verifies if a GreenT policy is created.\"\n    categories: ClassVar[list[str]] = [\"greent\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show monitor telemetry postcard policy profile\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyGreenT.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        profiles = [profile for profile in command_output[\"profiles\"] if profile != \"default\"]\n\n        if profiles:\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"No GreenT policy is created\")\n
"},{"location":"api/tests.greent/#anta.tests.greent.VerifyGreenTCounters","title":"VerifyGreenTCounters","text":"

Verifies if the GreenT (GRE Encapsulated Telemetry) counters are incremented.

Expected Results
  • Success: The test will pass if the GreenT counters are incremented.
  • Failure: The test will fail if the GreenT counters are not incremented.
Examples
anta.tests.greent:\n  - VerifyGreenT:\n
Source code in anta/tests/greent.py
class VerifyGreenTCounters(AntaTest):\n    \"\"\"Verifies if the GreenT (GRE Encapsulated Telemetry) counters are incremented.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the GreenT counters are incremented.\n    * Failure: The test will fail if the GreenT counters are not incremented.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.greent:\n      - VerifyGreenT:\n    ```\n    \"\"\"\n\n    name = \"VerifyGreenTCounters\"\n    description = \"Verifies if the GreenT counters are incremented.\"\n    categories: ClassVar[list[str]] = [\"greent\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show monitor telemetry postcard counters\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyGreenTCounters.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        if command_output[\"grePktSent\"] > 0:\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"GreenT counters are not incremented\")\n
"},{"location":"api/tests.hardware/","title":"Hardware","text":""},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyAdverseDrops","title":"VerifyAdverseDrops","text":"

Verifies there are no adverse drops on DCS-7280 and DCS-7500 family switches (Arad/Jericho chips).

Expected Results
  • Success: The test will pass if there are no adverse drops.
  • Failure: The test will fail if there are adverse drops.
Examples
anta.tests.hardware:\n  - VerifyAdverseDrops:\n
Source code in anta/tests/hardware.py
class VerifyAdverseDrops(AntaTest):\n    \"\"\"Verifies there are no adverse drops on DCS-7280 and DCS-7500 family switches (Arad/Jericho chips).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are no adverse drops.\n    * Failure: The test will fail if there are adverse drops.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyAdverseDrops:\n    ```\n    \"\"\"\n\n    name = \"VerifyAdverseDrops\"\n    description = \"Verifies there are no adverse drops on DCS-7280 and DCS-7500 family switches.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show hardware counter drop\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAdverseDrops.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        total_adverse_drop = command_output.get(\"totalAdverseDrops\", \"\")\n        if total_adverse_drop == 0:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device totalAdverseDrops counter is: '{total_adverse_drop}'\")\n
"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyEnvironmentCooling","title":"VerifyEnvironmentCooling","text":"

Verifies the status of power supply fans and all fan trays.

Expected Results
  • Success: The test will pass if the fans status are within the accepted states list.
  • Failure: The test will fail if some fans status is not within the accepted states list.
Examples
anta.tests.hardware:\n  - VerifyEnvironmentCooling:\n      states:\n        - ok\n
Source code in anta/tests/hardware.py
class VerifyEnvironmentCooling(AntaTest):\n    \"\"\"Verifies the status of power supply fans and all fan trays.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the fans status are within the accepted states list.\n    * Failure: The test will fail if some fans status is not within the accepted states list.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyEnvironmentCooling:\n          states:\n            - ok\n    ```\n    \"\"\"\n\n    name = \"VerifyEnvironmentCooling\"\n    description = \"Verifies the status of power supply fans and all fan trays.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system environment cooling\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyEnvironmentCooling test.\"\"\"\n\n        states: list[str]\n        \"\"\"List of accepted states of fan status.\"\"\"\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyEnvironmentCooling.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n        # First go through power supplies fans\n        for power_supply in command_output.get(\"powerSupplySlots\", []):\n            for fan in power_supply.get(\"fans\", []):\n                if (state := fan[\"status\"]) not in self.inputs.states:\n                    self.result.is_failure(f\"Fan {fan['label']} on PowerSupply {power_supply['label']} is: '{state}'\")\n        # Then go through fan trays\n        for fan_tray in command_output.get(\"fanTraySlots\", []):\n            for fan in fan_tray.get(\"fans\", []):\n                if (state := fan[\"status\"]) not in self.inputs.states:\n                    self.result.is_failure(f\"Fan {fan['label']} on Fan Tray {fan_tray['label']} is: '{state}'\")\n
"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyEnvironmentCooling-attributes","title":"Inputs","text":"Name Type Description Default states list[str] List of accepted states of fan status. -"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyEnvironmentPower","title":"VerifyEnvironmentPower","text":"

Verifies the power supplies status.

Expected Results
  • Success: The test will pass if the power supplies status are within the accepted states list.
  • Failure: The test will fail if some power supplies status is not within the accepted states list.
Examples
anta.tests.hardware:\n  - VerifyEnvironmentPower:\n      states:\n        - ok\n
Source code in anta/tests/hardware.py
class VerifyEnvironmentPower(AntaTest):\n    \"\"\"Verifies the power supplies status.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the power supplies status are within the accepted states list.\n    * Failure: The test will fail if some power supplies status is not within the accepted states list.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyEnvironmentPower:\n          states:\n            - ok\n    ```\n    \"\"\"\n\n    name = \"VerifyEnvironmentPower\"\n    description = \"Verifies the power supplies status.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system environment power\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyEnvironmentPower test.\"\"\"\n\n        states: list[str]\n        \"\"\"List of accepted states list of power supplies status.\"\"\"\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyEnvironmentPower.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        power_supplies = command_output.get(\"powerSupplies\", \"{}\")\n        wrong_power_supplies = {\n            powersupply: {\"state\": value[\"state\"]} for powersupply, value in dict(power_supplies).items() if value[\"state\"] not in self.inputs.states\n        }\n        if not wrong_power_supplies:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following power supplies status are not in the accepted states list: {wrong_power_supplies}\")\n
"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyEnvironmentPower-attributes","title":"Inputs","text":"Name Type Description Default states list[str] List of accepted states list of power supplies status. -"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyEnvironmentSystemCooling","title":"VerifyEnvironmentSystemCooling","text":"

Verifies the device\u2019s system cooling status.

Expected Results
  • Success: The test will pass if the system cooling status is OK: \u2018coolingOk\u2019.
  • Failure: The test will fail if the system cooling status is NOT OK.
Examples
anta.tests.hardware:\n  - VerifyEnvironmentSystemCooling:\n
Source code in anta/tests/hardware.py
class VerifyEnvironmentSystemCooling(AntaTest):\n    \"\"\"Verifies the device's system cooling status.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the system cooling status is OK: 'coolingOk'.\n    * Failure: The test will fail if the system cooling status is NOT OK.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyEnvironmentSystemCooling:\n    ```\n    \"\"\"\n\n    name = \"VerifyEnvironmentSystemCooling\"\n    description = \"Verifies the system cooling status.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system environment cooling\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyEnvironmentSystemCooling.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        sys_status = command_output.get(\"systemStatus\", \"\")\n        self.result.is_success()\n        if sys_status != \"coolingOk\":\n            self.result.is_failure(f\"Device system cooling is not OK: '{sys_status}'\")\n
"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyTemperature","title":"VerifyTemperature","text":"

Verifies if the device temperature is within acceptable limits.

Expected Results
  • Success: The test will pass if the device temperature is currently OK: \u2018temperatureOk\u2019.
  • Failure: The test will fail if the device temperature is NOT OK.
Examples
anta.tests.hardware:\n  - VerifyTemperature:\n
Source code in anta/tests/hardware.py
class VerifyTemperature(AntaTest):\n    \"\"\"Verifies if the device temperature is within acceptable limits.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device temperature is currently OK: 'temperatureOk'.\n    * Failure: The test will fail if the device temperature is NOT OK.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyTemperature:\n    ```\n    \"\"\"\n\n    name = \"VerifyTemperature\"\n    description = \"Verifies the device temperature.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system environment temperature\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTemperature.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        temperature_status = command_output.get(\"systemStatus\", \"\")\n        if temperature_status == \"temperatureOk\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device temperature exceeds acceptable limits. Current system status: '{temperature_status}'\")\n
"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyTransceiversManufacturers","title":"VerifyTransceiversManufacturers","text":"

Verifies if all the transceivers come from approved manufacturers.

Expected Results
  • Success: The test will pass if all transceivers are from approved manufacturers.
  • Failure: The test will fail if some transceivers are from unapproved manufacturers.
Examples
anta.tests.hardware:\n  - VerifyTransceiversManufacturers:\n      manufacturers:\n        - Not Present\n        - Arista Networks\n        - Arastra, Inc.\n
Source code in anta/tests/hardware.py
class VerifyTransceiversManufacturers(AntaTest):\n    \"\"\"Verifies if all the transceivers come from approved manufacturers.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all transceivers are from approved manufacturers.\n    * Failure: The test will fail if some transceivers are from unapproved manufacturers.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyTransceiversManufacturers:\n          manufacturers:\n            - Not Present\n            - Arista Networks\n            - Arastra, Inc.\n    ```\n    \"\"\"\n\n    name = \"VerifyTransceiversManufacturers\"\n    description = \"Verifies if all transceivers come from approved manufacturers.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show inventory\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyTransceiversManufacturers test.\"\"\"\n\n        manufacturers: list[str]\n        \"\"\"List of approved transceivers manufacturers.\"\"\"\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTransceiversManufacturers.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        wrong_manufacturers = {\n            interface: value[\"mfgName\"] for interface, value in command_output[\"xcvrSlots\"].items() if value[\"mfgName\"] not in self.inputs.manufacturers\n        }\n        if not wrong_manufacturers:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Some transceivers are from unapproved manufacturers: {wrong_manufacturers}\")\n
"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyTransceiversManufacturers-attributes","title":"Inputs","text":"Name Type Description Default manufacturers list[str] List of approved transceivers manufacturers. -"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyTransceiversTemperature","title":"VerifyTransceiversTemperature","text":"

Verifies if all the transceivers are operating at an acceptable temperature.

Expected Results
  • Success: The test will pass if all transceivers status are OK: \u2018ok\u2019.
  • Failure: The test will fail if some transceivers are NOT OK.
Examples
anta.tests.hardware:\n  - VerifyTransceiversTemperature:\n
Source code in anta/tests/hardware.py
class VerifyTransceiversTemperature(AntaTest):\n    \"\"\"Verifies if all the transceivers are operating at an acceptable temperature.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all transceivers status are OK: 'ok'.\n    * Failure: The test will fail if some transceivers are NOT OK.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyTransceiversTemperature:\n    ```\n    \"\"\"\n\n    name = \"VerifyTransceiversTemperature\"\n    description = \"Verifies the transceivers temperature.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system environment temperature transceiver\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTransceiversTemperature.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        sensors = command_output.get(\"tempSensors\", \"\")\n        wrong_sensors = {\n            sensor[\"name\"]: {\n                \"hwStatus\": sensor[\"hwStatus\"],\n                \"alertCount\": sensor[\"alertCount\"],\n            }\n            for sensor in sensors\n            if sensor[\"hwStatus\"] != \"ok\" or sensor[\"alertCount\"] != 0\n        }\n        if not wrong_sensors:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following sensors are operating outside the acceptable temperature range or have raised alerts: {wrong_sensors}\")\n
"},{"location":"api/tests.interfaces/","title":"Interfaces","text":""},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyIPProxyARP","title":"VerifyIPProxyARP","text":"

Verifies if Proxy-ARP is enabled for the provided list of interface(s).

Expected Results
  • Success: The test will pass if Proxy-ARP is enabled on the specified interface(s).
  • Failure: The test will fail if Proxy-ARP is disabled on the specified interface(s).
Examples
anta.tests.interfaces:\n  - VerifyIPProxyARP:\n      interfaces:\n        - Ethernet1\n        - Ethernet2\n
Source code in anta/tests/interfaces.py
class VerifyIPProxyARP(AntaTest):\n    \"\"\"Verifies if Proxy-ARP is enabled for the provided list of interface(s).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if Proxy-ARP is enabled on the specified interface(s).\n    * Failure: The test will fail if Proxy-ARP is disabled on the specified interface(s).\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyIPProxyARP:\n          interfaces:\n            - Ethernet1\n            - Ethernet2\n    ```\n    \"\"\"\n\n    name = \"VerifyIPProxyARP\"\n    description = \"Verifies if Proxy ARP is enabled.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show ip interface {intf}\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyIPProxyARP test.\"\"\"\n\n        interfaces: list[str]\n        \"\"\"List of interfaces to be tested.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each interface in the input list.\"\"\"\n        return [template.render(intf=intf) for intf in self.inputs.interfaces]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIPProxyARP.\"\"\"\n        disabled_intf = []\n        for command in self.instance_commands:\n            intf = command.params.intf\n            if not command.json_output[\"interfaces\"][intf][\"proxyArp\"]:\n                disabled_intf.append(intf)\n        if disabled_intf:\n            self.result.is_failure(f\"The following interface(s) have Proxy-ARP disabled: {disabled_intf}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyIPProxyARP-attributes","title":"Inputs","text":"Name Type Description Default interfaces list[str] List of interfaces to be tested. -"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyIllegalLACP","title":"VerifyIllegalLACP","text":"

Verifies there are no illegal LACP packets in all port channels.

Expected Results
  • Success: The test will pass if there are no illegal LACP packets received.
  • Failure: The test will fail if there is at least one illegal LACP packet received.
Examples
anta.tests.interfaces:\n  - VerifyIllegalLACP:\n
Source code in anta/tests/interfaces.py
class VerifyIllegalLACP(AntaTest):\n    \"\"\"Verifies there are no illegal LACP packets in all port channels.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are no illegal LACP packets received.\n    * Failure: The test will fail if there is at least one illegal LACP packet received.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyIllegalLACP:\n    ```\n    \"\"\"\n\n    name = \"VerifyIllegalLACP\"\n    description = \"Verifies there are no illegal LACP packets in all port channels.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show lacp counters all-ports\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIllegalLACP.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        po_with_illegal_lacp: list[dict[str, dict[str, int]]] = []\n        for portchannel, portchannel_dict in command_output[\"portChannels\"].items():\n            po_with_illegal_lacp.extend(\n                {portchannel: interface} for interface, interface_dict in portchannel_dict[\"interfaces\"].items() if interface_dict[\"illegalRxCount\"] != 0\n            )\n        if not po_with_illegal_lacp:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following port-channels have received illegal LACP packets on the following ports: {po_with_illegal_lacp}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceDiscards","title":"VerifyInterfaceDiscards","text":"

Verifies that the interfaces packet discard counters are equal to zero.

Expected Results
  • Success: The test will pass if all interfaces have discard counters equal to zero.
  • Failure: The test will fail if one or more interfaces have non-zero discard counters.
Examples
anta.tests.interfaces:\n  - VerifyInterfaceDiscards:\n
Source code in anta/tests/interfaces.py
class VerifyInterfaceDiscards(AntaTest):\n    \"\"\"Verifies that the interfaces packet discard counters are equal to zero.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all interfaces have discard counters equal to zero.\n    * Failure: The test will fail if one or more interfaces have non-zero discard counters.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfaceDiscards:\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfaceDiscards\"\n    description = \"Verifies there are no interface discard counters.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces counters discards\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfaceDiscards.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        wrong_interfaces: list[dict[str, dict[str, int]]] = []\n        for interface, outer_v in command_output[\"interfaces\"].items():\n            wrong_interfaces.extend({interface: outer_v} for value in outer_v.values() if value > 0)\n        if not wrong_interfaces:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following interfaces have non 0 discard counter(s): {wrong_interfaces}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceErrDisabled","title":"VerifyInterfaceErrDisabled","text":"

Verifies there are no interfaces in the errdisabled state.

Expected Results
  • Success: The test will pass if there are no interfaces in the errdisabled state.
  • Failure: The test will fail if there is at least one interface in the errdisabled state.
Examples
anta.tests.interfaces:\n  - VerifyInterfaceErrDisabled:\n
Source code in anta/tests/interfaces.py
class VerifyInterfaceErrDisabled(AntaTest):\n    \"\"\"Verifies there are no interfaces in the errdisabled state.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are no interfaces in the errdisabled state.\n    * Failure: The test will fail if there is at least one interface in the errdisabled state.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfaceErrDisabled:\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfaceErrDisabled\"\n    description = \"Verifies there are no interfaces in the errdisabled state.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces status\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfaceErrDisabled.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        errdisabled_interfaces = [interface for interface, value in command_output[\"interfaceStatuses\"].items() if value[\"linkStatus\"] == \"errdisabled\"]\n        if errdisabled_interfaces:\n            self.result.is_failure(f\"The following interfaces are in error disabled state: {errdisabled_interfaces}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceErrors","title":"VerifyInterfaceErrors","text":"

Verifies that the interfaces error counters are equal to zero.

Expected Results
  • Success: The test will pass if all interfaces have error counters equal to zero.
  • Failure: The test will fail if one or more interfaces have non-zero error counters.
Examples
anta.tests.interfaces:\n  - VerifyInterfaceErrors:\n
Source code in anta/tests/interfaces.py
class VerifyInterfaceErrors(AntaTest):\n    \"\"\"Verifies that the interfaces error counters are equal to zero.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all interfaces have error counters equal to zero.\n    * Failure: The test will fail if one or more interfaces have non-zero error counters.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfaceErrors:\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfaceErrors\"\n    description = \"Verifies there are no interface error counters.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces counters errors\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfaceErrors.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        wrong_interfaces: list[dict[str, dict[str, int]]] = []\n        for interface, counters in command_output[\"interfaceErrorCounters\"].items():\n            if any(value > 0 for value in counters.values()) and all(interface not in wrong_interface for wrong_interface in wrong_interfaces):\n                wrong_interfaces.append({interface: counters})\n        if not wrong_interfaces:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following interface(s) have non-zero error counters: {wrong_interfaces}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceIPv4","title":"VerifyInterfaceIPv4","text":"

Verifies if an interface is configured with a correct primary and list of optional secondary IPv4 addresses.

Expected Results
  • Success: The test will pass if an interface is configured with a correct primary and secondary IPv4 address.
  • Failure: The test will fail if an interface is not found or the primary and secondary IPv4 addresses do not match with the input.
Examples
anta.tests.interfaces:\n  - VerifyInterfaceIPv4:\n      interfaces:\n        - name: Ethernet2\n          primary_ip: 172.30.11.0/31\n          secondary_ips:\n            - 10.10.10.0/31\n            - 10.10.10.10/31\n
Source code in anta/tests/interfaces.py
class VerifyInterfaceIPv4(AntaTest):\n    \"\"\"Verifies if an interface is configured with a correct primary and list of optional secondary IPv4 addresses.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if an interface is configured with a correct primary and secondary IPv4 address.\n    * Failure: The test will fail if an interface is not found or the primary and secondary IPv4 addresses do not match with the input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfaceIPv4:\n          interfaces:\n            - name: Ethernet2\n              primary_ip: 172.30.11.0/31\n              secondary_ips:\n                - 10.10.10.0/31\n                - 10.10.10.10/31\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfaceIPv4\"\n    description = \"Verifies the interface IPv4 addresses.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show ip interface {interface}\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyInterfaceIPv4 test.\"\"\"\n\n        interfaces: list[InterfaceDetail]\n        \"\"\"List of interfaces with their details.\"\"\"\n\n        class InterfaceDetail(BaseModel):\n            \"\"\"Model for an interface detail.\"\"\"\n\n            name: Interface\n            \"\"\"Name of the interface.\"\"\"\n            primary_ip: IPv4Network\n            \"\"\"Primary IPv4 address in CIDR notation.\"\"\"\n            secondary_ips: list[IPv4Network] | None = None\n            \"\"\"Optional list of secondary IPv4 addresses in CIDR notation.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each interface in the input list.\"\"\"\n        return [template.render(interface=interface.name) for interface in self.inputs.interfaces]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfaceIPv4.\"\"\"\n        self.result.is_success()\n        for command in self.instance_commands:\n            intf = command.params.interface\n            for interface in self.inputs.interfaces:\n                if interface.name == intf:\n                    input_interface_detail = interface\n                    break\n            else:\n                self.result.is_error(f\"Could not find `{intf}` in the input interfaces. {GITHUB_SUGGESTION}\")\n                continue\n\n            input_primary_ip = str(input_interface_detail.primary_ip)\n            failed_messages = []\n\n            # Check if the interface has an IP address configured\n            if not (interface_output := get_value(command.json_output, f\"interfaces.{intf}.interfaceAddress\")):\n                self.result.is_failure(f\"For interface `{intf}`, IP address is not configured.\")\n                continue\n\n            primary_ip = get_value(interface_output, \"primaryIp\")\n\n            # Combine IP address and subnet for primary IP\n            actual_primary_ip = f\"{primary_ip['address']}/{primary_ip['maskLen']}\"\n\n            # Check if the primary IP address matches the input\n            if actual_primary_ip != input_primary_ip:\n                failed_messages.append(f\"The expected primary IP address is `{input_primary_ip}`, but the actual primary IP address is `{actual_primary_ip}`.\")\n\n            if (param_secondary_ips := input_interface_detail.secondary_ips) is not None:\n                input_secondary_ips = sorted([str(network) for network in param_secondary_ips])\n                secondary_ips = get_value(interface_output, \"secondaryIpsOrderedList\")\n\n                # Combine IP address and subnet for secondary IPs\n                actual_secondary_ips = sorted([f\"{secondary_ip['address']}/{secondary_ip['maskLen']}\" for secondary_ip in secondary_ips])\n\n                # Check if the secondary IP address is configured\n                if not actual_secondary_ips:\n                    failed_messages.append(\n                        f\"The expected secondary IP addresses are `{input_secondary_ips}`, but the actual secondary IP address is not configured.\"\n                    )\n\n                # Check if the secondary IP addresses match the input\n                elif actual_secondary_ips != input_secondary_ips:\n                    failed_messages.append(\n                        f\"The expected secondary IP addresses are `{input_secondary_ips}`, but the actual secondary IP addresses are `{actual_secondary_ips}`.\"\n                    )\n\n            if failed_messages:\n                self.result.is_failure(f\"For interface `{intf}`, \" + \" \".join(failed_messages))\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceIPv4-attributes","title":"Inputs","text":"Name Type Description Default interfaces list[InterfaceDetail] List of interfaces with their details. -"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceIPv4-attributes","title":"InterfaceDetail","text":"Name Type Description Default name Interface Name of the interface. - primary_ip IPv4Network Primary IPv4 address in CIDR notation. - secondary_ips list[IPv4Network] | None Optional list of secondary IPv4 addresses in CIDR notation. None"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceUtilization","title":"VerifyInterfaceUtilization","text":"

Verifies that the utilization of interfaces is below a certain threshold.

Load interval (default to 5 minutes) is defined in device configuration. This test has been implemented for full-duplex interfaces only.

Expected Results
  • Success: The test will pass if all interfaces have a usage below the threshold.
  • Failure: The test will fail if one or more interfaces have a usage above the threshold.
  • Error: The test will error out if the device has at least one non full-duplex interface.
Examples
anta.tests.interfaces:\n  - VerifyInterfaceUtilization:\n      threshold: 70.0\n
Source code in anta/tests/interfaces.py
class VerifyInterfaceUtilization(AntaTest):\n    \"\"\"Verifies that the utilization of interfaces is below a certain threshold.\n\n    Load interval (default to 5 minutes) is defined in device configuration.\n    This test has been implemented for full-duplex interfaces only.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all interfaces have a usage below the threshold.\n    * Failure: The test will fail if one or more interfaces have a usage above the threshold.\n    * Error: The test will error out if the device has at least one non full-duplex interface.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfaceUtilization:\n          threshold: 70.0\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfaceUtilization\"\n    description = \"Verifies that the utilization of interfaces is below a certain threshold.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"show interfaces counters rates\", revision=1),\n        AntaCommand(command=\"show interfaces\", revision=1),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyInterfaceUtilization test.\"\"\"\n\n        threshold: Percent = 75.0\n        \"\"\"Interface utilization threshold above which the test will fail. Defaults to 75%.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfaceUtilization.\"\"\"\n        duplex_full = \"duplexFull\"\n        failed_interfaces: dict[str, dict[str, float]] = {}\n        rates = self.instance_commands[0].json_output\n        interfaces = self.instance_commands[1].json_output\n\n        for intf, rate in rates[\"interfaces\"].items():\n            # The utilization logic has been implemented for full-duplex interfaces only\n            if ((duplex := (interface := interfaces[\"interfaces\"][intf]).get(\"duplex\", None)) is not None and duplex != duplex_full) or (\n                (members := interface.get(\"memberInterfaces\", None)) is not None and any(stats[\"duplex\"] != duplex_full for stats in members.values())\n            ):\n                self.result.is_error(f\"Interface {intf} or one of its member interfaces is not Full-Duplex. VerifyInterfaceUtilization has not been implemented.\")\n                return\n\n            if (bandwidth := interfaces[\"interfaces\"][intf][\"bandwidth\"]) == 0:\n                self.logger.debug(\"Interface %s has been ignored due to null bandwidth value\", intf)\n                continue\n\n            for bps_rate in (\"inBpsRate\", \"outBpsRate\"):\n                usage = rate[bps_rate] / bandwidth * 100\n                if usage > self.inputs.threshold:\n                    failed_interfaces.setdefault(intf, {})[bps_rate] = usage\n\n        if not failed_interfaces:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following interfaces have a usage > {self.inputs.threshold}%: {failed_interfaces}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceUtilization-attributes","title":"Inputs","text":"Name Type Description Default threshold Percent Interface utilization threshold above which the test will fail. Defaults to 75%. 75.0"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfacesSpeed","title":"VerifyInterfacesSpeed","text":"

Verifies the speed, lanes, auto-negotiation status, and mode as full duplex for interfaces.

  • If the auto-negotiation status is set to True, verifies that auto-negotiation is successful, the mode is full duplex and the speed/lanes match the input.
  • If the auto-negotiation status is set to False, verifies that the mode is full duplex and the speed/lanes match the input.
Expected Results
  • Success: The test will pass if an interface is configured correctly with the specified speed, lanes, auto-negotiation status, and mode as full duplex.
  • Failure: The test will fail if an interface is not found, if the speed, lanes, and auto-negotiation status do not match the input, or mode is not full duplex.
Examples
anta.tests.interfaces:\n  - VerifyInterfacesSpeed:\n      interfaces:\n        - name: Ethernet2\n          auto: False\n          speed: 10\n        - name: Eth3\n          auto: True\n          speed: 100\n          lanes: 1\n        - name: Eth2\n          auto: False\n          speed: 2.5\n
Source code in anta/tests/interfaces.py
class VerifyInterfacesSpeed(AntaTest):\n    \"\"\"Verifies the speed, lanes, auto-negotiation status, and mode as full duplex for interfaces.\n\n    - If the auto-negotiation status is set to True, verifies that auto-negotiation is successful, the mode is full duplex and the speed/lanes match the input.\n    - If the auto-negotiation status is set to False, verifies that the mode is full duplex and the speed/lanes match the input.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if an interface is configured correctly with the specified speed, lanes, auto-negotiation status, and mode as full duplex.\n    * Failure: The test will fail if an interface is not found, if the speed, lanes, and auto-negotiation status do not match the input, or mode is not full duplex.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfacesSpeed:\n          interfaces:\n            - name: Ethernet2\n              auto: False\n              speed: 10\n            - name: Eth3\n              auto: True\n              speed: 100\n              lanes: 1\n            - name: Eth2\n              auto: False\n              speed: 2.5\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfacesSpeed\"\n    description = \"Verifies the speed, lanes, auto-negotiation status, and mode as full duplex for interfaces.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Inputs for the VerifyInterfacesSpeed test.\"\"\"\n\n        interfaces: list[InterfaceDetail]\n        \"\"\"List of interfaces to be tested\"\"\"\n\n        class InterfaceDetail(BaseModel):\n            \"\"\"Detail of an interface.\"\"\"\n\n            name: EthernetInterface\n            \"\"\"The name of the interface.\"\"\"\n            auto: bool\n            \"\"\"The auto-negotiation status of the interface.\"\"\"\n            speed: float = Field(ge=1, le=1000)\n            \"\"\"The speed of the interface in Gigabits per second. Valid range is 1 to 1000.\"\"\"\n            lanes: None | int = Field(None, ge=1, le=8)\n            \"\"\"The number of lanes in the interface. Valid range is 1 to 8. This field is optional.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfacesSpeed.\"\"\"\n        self.result.is_success()\n        command_output = self.instance_commands[0].json_output\n\n        # Iterate over all the interfaces\n        for interface in self.inputs.interfaces:\n            intf = interface.name\n\n            # Check if interface exists\n            if not (interface_output := get_value(command_output, f\"interfaces.{intf}\")):\n                self.result.is_failure(f\"Interface `{intf}` is not found.\")\n                continue\n\n            auto_negotiation = interface_output.get(\"autoNegotiate\")\n            actual_lanes = interface_output.get(\"lanes\")\n\n            # Collecting actual interface details\n            actual_interface_output = {\n                \"auto negotiation\": auto_negotiation if interface.auto is True else None,\n                \"duplex mode\": interface_output.get(\"duplex\"),\n                \"speed\": interface_output.get(\"bandwidth\"),\n                \"lanes\": actual_lanes if interface.lanes is not None else None,\n            }\n\n            # Forming expected interface details\n            expected_interface_output = {\n                \"auto negotiation\": \"success\" if interface.auto is True else None,\n                \"duplex mode\": \"duplexFull\",\n                \"speed\": interface.speed * BPS_GBPS_CONVERSIONS,\n                \"lanes\": interface.lanes,\n            }\n\n            # Forming failure message\n            if actual_interface_output != expected_interface_output:\n                for output in [actual_interface_output, expected_interface_output]:\n                    # Convert speed to Gbps for readability\n                    if output[\"speed\"] is not None:\n                        output[\"speed\"] = f\"{custom_division(output['speed'], BPS_GBPS_CONVERSIONS)}Gbps\"\n                failed_log = get_failed_logs(expected_interface_output, actual_interface_output)\n                self.result.is_failure(f\"For interface {intf}:{failed_log}\\n\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfacesSpeed-attributes","title":"Inputs","text":"Name Type Description Default interfaces list[InterfaceDetail] List of interfaces to be tested -"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfacesSpeed-attributes","title":"InterfaceDetail","text":"Name Type Description Default name EthernetInterface The name of the interface. - auto bool The auto-negotiation status of the interface. - speed float The speed of the interface in Gigabits per second. Valid range is 1 to 1000. Field(ge=1, le=1000) lanes None | int The number of lanes in the interface. Valid range is 1 to 8. This field is optional. Field(None, ge=1, le=8)"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfacesStatus","title":"VerifyInterfacesStatus","text":"

Verifies if the provided list of interfaces are all in the expected state.

  • If line protocol status is provided, prioritize checking against both status and line protocol status
  • If line protocol status is not provided and interface status is \u201cup\u201d, expect both status and line protocol to be \u201cup\u201d
  • If interface status is not \u201cup\u201d, check only the interface status without considering line protocol status
Expected Results
  • Success: The test will pass if the provided interfaces are all in the expected state.
  • Failure: The test will fail if any interface is not in the expected state.
Examples
anta.tests.interfaces:\n  - VerifyInterfacesStatus:\n      interfaces:\n        - name: Ethernet1\n          status: up\n        - name: Port-Channel100\n          status: down\n          line_protocol_status: lowerLayerDown\n        - name: Ethernet49/1\n          status: adminDown\n          line_protocol_status: notPresent\n
Source code in anta/tests/interfaces.py
class VerifyInterfacesStatus(AntaTest):\n    \"\"\"Verifies if the provided list of interfaces are all in the expected state.\n\n    - If line protocol status is provided, prioritize checking against both status and line protocol status\n    - If line protocol status is not provided and interface status is \"up\", expect both status and line protocol to be \"up\"\n    - If interface status is not \"up\", check only the interface status without considering line protocol status\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided interfaces are all in the expected state.\n    * Failure: The test will fail if any interface is not in the expected state.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfacesStatus:\n          interfaces:\n            - name: Ethernet1\n              status: up\n            - name: Port-Channel100\n              status: down\n              line_protocol_status: lowerLayerDown\n            - name: Ethernet49/1\n              status: adminDown\n              line_protocol_status: notPresent\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfacesStatus\"\n    description = \"Verifies the status of the provided interfaces.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces description\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyInterfacesStatus test.\"\"\"\n\n        interfaces: list[InterfaceState]\n        \"\"\"List of interfaces with their expected state.\"\"\"\n\n        class InterfaceState(BaseModel):\n            \"\"\"Model for an interface state.\"\"\"\n\n            name: Interface\n            \"\"\"Interface to validate.\"\"\"\n            status: Literal[\"up\", \"down\", \"adminDown\"]\n            \"\"\"Expected status of the interface.\"\"\"\n            line_protocol_status: Literal[\"up\", \"down\", \"testing\", \"unknown\", \"dormant\", \"notPresent\", \"lowerLayerDown\"] | None = None\n            \"\"\"Expected line protocol status of the interface.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfacesStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        self.result.is_success()\n\n        intf_not_configured = []\n        intf_wrong_state = []\n\n        for interface in self.inputs.interfaces:\n            if (intf_status := get_value(command_output[\"interfaceDescriptions\"], interface.name, separator=\"..\")) is None:\n                intf_not_configured.append(interface.name)\n                continue\n\n            status = \"up\" if intf_status[\"interfaceStatus\"] in {\"up\", \"connected\"} else intf_status[\"interfaceStatus\"]\n            proto = \"up\" if intf_status[\"lineProtocolStatus\"] in {\"up\", \"connected\"} else intf_status[\"lineProtocolStatus\"]\n\n            # If line protocol status is provided, prioritize checking against both status and line protocol status\n            if interface.line_protocol_status:\n                if interface.status != status or interface.line_protocol_status != proto:\n                    intf_wrong_state.append(f\"{interface.name} is {status}/{proto}\")\n\n            # If line protocol status is not provided and interface status is \"up\", expect both status and proto to be \"up\"\n            # If interface status is not \"up\", check only the interface status without considering line protocol status\n            elif (interface.status == \"up\" and (status != \"up\" or proto != \"up\")) or (interface.status != status):\n                intf_wrong_state.append(f\"{interface.name} is {status}/{proto}\")\n\n        if intf_not_configured:\n            self.result.is_failure(f\"The following interface(s) are not configured: {intf_not_configured}\")\n\n        if intf_wrong_state:\n            self.result.is_failure(f\"The following interface(s) are not in the expected state: {intf_wrong_state}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfacesStatus-attributes","title":"Inputs","text":"Name Type Description Default interfaces list[InterfaceState] List of interfaces with their expected state. -"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfacesStatus-attributes","title":"InterfaceState","text":"Name Type Description Default name Interface Interface to validate. - status Literal['up', 'down', 'adminDown'] Expected status of the interface. - line_protocol_status Literal['up', 'down', 'testing', 'unknown', 'dormant', 'notPresent', 'lowerLayerDown'] | None Expected line protocol status of the interface. None"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyIpVirtualRouterMac","title":"VerifyIpVirtualRouterMac","text":"

Verifies the IP virtual router MAC address.

Expected Results
  • Success: The test will pass if the IP virtual router MAC address matches the input.
  • Failure: The test will fail if the IP virtual router MAC address does not match the input.
Examples
anta.tests.interfaces:\n  - VerifyIpVirtualRouterMac:\n      mac_address: 00:1c:73:00:dc:01\n
Source code in anta/tests/interfaces.py
class VerifyIpVirtualRouterMac(AntaTest):\n    \"\"\"Verifies the IP virtual router MAC address.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the IP virtual router MAC address matches the input.\n    * Failure: The test will fail if the IP virtual router MAC address does not match the input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyIpVirtualRouterMac:\n          mac_address: 00:1c:73:00:dc:01\n    ```\n    \"\"\"\n\n    name = \"VerifyIpVirtualRouterMac\"\n    description = \"Verifies the IP virtual router MAC address.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip virtual-router\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyIpVirtualRouterMac test.\"\"\"\n\n        mac_address: MacAddress\n        \"\"\"IP virtual router MAC address.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIpVirtualRouterMac.\"\"\"\n        command_output = self.instance_commands[0].json_output[\"virtualMacs\"]\n        mac_address_found = get_item(command_output, \"macAddress\", self.inputs.mac_address)\n\n        if mac_address_found is None:\n            self.result.is_failure(f\"IP virtual router MAC address `{self.inputs.mac_address}` is not configured.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyIpVirtualRouterMac-attributes","title":"Inputs","text":"Name Type Description Default mac_address MacAddress IP virtual router MAC address. -"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyL2MTU","title":"VerifyL2MTU","text":"

Verifies the global layer 2 Maximum Transfer Unit (MTU) for all L2 interfaces.

Test that L2 interfaces are configured with the correct MTU. It supports Ethernet, Port Channel and VLAN interfaces. You can define a global MTU to check and also an MTU per interface and also ignored some interfaces.

Expected Results
  • Success: The test will pass if all layer 2 interfaces have the proper MTU configured.
  • Failure: The test will fail if one or many layer 2 interfaces have the wrong MTU configured.
Examples
anta.tests.interfaces:\n  - VerifyL2MTU:\n      mtu: 1500\n      ignored_interfaces:\n        - Management1\n        - Vxlan1\n      specific_mtu:\n        - Ethernet1/1: 1500\n
Source code in anta/tests/interfaces.py
class VerifyL2MTU(AntaTest):\n    \"\"\"Verifies the global layer 2 Maximum Transfer Unit (MTU) for all L2 interfaces.\n\n    Test that L2 interfaces are configured with the correct MTU. It supports Ethernet, Port Channel and VLAN interfaces.\n    You can define a global MTU to check and also an MTU per interface and also ignored some interfaces.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all layer 2 interfaces have the proper MTU configured.\n    * Failure: The test will fail if one or many layer 2 interfaces have the wrong MTU configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyL2MTU:\n          mtu: 1500\n          ignored_interfaces:\n            - Management1\n            - Vxlan1\n          specific_mtu:\n            - Ethernet1/1: 1500\n    ```\n    \"\"\"\n\n    name = \"VerifyL2MTU\"\n    description = \"Verifies the global L2 MTU of all L2 interfaces.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyL2MTU test.\"\"\"\n\n        mtu: int = 9214\n        \"\"\"Default MTU we should have configured on all non-excluded interfaces. Defaults to 9214.\"\"\"\n        ignored_interfaces: list[str] = Field(default=[\"Management\", \"Loopback\", \"Vxlan\", \"Tunnel\"])\n        \"\"\"A list of L2 interfaces to ignore. Defaults to [\"Management\", \"Loopback\", \"Vxlan\", \"Tunnel\"]\"\"\"\n        specific_mtu: list[dict[str, int]] = Field(default=[])\n        \"\"\"A list of dictionary of L2 interfaces with their specific MTU configured\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyL2MTU.\"\"\"\n        # Parameter to save incorrect interface settings\n        wrong_l2mtu_intf: list[dict[str, int]] = []\n        command_output = self.instance_commands[0].json_output\n        # Set list of interfaces with specific settings\n        specific_interfaces: list[str] = []\n        if self.inputs.specific_mtu:\n            for d in self.inputs.specific_mtu:\n                specific_interfaces.extend(d)\n        for interface, values in command_output[\"interfaces\"].items():\n            catch_interface = re.findall(r\"^[e,p][a-zA-Z]+[-,a-zA-Z]*\\d+\\/*\\d*\", interface, re.IGNORECASE)\n            if len(catch_interface) and catch_interface[0] not in self.inputs.ignored_interfaces and values[\"forwardingModel\"] == \"bridged\":\n                if interface in specific_interfaces:\n                    wrong_l2mtu_intf.extend({interface: values[\"mtu\"]} for custom_data in self.inputs.specific_mtu if values[\"mtu\"] != custom_data[interface])\n                # Comparison with generic setting\n                elif values[\"mtu\"] != self.inputs.mtu:\n                    wrong_l2mtu_intf.append({interface: values[\"mtu\"]})\n        if wrong_l2mtu_intf:\n            self.result.is_failure(f\"Some L2 interfaces do not have correct MTU configured:\\n{wrong_l2mtu_intf}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyL2MTU-attributes","title":"Inputs","text":"Name Type Description Default mtu int Default MTU we should have configured on all non-excluded interfaces. Defaults to 9214. 9214 ignored_interfaces list[str] A list of L2 interfaces to ignore. Defaults to [\"Management\", \"Loopback\", \"Vxlan\", \"Tunnel\"] Field(default=['Management', 'Loopback', 'Vxlan', 'Tunnel']) specific_mtu list[dict[str, int]] A list of dictionary of L2 interfaces with their specific MTU configured Field(default=[])"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyL3MTU","title":"VerifyL3MTU","text":"

Verifies the global layer 3 Maximum Transfer Unit (MTU) for all L3 interfaces.

Test that L3 interfaces are configured with the correct MTU. It supports Ethernet, Port Channel and VLAN interfaces.

You can define a global MTU to check, or an MTU per interface and you can also ignored some interfaces.

Expected Results
  • Success: The test will pass if all layer 3 interfaces have the proper MTU configured.
  • Failure: The test will fail if one or many layer 3 interfaces have the wrong MTU configured.
Examples
anta.tests.interfaces:\n  - VerifyL3MTU:\n      mtu: 1500\n      ignored_interfaces:\n          - Vxlan1\n      specific_mtu:\n          - Ethernet1: 2500\n
Source code in anta/tests/interfaces.py
class VerifyL3MTU(AntaTest):\n    \"\"\"Verifies the global layer 3 Maximum Transfer Unit (MTU) for all L3 interfaces.\n\n    Test that L3 interfaces are configured with the correct MTU. It supports Ethernet, Port Channel and VLAN interfaces.\n\n    You can define a global MTU to check, or an MTU per interface and you can also ignored some interfaces.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all layer 3 interfaces have the proper MTU configured.\n    * Failure: The test will fail if one or many layer 3 interfaces have the wrong MTU configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyL3MTU:\n          mtu: 1500\n          ignored_interfaces:\n              - Vxlan1\n          specific_mtu:\n              - Ethernet1: 2500\n    ```\n    \"\"\"\n\n    name = \"VerifyL3MTU\"\n    description = \"Verifies the global L3 MTU of all L3 interfaces.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyL3MTU test.\"\"\"\n\n        mtu: int = 1500\n        \"\"\"Default MTU we should have configured on all non-excluded interfaces. Defaults to 1500.\"\"\"\n        ignored_interfaces: list[str] = Field(default=[\"Management\", \"Loopback\", \"Vxlan\", \"Tunnel\"])\n        \"\"\"A list of L3 interfaces to ignore\"\"\"\n        specific_mtu: list[dict[str, int]] = Field(default=[])\n        \"\"\"A list of dictionary of L3 interfaces with their specific MTU configured\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyL3MTU.\"\"\"\n        # Parameter to save incorrect interface settings\n        wrong_l3mtu_intf: list[dict[str, int]] = []\n        command_output = self.instance_commands[0].json_output\n        # Set list of interfaces with specific settings\n        specific_interfaces: list[str] = []\n        if self.inputs.specific_mtu:\n            for d in self.inputs.specific_mtu:\n                specific_interfaces.extend(d)\n        for interface, values in command_output[\"interfaces\"].items():\n            if re.findall(r\"[a-z]+\", interface, re.IGNORECASE)[0] not in self.inputs.ignored_interfaces and values[\"forwardingModel\"] == \"routed\":\n                if interface in specific_interfaces:\n                    wrong_l3mtu_intf.extend({interface: values[\"mtu\"]} for custom_data in self.inputs.specific_mtu if values[\"mtu\"] != custom_data[interface])\n                # Comparison with generic setting\n                elif values[\"mtu\"] != self.inputs.mtu:\n                    wrong_l3mtu_intf.append({interface: values[\"mtu\"]})\n        if wrong_l3mtu_intf:\n            self.result.is_failure(f\"Some interfaces do not have correct MTU configured:\\n{wrong_l3mtu_intf}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyL3MTU-attributes","title":"Inputs","text":"Name Type Description Default mtu int Default MTU we should have configured on all non-excluded interfaces. Defaults to 1500. 1500 ignored_interfaces list[str] A list of L3 interfaces to ignore Field(default=['Management', 'Loopback', 'Vxlan', 'Tunnel']) specific_mtu list[dict[str, int]] A list of dictionary of L3 interfaces with their specific MTU configured Field(default=[])"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyLoopbackCount","title":"VerifyLoopbackCount","text":"

Verifies that the device has the expected number of loopback interfaces and all are operational.

Expected Results
  • Success: The test will pass if the device has the correct number of loopback interfaces and none are down.
  • Failure: The test will fail if the loopback interface count is incorrect or any are non-operational.
Examples
anta.tests.interfaces:\n  - VerifyLoopbackCount:\n      number: 3\n
Source code in anta/tests/interfaces.py
class VerifyLoopbackCount(AntaTest):\n    \"\"\"Verifies that the device has the expected number of loopback interfaces and all are operational.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device has the correct number of loopback interfaces and none are down.\n    * Failure: The test will fail if the loopback interface count is incorrect or any are non-operational.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyLoopbackCount:\n          number: 3\n    ```\n    \"\"\"\n\n    name = \"VerifyLoopbackCount\"\n    description = \"Verifies the number of loopback interfaces and their status.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip interface brief\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyLoopbackCount test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"Number of loopback interfaces expected to be present.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoopbackCount.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        loopback_count = 0\n        down_loopback_interfaces = []\n        for interface in command_output[\"interfaces\"]:\n            interface_dict = command_output[\"interfaces\"][interface]\n            if \"Loopback\" in interface:\n                loopback_count += 1\n                if not (interface_dict[\"lineProtocolStatus\"] == \"up\" and interface_dict[\"interfaceStatus\"] == \"connected\"):\n                    down_loopback_interfaces.append(interface)\n        if loopback_count == self.inputs.number and len(down_loopback_interfaces) == 0:\n            self.result.is_success()\n        else:\n            self.result.is_failure()\n            if loopback_count != self.inputs.number:\n                self.result.is_failure(f\"Found {loopback_count} Loopbacks when expecting {self.inputs.number}\")\n            elif len(down_loopback_interfaces) != 0:  # pragma: no branch\n                self.result.is_failure(f\"The following Loopbacks are not up: {down_loopback_interfaces}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyLoopbackCount-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger Number of loopback interfaces expected to be present. -"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyPortChannels","title":"VerifyPortChannels","text":"

Verifies there are no inactive ports in all port channels.

Expected Results
  • Success: The test will pass if there are no inactive ports in all port channels.
  • Failure: The test will fail if there is at least one inactive port in a port channel.
Examples
anta.tests.interfaces:\n  - VerifyPortChannels:\n
Source code in anta/tests/interfaces.py
class VerifyPortChannels(AntaTest):\n    \"\"\"Verifies there are no inactive ports in all port channels.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are no inactive ports in all port channels.\n    * Failure: The test will fail if there is at least one inactive port in a port channel.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyPortChannels:\n    ```\n    \"\"\"\n\n    name = \"VerifyPortChannels\"\n    description = \"Verifies there are no inactive ports in all port channels.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show port-channel\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPortChannels.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        po_with_inactive_ports: list[dict[str, str]] = []\n        for portchannel, portchannel_dict in command_output[\"portChannels\"].items():\n            if len(portchannel_dict[\"inactivePorts\"]) != 0:\n                po_with_inactive_ports.extend({portchannel: portchannel_dict[\"inactivePorts\"]})\n        if not po_with_inactive_ports:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following port-channels have inactive port(s): {po_with_inactive_ports}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifySVI","title":"VerifySVI","text":"

Verifies the status of all SVIs.

Expected Results
  • Success: The test will pass if all SVIs are up.
  • Failure: The test will fail if one or many SVIs are not up.
Examples
anta.tests.interfaces:\n  - VerifySVI:\n
Source code in anta/tests/interfaces.py
class VerifySVI(AntaTest):\n    \"\"\"Verifies the status of all SVIs.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all SVIs are up.\n    * Failure: The test will fail if one or many SVIs are not up.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifySVI:\n    ```\n    \"\"\"\n\n    name = \"VerifySVI\"\n    description = \"Verifies the status of all SVIs.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip interface brief\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySVI.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        down_svis = []\n        for interface in command_output[\"interfaces\"]:\n            interface_dict = command_output[\"interfaces\"][interface]\n            if \"Vlan\" in interface and not (interface_dict[\"lineProtocolStatus\"] == \"up\" and interface_dict[\"interfaceStatus\"] == \"connected\"):\n                down_svis.append(interface)\n        if len(down_svis) == 0:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following SVIs are not up: {down_svis}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyStormControlDrops","title":"VerifyStormControlDrops","text":"

Verifies there are no interface storm-control drop counters.

Expected Results
  • Success: The test will pass if there are no storm-control drop counters.
  • Failure: The test will fail if there is at least one storm-control drop counter.
Examples
anta.tests.interfaces:\n  - VerifyStormControlDrops:\n
Source code in anta/tests/interfaces.py
class VerifyStormControlDrops(AntaTest):\n    \"\"\"Verifies there are no interface storm-control drop counters.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are no storm-control drop counters.\n    * Failure: The test will fail if there is at least one storm-control drop counter.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyStormControlDrops:\n    ```\n    \"\"\"\n\n    name = \"VerifyStormControlDrops\"\n    description = \"Verifies there are no interface storm-control drop counters.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show storm-control\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyStormControlDrops.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        storm_controlled_interfaces: dict[str, dict[str, Any]] = {}\n        for interface, interface_dict in command_output[\"interfaces\"].items():\n            for traffic_type, traffic_type_dict in interface_dict[\"trafficTypes\"].items():\n                if \"drop\" in traffic_type_dict and traffic_type_dict[\"drop\"] != 0:\n                    storm_controlled_interface_dict = storm_controlled_interfaces.setdefault(interface, {})\n                    storm_controlled_interface_dict.update({traffic_type: traffic_type_dict[\"drop\"]})\n        if not storm_controlled_interfaces:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following interfaces have none 0 storm-control drop counters {storm_controlled_interfaces}\")\n
"},{"location":"api/tests.lanz/","title":"LANZ","text":""},{"location":"api/tests.lanz/#anta.tests.lanz.VerifyLANZ","title":"VerifyLANZ","text":"

Verifies if LANZ (Latency Analyzer) is enabled.

Expected Results
  • Success: The test will pass if LANZ is enabled.
  • Failure: The test will fail if LANZ is disabled.
Examples
anta.tests.lanz:\n  - VerifyLANZ:\n
Source code in anta/tests/lanz.py
class VerifyLANZ(AntaTest):\n    \"\"\"Verifies if LANZ (Latency Analyzer) is enabled.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if LANZ is enabled.\n    * Failure: The test will fail if LANZ is disabled.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.lanz:\n      - VerifyLANZ:\n    ```\n    \"\"\"\n\n    name = \"VerifyLANZ\"\n    description = \"Verifies if LANZ is enabled.\"\n    categories: ClassVar[list[str]] = [\"lanz\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show queue-monitor length status\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLANZ.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        if command_output[\"lanzEnabled\"] is not True:\n            self.result.is_failure(\"LANZ is not enabled\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.logging/","title":"Logging","text":""},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingAccounting","title":"VerifyLoggingAccounting","text":"

Verifies if AAA accounting logs are generated.

Expected Results
  • Success: The test will pass if AAA accounting logs are generated.
  • Failure: The test will fail if AAA accounting logs are NOT generated.
Examples
anta.tests.logging:\n  - VerifyLoggingAccounting:\n
Source code in anta/tests/logging.py
class VerifyLoggingAccounting(AntaTest):\n    \"\"\"Verifies if AAA accounting logs are generated.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if AAA accounting logs are generated.\n    * Failure: The test will fail if AAA accounting logs are NOT generated.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingAccounting:\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingAccounting\"\n    description = \"Verifies if AAA accounting logs are generated.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show aaa accounting logs | tail\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingAccounting.\"\"\"\n        pattern = r\"cmd=show aaa accounting logs\"\n        output = self.instance_commands[0].text_output\n        if re.search(pattern, output):\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"AAA accounting logs are not generated\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingErrors","title":"VerifyLoggingErrors","text":"

Verifies there are no syslog messages with a severity of ERRORS or higher.

Expected Results
  • Success: The test will pass if there are NO syslog messages with a severity of ERRORS or higher.
  • Failure: The test will fail if ERRORS or higher syslog messages are present.
Examples
anta.tests.logging:\n  - VerifyLoggingErrors:\n
Source code in anta/tests/logging.py
class VerifyLoggingErrors(AntaTest):\n    \"\"\"Verifies there are no syslog messages with a severity of ERRORS or higher.\n\n    Expected Results\n    ----------------\n      * Success: The test will pass if there are NO syslog messages with a severity of ERRORS or higher.\n      * Failure: The test will fail if ERRORS or higher syslog messages are present.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingErrors:\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingErrors\"\n    description = \"Verifies there are no syslog messages with a severity of ERRORS or higher.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show logging threshold errors\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingErrors.\"\"\"\n        command_output = self.instance_commands[0].text_output\n\n        if len(command_output) == 0:\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"Device has reported syslog messages with a severity of ERRORS or higher\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingHostname","title":"VerifyLoggingHostname","text":"

Verifies if logs are generated with the device FQDN.

Expected Results
  • Success: The test will pass if logs are generated with the device FQDN.
  • Failure: The test will fail if logs are NOT generated with the device FQDN.
Examples
anta.tests.logging:\n  - VerifyLoggingHostname:\n
Source code in anta/tests/logging.py
class VerifyLoggingHostname(AntaTest):\n    \"\"\"Verifies if logs are generated with the device FQDN.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if logs are generated with the device FQDN.\n    * Failure: The test will fail if logs are NOT generated with the device FQDN.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingHostname:\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingHostname\"\n    description = \"Verifies if logs are generated with the device FQDN.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"show hostname\", revision=1),\n        AntaCommand(command=\"send log level informational message ANTA VerifyLoggingHostname validation\", ofmt=\"text\"),\n        AntaCommand(command=\"show logging informational last 30 seconds | grep ANTA\", ofmt=\"text\", use_cache=False),\n    ]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingHostname.\"\"\"\n        output_hostname = self.instance_commands[0].json_output\n        output_logging = self.instance_commands[2].text_output\n        fqdn = output_hostname[\"fqdn\"]\n        lines = output_logging.strip().split(\"\\n\")[::-1]\n        log_pattern = r\"ANTA VerifyLoggingHostname validation\"\n        last_line_with_pattern = \"\"\n        for line in lines:\n            if re.search(log_pattern, line):\n                last_line_with_pattern = line\n                break\n        if fqdn in last_line_with_pattern:\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"Logs are not generated with the device FQDN\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingHosts","title":"VerifyLoggingHosts","text":"

Verifies logging hosts (syslog servers) for a specified VRF.

Expected Results
  • Success: The test will pass if the provided syslog servers are configured in the specified VRF.
  • Failure: The test will fail if the provided syslog servers are NOT configured in the specified VRF.
Examples
anta.tests.logging:\n  - VerifyLoggingHosts:\n      hosts:\n        - 1.1.1.1\n        - 2.2.2.2\n      vrf: default\n
Source code in anta/tests/logging.py
class VerifyLoggingHosts(AntaTest):\n    \"\"\"Verifies logging hosts (syslog servers) for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided syslog servers are configured in the specified VRF.\n    * Failure: The test will fail if the provided syslog servers are NOT configured in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingHosts:\n          hosts:\n            - 1.1.1.1\n            - 2.2.2.2\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingHosts\"\n    description = \"Verifies logging hosts (syslog servers) for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show logging\", ofmt=\"text\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyLoggingHosts test.\"\"\"\n\n        hosts: list[IPv4Address]\n        \"\"\"List of hosts (syslog servers) IP addresses.\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF to transport log messages. Defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingHosts.\"\"\"\n        output = self.instance_commands[0].text_output\n        not_configured = []\n        for host in self.inputs.hosts:\n            pattern = rf\"Logging to '{host!s}'.*VRF {self.inputs.vrf}\"\n            if not re.search(pattern, _get_logging_states(self.logger, output)):\n                not_configured.append(str(host))\n\n        if not not_configured:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Syslog servers {not_configured} are not configured in VRF {self.inputs.vrf}\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingHosts-attributes","title":"Inputs","text":"Name Type Description Default hosts list[IPv4Address] List of hosts (syslog servers) IP addresses. - vrf str The name of the VRF to transport log messages. Defaults to `default`. 'default'"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingLogsGeneration","title":"VerifyLoggingLogsGeneration","text":"

Verifies if logs are generated.

Expected Results
  • Success: The test will pass if logs are generated.
  • Failure: The test will fail if logs are NOT generated.
Examples
anta.tests.logging:\n  - VerifyLoggingLogsGeneration:\n
Source code in anta/tests/logging.py
class VerifyLoggingLogsGeneration(AntaTest):\n    \"\"\"Verifies if logs are generated.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if logs are generated.\n    * Failure: The test will fail if logs are NOT generated.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingLogsGeneration:\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingLogsGeneration\"\n    description = \"Verifies if logs are generated.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"send log level informational message ANTA VerifyLoggingLogsGeneration validation\", ofmt=\"text\"),\n        AntaCommand(command=\"show logging informational last 30 seconds | grep ANTA\", ofmt=\"text\", use_cache=False),\n    ]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingLogsGeneration.\"\"\"\n        log_pattern = r\"ANTA VerifyLoggingLogsGeneration validation\"\n        output = self.instance_commands[1].text_output\n        lines = output.strip().split(\"\\n\")[::-1]\n        for line in lines:\n            if re.search(log_pattern, line):\n                self.result.is_success()\n                return\n        self.result.is_failure(\"Logs are not generated\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingPersistent","title":"VerifyLoggingPersistent","text":"

Verifies if logging persistent is enabled and logs are saved in flash.

Expected Results
  • Success: The test will pass if logging persistent is enabled and logs are in flash.
  • Failure: The test will fail if logging persistent is disabled or no logs are saved in flash.
Examples
anta.tests.logging:\n  - VerifyLoggingPersistent:\n
Source code in anta/tests/logging.py
class VerifyLoggingPersistent(AntaTest):\n    \"\"\"Verifies if logging persistent is enabled and logs are saved in flash.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if logging persistent is enabled and logs are in flash.\n    * Failure: The test will fail if logging persistent is disabled or no logs are saved in flash.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingPersistent:\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingPersistent\"\n    description = \"Verifies if logging persistent is enabled and logs are saved in flash.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"show logging\", ofmt=\"text\"),\n        AntaCommand(command=\"dir flash:/persist/messages\", ofmt=\"text\"),\n    ]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingPersistent.\"\"\"\n        self.result.is_success()\n        log_output = self.instance_commands[0].text_output\n        dir_flash_output = self.instance_commands[1].text_output\n        if \"Persistent logging: disabled\" in _get_logging_states(self.logger, log_output):\n            self.result.is_failure(\"Persistent logging is disabled\")\n            return\n        pattern = r\"-rw-\\s+(\\d+)\"\n        persist_logs = re.search(pattern, dir_flash_output)\n        if not persist_logs or int(persist_logs.group(1)) == 0:\n            self.result.is_failure(\"No persistent logs are saved in flash\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingSourceIntf","title":"VerifyLoggingSourceIntf","text":"

Verifies logging source-interface for a specified VRF.

Expected Results
  • Success: The test will pass if the provided logging source-interface is configured in the specified VRF.
  • Failure: The test will fail if the provided logging source-interface is NOT configured in the specified VRF.
Examples
anta.tests.logging:\n  - VerifyLoggingSourceIntf:\n      interface: Management0\n      vrf: default\n
Source code in anta/tests/logging.py
class VerifyLoggingSourceIntf(AntaTest):\n    \"\"\"Verifies logging source-interface for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided logging source-interface is configured in the specified VRF.\n    * Failure: The test will fail if the provided logging source-interface is NOT configured in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingSourceIntf:\n          interface: Management0\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingSourceInt\"\n    description = \"Verifies logging source-interface for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show logging\", ofmt=\"text\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyLoggingSourceInt test.\"\"\"\n\n        interface: str\n        \"\"\"Source-interface to use as source IP of log messages.\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF to transport log messages. Defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingSourceInt.\"\"\"\n        output = self.instance_commands[0].text_output\n        pattern = rf\"Logging source-interface '{self.inputs.interface}'.*VRF {self.inputs.vrf}\"\n        if re.search(pattern, _get_logging_states(self.logger, output)):\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Source-interface '{self.inputs.interface}' is not configured in VRF {self.inputs.vrf}\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingSourceIntf-attributes","title":"Inputs","text":"Name Type Description Default interface str Source-interface to use as source IP of log messages. - vrf str The name of the VRF to transport log messages. Defaults to `default`. 'default'"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingTimestamp","title":"VerifyLoggingTimestamp","text":"

Verifies if logs are generated with the appropriate timestamp.

Expected Results
  • Success: The test will pass if logs are generated with the appropriate timestamp.
  • Failure: The test will fail if logs are NOT generated with the appropriate timestamp.
Examples
anta.tests.logging:\n  - VerifyLoggingTimestamp:\n
Source code in anta/tests/logging.py
class VerifyLoggingTimestamp(AntaTest):\n    \"\"\"Verifies if logs are generated with the appropriate timestamp.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if logs are generated with the appropriate timestamp.\n    * Failure: The test will fail if logs are NOT generated with the appropriate timestamp.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingTimestamp:\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingTimestamp\"\n    description = \"Verifies if logs are generated with the riate timestamp.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"send log level informational message ANTA VerifyLoggingTimestamp validation\", ofmt=\"text\"),\n        AntaCommand(command=\"show logging informational last 30 seconds | grep ANTA\", ofmt=\"text\", use_cache=False),\n    ]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingTimestamp.\"\"\"\n        log_pattern = r\"ANTA VerifyLoggingTimestamp validation\"\n        timestamp_pattern = r\"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{6}-\\d{2}:\\d{2}\"\n        output = self.instance_commands[1].text_output\n        lines = output.strip().split(\"\\n\")[::-1]\n        last_line_with_pattern = \"\"\n        for line in lines:\n            if re.search(log_pattern, line):\n                last_line_with_pattern = line\n                break\n        if re.search(timestamp_pattern, last_line_with_pattern):\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"Logs are not generated with the appropriate timestamp format\")\n
"},{"location":"api/tests.logging/#anta.tests.logging._get_logging_states","title":"_get_logging_states","text":"
_get_logging_states(logger: logging.Logger, command_output: str) -> str\n

Parse show logging output and gets operational logging states used in the tests in this module.

Returns:

Type Description str: The operational logging states. Source code in anta/tests/logging.py
def _get_logging_states(logger: logging.Logger, command_output: str) -> str:\n    \"\"\"Parse `show logging` output and gets operational logging states used in the tests in this module.\n\n    Parameters\n    ----------\n        logger: The logger object.\n        command_output: The `show logging` output.\n\n    Returns\n    -------\n        str: The operational logging states.\n\n    \"\"\"\n    log_states = command_output.partition(\"\\n\\nExternal configuration:\")[0]\n    logger.debug(\"Device logging states:\\n%s\", log_states)\n    return log_states\n
"},{"location":"api/tests/","title":"Overview","text":""},{"location":"api/tests/#anta-tests-landing-page","title":"ANTA Tests Landing Page","text":"

This section describes all the available tests provided by the ANTA package.

"},{"location":"api/tests/#available-tests","title":"Available Tests","text":"

Here are the tests that we currently provide:

  • AAA
  • Adaptive Virtual Topology
  • BFD
  • Configuration
  • Connectivity
  • Field Notice
  • GreenT
  • Hardware
  • Interfaces
  • LANZ
  • Logging
  • MLAG
  • Multicast
  • Profiles
  • PTP
  • Router Path Selection
  • Routing Generic
  • Routing BGP
  • Routing OSPF
  • Security
  • Services
  • SNMP
  • Software
  • STP
  • STUN
  • System
  • VLAN
  • VXLAN
"},{"location":"api/tests/#using-the-tests","title":"Using the Tests","text":"

All these tests can be imported in a catalog to be used by the ANTA CLI or in your own framework.

"},{"location":"api/tests.mlag/","title":"MLAG","text":""},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagConfigSanity","title":"VerifyMlagConfigSanity","text":"

Verifies there are no MLAG config-sanity inconsistencies.

Expected Results
  • Success: The test will pass if there are NO MLAG config-sanity inconsistencies.
  • Failure: The test will fail if there are MLAG config-sanity inconsistencies.
  • Skipped: The test will be skipped if MLAG is \u2018disabled\u2019.
  • Error: The test will give an error if \u2018mlagActive\u2019 is not found in the JSON response.
Examples
anta.tests.mlag:\n  - VerifyMlagConfigSanity:\n
Source code in anta/tests/mlag.py
class VerifyMlagConfigSanity(AntaTest):\n    \"\"\"Verifies there are no MLAG config-sanity inconsistencies.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are NO MLAG config-sanity inconsistencies.\n    * Failure: The test will fail if there are MLAG config-sanity inconsistencies.\n    * Skipped: The test will be skipped if MLAG is 'disabled'.\n    * Error: The test will give an error if 'mlagActive' is not found in the JSON response.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.mlag:\n      - VerifyMlagConfigSanity:\n    ```\n    \"\"\"\n\n    name = \"VerifyMlagConfigSanity\"\n    description = \"Verifies there are no MLAG config-sanity inconsistencies.\"\n    categories: ClassVar[list[str]] = [\"mlag\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show mlag config-sanity\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMlagConfigSanity.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if (mlag_status := get_value(command_output, \"mlagActive\")) is None:\n            self.result.is_error(message=\"Incorrect JSON response - 'mlagActive' state was not found\")\n            return\n        if mlag_status is False:\n            self.result.is_skipped(\"MLAG is disabled\")\n            return\n        keys_to_verify = [\"globalConfiguration\", \"interfaceConfiguration\"]\n        verified_output = {key: get_value(command_output, key) for key in keys_to_verify}\n        if not any(verified_output.values()):\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"MLAG config-sanity returned inconsistencies: {verified_output}\")\n
"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagDualPrimary","title":"VerifyMlagDualPrimary","text":"

Verifies the dual-primary detection and its parameters of the MLAG configuration.

Expected Results
  • Success: The test will pass if the dual-primary detection is enabled and its parameters are configured properly.
  • Failure: The test will fail if the dual-primary detection is NOT enabled or its parameters are NOT configured properly.
  • Skipped: The test will be skipped if MLAG is \u2018disabled\u2019.
Examples
anta.tests.mlag:\n  - VerifyMlagDualPrimary:\n      detection_delay: 200\n      errdisabled: True\n      recovery_delay: 60\n      recovery_delay_non_mlag: 0\n
Source code in anta/tests/mlag.py
class VerifyMlagDualPrimary(AntaTest):\n    \"\"\"Verifies the dual-primary detection and its parameters of the MLAG configuration.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the dual-primary detection is enabled and its parameters are configured properly.\n    * Failure: The test will fail if the dual-primary detection is NOT enabled or its parameters are NOT configured properly.\n    * Skipped: The test will be skipped if MLAG is 'disabled'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.mlag:\n      - VerifyMlagDualPrimary:\n          detection_delay: 200\n          errdisabled: True\n          recovery_delay: 60\n          recovery_delay_non_mlag: 0\n    ```\n    \"\"\"\n\n    name = \"VerifyMlagDualPrimary\"\n    description = \"Verifies the MLAG dual-primary detection parameters.\"\n    categories: ClassVar[list[str]] = [\"mlag\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show mlag detail\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyMlagDualPrimary test.\"\"\"\n\n        detection_delay: PositiveInteger\n        \"\"\"Delay detection (seconds).\"\"\"\n        errdisabled: bool = False\n        \"\"\"Errdisabled all interfaces when dual-primary is detected.\"\"\"\n        recovery_delay: PositiveInteger\n        \"\"\"Delay (seconds) after dual-primary detection resolves until non peer-link ports that are part of an MLAG are enabled.\"\"\"\n        recovery_delay_non_mlag: PositiveInteger\n        \"\"\"Delay (seconds) after dual-primary detection resolves until ports that are not part of an MLAG are enabled.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMlagDualPrimary.\"\"\"\n        errdisabled_action = \"errdisableAllInterfaces\" if self.inputs.errdisabled else \"none\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"state\"] == \"disabled\":\n            self.result.is_skipped(\"MLAG is disabled\")\n            return\n        if command_output[\"dualPrimaryDetectionState\"] == \"disabled\":\n            self.result.is_failure(\"Dual-primary detection is disabled\")\n            return\n        keys_to_verify = [\"detail.dualPrimaryDetectionDelay\", \"detail.dualPrimaryAction\", \"dualPrimaryMlagRecoveryDelay\", \"dualPrimaryNonMlagRecoveryDelay\"]\n        verified_output = {key: get_value(command_output, key) for key in keys_to_verify}\n        if (\n            verified_output[\"detail.dualPrimaryDetectionDelay\"] == self.inputs.detection_delay\n            and verified_output[\"detail.dualPrimaryAction\"] == errdisabled_action\n            and verified_output[\"dualPrimaryMlagRecoveryDelay\"] == self.inputs.recovery_delay\n            and verified_output[\"dualPrimaryNonMlagRecoveryDelay\"] == self.inputs.recovery_delay_non_mlag\n        ):\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The dual-primary parameters are not configured properly: {verified_output}\")\n
"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagDualPrimary-attributes","title":"Inputs","text":"Name Type Description Default detection_delay PositiveInteger Delay detection (seconds). - errdisabled bool Errdisabled all interfaces when dual-primary is detected. False recovery_delay PositiveInteger Delay (seconds) after dual-primary detection resolves until non peer-link ports that are part of an MLAG are enabled. - recovery_delay_non_mlag PositiveInteger Delay (seconds) after dual-primary detection resolves until ports that are not part of an MLAG are enabled. -"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagInterfaces","title":"VerifyMlagInterfaces","text":"

Verifies there are no inactive or active-partial MLAG ports.

Expected Results
  • Success: The test will pass if there are NO inactive or active-partial MLAG ports.
  • Failure: The test will fail if there are inactive or active-partial MLAG ports.
  • Skipped: The test will be skipped if MLAG is \u2018disabled\u2019.
Examples
anta.tests.mlag:\n  - VerifyMlagInterfaces:\n
Source code in anta/tests/mlag.py
class VerifyMlagInterfaces(AntaTest):\n    \"\"\"Verifies there are no inactive or active-partial MLAG ports.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are NO inactive or active-partial MLAG ports.\n    * Failure: The test will fail if there are inactive or active-partial MLAG ports.\n    * Skipped: The test will be skipped if MLAG is 'disabled'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.mlag:\n      - VerifyMlagInterfaces:\n    ```\n    \"\"\"\n\n    name = \"VerifyMlagInterfaces\"\n    description = \"Verifies there are no inactive or active-partial MLAG ports.\"\n    categories: ClassVar[list[str]] = [\"mlag\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show mlag\", revision=2)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMlagInterfaces.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"state\"] == \"disabled\":\n            self.result.is_skipped(\"MLAG is disabled\")\n            return\n        if command_output[\"mlagPorts\"][\"Inactive\"] == 0 and command_output[\"mlagPorts\"][\"Active-partial\"] == 0:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"MLAG status is not OK: {command_output['mlagPorts']}\")\n
"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagPrimaryPriority","title":"VerifyMlagPrimaryPriority","text":"

Verify the MLAG (Multi-Chassis Link Aggregation) primary priority.

Expected Results
  • Success: The test will pass if the MLAG state is set as \u2018primary\u2019 and the priority matches the input.
  • Failure: The test will fail if the MLAG state is not \u2018primary\u2019 or the priority doesn\u2019t match the input.
  • Skipped: The test will be skipped if MLAG is \u2018disabled\u2019.
Examples
anta.tests.mlag:\n  - VerifyMlagPrimaryPriority:\n      primary_priority: 3276\n
Source code in anta/tests/mlag.py
class VerifyMlagPrimaryPriority(AntaTest):\n    \"\"\"Verify the MLAG (Multi-Chassis Link Aggregation) primary priority.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the MLAG state is set as 'primary' and the priority matches the input.\n    * Failure: The test will fail if the MLAG state is not 'primary' or the priority doesn't match the input.\n    * Skipped: The test will be skipped if MLAG is 'disabled'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.mlag:\n      - VerifyMlagPrimaryPriority:\n          primary_priority: 3276\n    ```\n    \"\"\"\n\n    name = \"VerifyMlagPrimaryPriority\"\n    description = \"Verifies the configuration of the MLAG primary priority.\"\n    categories: ClassVar[list[str]] = [\"mlag\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show mlag detail\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyMlagPrimaryPriority test.\"\"\"\n\n        primary_priority: MlagPriority\n        \"\"\"The expected MLAG primary priority.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMlagPrimaryPriority.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n        # Skip the test if MLAG is disabled\n        if command_output[\"state\"] == \"disabled\":\n            self.result.is_skipped(\"MLAG is disabled\")\n            return\n\n        mlag_state = get_value(command_output, \"detail.mlagState\")\n        primary_priority = get_value(command_output, \"detail.primaryPriority\")\n\n        # Check MLAG state\n        if mlag_state != \"primary\":\n            self.result.is_failure(\"The device is not set as MLAG primary.\")\n\n        # Check primary priority\n        if primary_priority != self.inputs.primary_priority:\n            self.result.is_failure(\n                f\"The primary priority does not match expected. Expected `{self.inputs.primary_priority}`, but found `{primary_priority}` instead.\",\n            )\n
"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagPrimaryPriority-attributes","title":"Inputs","text":"Name Type Description Default primary_priority MlagPriority The expected MLAG primary priority. -"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagReloadDelay","title":"VerifyMlagReloadDelay","text":"

Verifies the reload-delay parameters of the MLAG configuration.

Expected Results
  • Success: The test will pass if the reload-delay parameters are configured properly.
  • Failure: The test will fail if the reload-delay parameters are NOT configured properly.
  • Skipped: The test will be skipped if MLAG is \u2018disabled\u2019.
Examples
anta.tests.mlag:\n  - VerifyMlagReloadDelay:\n      reload_delay: 300\n      reload_delay_non_mlag: 330\n
Source code in anta/tests/mlag.py
class VerifyMlagReloadDelay(AntaTest):\n    \"\"\"Verifies the reload-delay parameters of the MLAG configuration.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the reload-delay parameters are configured properly.\n    * Failure: The test will fail if the reload-delay parameters are NOT configured properly.\n    * Skipped: The test will be skipped if MLAG is 'disabled'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.mlag:\n      - VerifyMlagReloadDelay:\n          reload_delay: 300\n          reload_delay_non_mlag: 330\n    ```\n    \"\"\"\n\n    name = \"VerifyMlagReloadDelay\"\n    description = \"Verifies the MLAG reload-delay parameters.\"\n    categories: ClassVar[list[str]] = [\"mlag\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show mlag\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyMlagReloadDelay test.\"\"\"\n\n        reload_delay: PositiveInteger\n        \"\"\"Delay (seconds) after reboot until non peer-link ports that are part of an MLAG are enabled.\"\"\"\n        reload_delay_non_mlag: PositiveInteger\n        \"\"\"Delay (seconds) after reboot until ports that are not part of an MLAG are enabled.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMlagReloadDelay.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"state\"] == \"disabled\":\n            self.result.is_skipped(\"MLAG is disabled\")\n            return\n        keys_to_verify = [\"reloadDelay\", \"reloadDelayNonMlag\"]\n        verified_output = {key: get_value(command_output, key) for key in keys_to_verify}\n        if verified_output[\"reloadDelay\"] == self.inputs.reload_delay and verified_output[\"reloadDelayNonMlag\"] == self.inputs.reload_delay_non_mlag:\n            self.result.is_success()\n\n        else:\n            self.result.is_failure(f\"The reload-delay parameters are not configured properly: {verified_output}\")\n
"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagReloadDelay-attributes","title":"Inputs","text":"Name Type Description Default reload_delay PositiveInteger Delay (seconds) after reboot until non peer-link ports that are part of an MLAG are enabled. - reload_delay_non_mlag PositiveInteger Delay (seconds) after reboot until ports that are not part of an MLAG are enabled. -"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagStatus","title":"VerifyMlagStatus","text":"

Verifies the health status of the MLAG configuration.

Expected Results
  • Success: The test will pass if the MLAG state is \u2018active\u2019, negotiation status is \u2018connected\u2019, peer-link status and local interface status are \u2018up\u2019.
  • Failure: The test will fail if the MLAG state is not \u2018active\u2019, negotiation status is not \u2018connected\u2019, peer-link status or local interface status are not \u2018up\u2019.
  • Skipped: The test will be skipped if MLAG is \u2018disabled\u2019.
Examples
anta.tests.mlag:\n  - VerifyMlagStatus:\n
Source code in anta/tests/mlag.py
class VerifyMlagStatus(AntaTest):\n    \"\"\"Verifies the health status of the MLAG configuration.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the MLAG state is 'active', negotiation status is 'connected',\n                   peer-link status and local interface status are 'up'.\n    * Failure: The test will fail if the MLAG state is not 'active', negotiation status is not 'connected',\n                   peer-link status or local interface status are not 'up'.\n    * Skipped: The test will be skipped if MLAG is 'disabled'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.mlag:\n      - VerifyMlagStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifyMlagStatus\"\n    description = \"Verifies the health status of the MLAG configuration.\"\n    categories: ClassVar[list[str]] = [\"mlag\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show mlag\", revision=2)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMlagStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"state\"] == \"disabled\":\n            self.result.is_skipped(\"MLAG is disabled\")\n            return\n        keys_to_verify = [\"state\", \"negStatus\", \"localIntfStatus\", \"peerLinkStatus\"]\n        verified_output = {key: get_value(command_output, key) for key in keys_to_verify}\n        if (\n            verified_output[\"state\"] == \"active\"\n            and verified_output[\"negStatus\"] == \"connected\"\n            and verified_output[\"localIntfStatus\"] == \"up\"\n            and verified_output[\"peerLinkStatus\"] == \"up\"\n        ):\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"MLAG status is not OK: {verified_output}\")\n
"},{"location":"api/tests.multicast/","title":"Multicast","text":""},{"location":"api/tests.multicast/#anta.tests.multicast.VerifyIGMPSnoopingGlobal","title":"VerifyIGMPSnoopingGlobal","text":"

Verifies the IGMP snooping global status.

Expected Results
  • Success: The test will pass if the IGMP snooping global status matches the expected status.
  • Failure: The test will fail if the IGMP snooping global status does not match the expected status.
Examples
anta.tests.multicast:\n  - VerifyIGMPSnoopingGlobal:\n      enabled: True\n
Source code in anta/tests/multicast.py
class VerifyIGMPSnoopingGlobal(AntaTest):\n    \"\"\"Verifies the IGMP snooping global status.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the IGMP snooping global status matches the expected status.\n    * Failure: The test will fail if the IGMP snooping global status does not match the expected status.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.multicast:\n      - VerifyIGMPSnoopingGlobal:\n          enabled: True\n    ```\n    \"\"\"\n\n    name = \"VerifyIGMPSnoopingGlobal\"\n    description = \"Verifies the IGMP snooping global configuration.\"\n    categories: ClassVar[list[str]] = [\"multicast\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip igmp snooping\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyIGMPSnoopingGlobal test.\"\"\"\n\n        enabled: bool\n        \"\"\"Whether global IGMP snopping must be enabled (True) or disabled (False).\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIGMPSnoopingGlobal.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n        igmp_state = command_output[\"igmpSnoopingState\"]\n        if igmp_state != \"enabled\" if self.inputs.enabled else igmp_state != \"disabled\":\n            self.result.is_failure(f\"IGMP state is not valid: {igmp_state}\")\n
"},{"location":"api/tests.multicast/#anta.tests.multicast.VerifyIGMPSnoopingGlobal-attributes","title":"Inputs","text":"Name Type Description Default enabled bool Whether global IGMP snopping must be enabled (True) or disabled (False). -"},{"location":"api/tests.multicast/#anta.tests.multicast.VerifyIGMPSnoopingVlans","title":"VerifyIGMPSnoopingVlans","text":"

Verifies the IGMP snooping status for the provided VLANs.

Expected Results
  • Success: The test will pass if the IGMP snooping status matches the expected status for the provided VLANs.
  • Failure: The test will fail if the IGMP snooping status does not match the expected status for the provided VLANs.
Examples
anta.tests.multicast:\n  - VerifyIGMPSnoopingVlans:\n      vlans:\n        10: False\n        12: False\n
Source code in anta/tests/multicast.py
class VerifyIGMPSnoopingVlans(AntaTest):\n    \"\"\"Verifies the IGMP snooping status for the provided VLANs.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the IGMP snooping status matches the expected status for the provided VLANs.\n    * Failure: The test will fail if the IGMP snooping status does not match the expected status for the provided VLANs.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.multicast:\n      - VerifyIGMPSnoopingVlans:\n          vlans:\n            10: False\n            12: False\n    ```\n    \"\"\"\n\n    name = \"VerifyIGMPSnoopingVlans\"\n    description = \"Verifies the IGMP snooping status for the provided VLANs.\"\n    categories: ClassVar[list[str]] = [\"multicast\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip igmp snooping\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyIGMPSnoopingVlans test.\"\"\"\n\n        vlans: dict[Vlan, bool]\n        \"\"\"Dictionary with VLAN ID and whether IGMP snooping must be enabled (True) or disabled (False).\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIGMPSnoopingVlans.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n        for vlan, enabled in self.inputs.vlans.items():\n            if str(vlan) not in command_output[\"vlans\"]:\n                self.result.is_failure(f\"Supplied vlan {vlan} is not present on the device.\")\n                continue\n\n            igmp_state = command_output[\"vlans\"][str(vlan)][\"igmpSnoopingState\"]\n            if igmp_state != \"enabled\" if enabled else igmp_state != \"disabled\":\n                self.result.is_failure(f\"IGMP state for vlan {vlan} is {igmp_state}\")\n
"},{"location":"api/tests.multicast/#anta.tests.multicast.VerifyIGMPSnoopingVlans-attributes","title":"Inputs","text":"Name Type Description Default vlans dict[Vlan, bool] Dictionary with VLAN ID and whether IGMP snooping must be enabled (True) or disabled (False). -"},{"location":"api/tests.path_selection/","title":"Router Path Selection","text":""},{"location":"api/tests.path_selection/#anta.tests.path_selection.VerifyPathsHealth","title":"VerifyPathsHealth","text":"

Verifies the path and telemetry state of all paths under router path-selection.

The expected states are \u2018IPsec established\u2019, \u2018Resolved\u2019 for path and \u2018active\u2019 for telemetry.

Expected Results
  • Success: The test will pass if all path states under router path-selection are either \u2018IPsec established\u2019 or \u2018Resolved\u2019 and their telemetry state as \u2018active\u2019.
  • Failure: The test will fail if router path-selection is not configured or if any path state is not \u2018IPsec established\u2019 or \u2018Resolved\u2019, or the telemetry state is \u2018inactive\u2019.
Examples
anta.tests.path_selection:\n  - VerifyPathsHealth:\n
Source code in anta/tests/path_selection.py
class VerifyPathsHealth(AntaTest):\n    \"\"\"\n    Verifies the path and telemetry state of all paths under router path-selection.\n\n    The expected states are 'IPsec established', 'Resolved' for path and 'active' for telemetry.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all path states under router path-selection are either 'IPsec established' or 'Resolved'\n               and their telemetry state as 'active'.\n    * Failure: The test will fail if router path-selection is not configured or if any path state is not 'IPsec established' or 'Resolved',\n               or the telemetry state is 'inactive'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.path_selection:\n      - VerifyPathsHealth:\n    ```\n    \"\"\"\n\n    name = \"VerifyPathsHealth\"\n    description = \"Verifies the path and telemetry state of all paths under router path-selection.\"\n    categories: ClassVar[list[str]] = [\"path-selection\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show path-selection paths\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPathsHealth.\"\"\"\n        self.result.is_success()\n\n        command_output = self.instance_commands[0].json_output[\"dpsPeers\"]\n\n        # If no paths are configured for router path-selection, the test fails\n        if not command_output:\n            self.result.is_failure(\"No path configured for router path-selection.\")\n            return\n\n        # Check the state of each path\n        for peer, peer_data in command_output.items():\n            for group, group_data in peer_data[\"dpsGroups\"].items():\n                for path_data in group_data[\"dpsPaths\"].values():\n                    path_state = path_data[\"state\"]\n                    session = path_data[\"dpsSessions\"][\"0\"][\"active\"]\n\n                    # If the path state of any path is not 'ipsecEstablished' or 'routeResolved', the test fails\n                    if path_state not in [\"ipsecEstablished\", \"routeResolved\"]:\n                        self.result.is_failure(f\"Path state for peer {peer} in path-group {group} is `{path_state}`.\")\n\n                    # If the telemetry state of any path is inactive, the test fails\n                    elif not session:\n                        self.result.is_failure(f\"Telemetry state for peer {peer} in path-group {group} is `inactive`.\")\n
"},{"location":"api/tests.path_selection/#anta.tests.path_selection.VerifySpecificPath","title":"VerifySpecificPath","text":"

Verifies the path and telemetry state of a specific path for an IPv4 peer under router path-selection.

The expected states are \u2018IPsec established\u2019, \u2018Resolved\u2019 for path and \u2018active\u2019 for telemetry.

Expected Results
  • Success: The test will pass if the path state under router path-selection is either \u2018IPsec established\u2019 or \u2018Resolved\u2019 and telemetry state as \u2018active\u2019.
  • Failure: The test will fail if router path-selection is not configured or if the path state is not \u2018IPsec established\u2019 or \u2018Resolved\u2019, or if the telemetry state is \u2018inactive\u2019.
Examples
anta.tests.path_selection:\n  - VerifySpecificPath:\n      paths:\n        - peer: 10.255.0.1\n          path_group: internet\n          source_address: 100.64.3.2\n          destination_address: 100.64.1.2\n
Source code in anta/tests/path_selection.py
class VerifySpecificPath(AntaTest):\n    \"\"\"\n    Verifies the path and telemetry state of a specific path for an IPv4 peer under router path-selection.\n\n    The expected states are 'IPsec established', 'Resolved' for path and 'active' for telemetry.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the path state under router path-selection is either 'IPsec established' or 'Resolved'\n               and telemetry state as 'active'.\n    * Failure: The test will fail if router path-selection is not configured or if the path state is not 'IPsec established' or 'Resolved',\n               or if the telemetry state is 'inactive'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.path_selection:\n      - VerifySpecificPath:\n          paths:\n            - peer: 10.255.0.1\n              path_group: internet\n              source_address: 100.64.3.2\n              destination_address: 100.64.1.2\n    ```\n    \"\"\"\n\n    name = \"VerifySpecificPath\"\n    description = \"Verifies the path and telemetry state of a specific path under router path-selection.\"\n    categories: ClassVar[list[str]] = [\"path-selection\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaTemplate(template=\"show path-selection paths peer {peer} path-group {group} source {source} destination {destination}\", revision=1)\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySpecificPath test.\"\"\"\n\n        paths: list[RouterPath]\n        \"\"\"List of router paths to verify.\"\"\"\n\n        class RouterPath(BaseModel):\n            \"\"\"Detail of a router path.\"\"\"\n\n            peer: IPv4Address\n            \"\"\"Static peer IPv4 address.\"\"\"\n\n            path_group: str\n            \"\"\"Router path group name.\"\"\"\n\n            source_address: IPv4Address\n            \"\"\"Source IPv4 address of path.\"\"\"\n\n            destination_address: IPv4Address\n            \"\"\"Destination IPv4 address of path.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each router path.\"\"\"\n        return [\n            template.render(peer=path.peer, group=path.path_group, source=path.source_address, destination=path.destination_address) for path in self.inputs.paths\n        ]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySpecificPath.\"\"\"\n        self.result.is_success()\n\n        # Check the state of each path\n        for command in self.instance_commands:\n            peer = command.params.peer\n            path_group = command.params.group\n            source = command.params.source\n            destination = command.params.destination\n            command_output = command.json_output.get(\"dpsPeers\", [])\n\n            # If the peer is not configured for the path group, the test fails\n            if not command_output:\n                self.result.is_failure(f\"Path `peer: {peer} source: {source} destination: {destination}` is not configured for path-group `{path_group}`.\")\n                continue\n\n            # Extract the state of the path\n            path_output = get_value(command_output, f\"{peer}..dpsGroups..{path_group}..dpsPaths\", separator=\"..\")\n            path_state = next(iter(path_output.values())).get(\"state\")\n            session = get_value(next(iter(path_output.values())), \"dpsSessions.0.active\")\n\n            # If the state of the path is not 'ipsecEstablished' or 'routeResolved', or the telemetry state is 'inactive', the test fails\n            if path_state not in [\"ipsecEstablished\", \"routeResolved\"]:\n                self.result.is_failure(f\"Path state for `peer: {peer} source: {source} destination: {destination}` in path-group {path_group} is `{path_state}`.\")\n            elif not session:\n                self.result.is_failure(\n                    f\"Telemetry state for path `peer: {peer} source: {source} destination: {destination}` in path-group {path_group} is `inactive`.\"\n                )\n
"},{"location":"api/tests.path_selection/#anta.tests.path_selection.VerifySpecificPath-attributes","title":"Inputs","text":"Name Type Description Default paths list[RouterPath] List of router paths to verify. -"},{"location":"api/tests.path_selection/#anta.tests.path_selection.VerifySpecificPath-attributes","title":"RouterPath","text":"Name Type Description Default peer IPv4Address Static peer IPv4 address. - path_group str Router path group name. - source_address IPv4Address Source IPv4 address of path. - destination_address IPv4Address Destination IPv4 address of path. -"},{"location":"api/tests.profiles/","title":"Profiles","text":""},{"location":"api/tests.profiles/#anta.tests.profiles.VerifyTcamProfile","title":"VerifyTcamProfile","text":"

Verifies that the device is using the provided Ternary Content-Addressable Memory (TCAM) profile.

Expected Results
  • Success: The test will pass if the provided TCAM profile is actually running on the device.
  • Failure: The test will fail if the provided TCAM profile is not running on the device.
Examples
anta.tests.profiles:\n  - VerifyTcamProfile:\n      profile: vxlan-routing\n
Source code in anta/tests/profiles.py
class VerifyTcamProfile(AntaTest):\n    \"\"\"Verifies that the device is using the provided Ternary Content-Addressable Memory (TCAM) profile.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided TCAM profile is actually running on the device.\n    * Failure: The test will fail if the provided TCAM profile is not running on the device.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.profiles:\n      - VerifyTcamProfile:\n          profile: vxlan-routing\n    ```\n    \"\"\"\n\n    name = \"VerifyTcamProfile\"\n    description = \"Verifies the device TCAM profile.\"\n    categories: ClassVar[list[str]] = [\"profiles\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show hardware tcam profile\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyTcamProfile test.\"\"\"\n\n        profile: str\n        \"\"\"Expected TCAM profile.\"\"\"\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTcamProfile.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"pmfProfiles\"][\"FixedSystem\"][\"status\"] == command_output[\"pmfProfiles\"][\"FixedSystem\"][\"config\"] == self.inputs.profile:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Incorrect profile running on device: {command_output['pmfProfiles']['FixedSystem']['status']}\")\n
"},{"location":"api/tests.profiles/#anta.tests.profiles.VerifyTcamProfile-attributes","title":"Inputs","text":"Name Type Description Default profile str Expected TCAM profile. -"},{"location":"api/tests.profiles/#anta.tests.profiles.VerifyUnifiedForwardingTableMode","title":"VerifyUnifiedForwardingTableMode","text":"

Verifies the device is using the expected UFT (Unified Forwarding Table) mode.

Expected Results
  • Success: The test will pass if the device is using the expected UFT mode.
  • Failure: The test will fail if the device is not using the expected UFT mode.
Examples
anta.tests.profiles:\n  - VerifyUnifiedForwardingTableMode:\n      mode: 3\n
Source code in anta/tests/profiles.py
class VerifyUnifiedForwardingTableMode(AntaTest):\n    \"\"\"Verifies the device is using the expected UFT (Unified Forwarding Table) mode.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is using the expected UFT mode.\n    * Failure: The test will fail if the device is not using the expected UFT mode.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.profiles:\n      - VerifyUnifiedForwardingTableMode:\n          mode: 3\n    ```\n    \"\"\"\n\n    name = \"VerifyUnifiedForwardingTableMode\"\n    description = \"Verifies the device is using the expected UFT mode.\"\n    categories: ClassVar[list[str]] = [\"profiles\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show platform trident forwarding-table partition\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyUnifiedForwardingTableMode test.\"\"\"\n\n        mode: Literal[0, 1, 2, 3, 4, \"flexible\"]\n        \"\"\"Expected UFT mode. Valid values are 0, 1, 2, 3, 4, or \"flexible\".\"\"\"\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyUnifiedForwardingTableMode.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"uftMode\"] == str(self.inputs.mode):\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device is not running correct UFT mode (expected: {self.inputs.mode} / running: {command_output['uftMode']})\")\n
"},{"location":"api/tests.profiles/#anta.tests.profiles.VerifyUnifiedForwardingTableMode-attributes","title":"Inputs","text":"Name Type Description Default mode Literal[0, 1, 2, 3, 4, 'flexible'] Expected UFT mode. Valid values are 0, 1, 2, 3, 4, or \"flexible\". -"},{"location":"api/tests.ptp/","title":"PTP","text":""},{"location":"api/tests.ptp/#anta.tests.ptp.VerifyPtpGMStatus","title":"VerifyPtpGMStatus","text":"

Verifies that the device is locked to a valid Precision Time Protocol (PTP) Grandmaster (GM).

To test PTP failover, re-run the test with a secondary GMID configured.

Expected Results
  • Success: The test will pass if the device is locked to the provided Grandmaster.
  • Failure: The test will fail if the device is not locked to the provided Grandmaster.
  • Skipped: The test will be skipped if PTP is not configured on the device.
Examples
anta.tests.ptp:\n  - VerifyPtpGMStatus:\n      gmid: 0xec:46:70:ff:fe:00:ff:a9\n
Source code in anta/tests/ptp.py
class VerifyPtpGMStatus(AntaTest):\n    \"\"\"Verifies that the device is locked to a valid Precision Time Protocol (PTP) Grandmaster (GM).\n\n    To test PTP failover, re-run the test with a secondary GMID configured.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is locked to the provided Grandmaster.\n    * Failure: The test will fail if the device is not locked to the provided Grandmaster.\n    * Skipped: The test will be skipped if PTP is not configured on the device.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.ptp:\n      - VerifyPtpGMStatus:\n          gmid: 0xec:46:70:ff:fe:00:ff:a9\n    ```\n    \"\"\"\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyPtpGMStatus test.\"\"\"\n\n        gmid: str\n        \"\"\"Identifier of the Grandmaster to which the device should be locked.\"\"\"\n\n    name = \"VerifyPtpGMStatus\"\n    description = \"Verifies that the device is locked to a valid PTP Grandmaster.\"\n    categories: ClassVar[list[str]] = [\"ptp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ptp\", revision=2)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPtpGMStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        if (ptp_clock_summary := command_output.get(\"ptpClockSummary\")) is None:\n            self.result.is_skipped(\"PTP is not configured\")\n            return\n\n        if ptp_clock_summary[\"gmClockIdentity\"] != self.inputs.gmid:\n            self.result.is_failure(\n                f\"The device is locked to the following Grandmaster: '{ptp_clock_summary['gmClockIdentity']}', which differ from the expected one.\",\n            )\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.ptp/#anta.tests.ptp.VerifyPtpGMStatus-attributes","title":"Inputs","text":"Name Type Description Default gmid str Identifier of the Grandmaster to which the device should be locked. -"},{"location":"api/tests.ptp/#anta.tests.ptp.VerifyPtpLockStatus","title":"VerifyPtpLockStatus","text":"

Verifies that the device was locked to the upstream Precision Time Protocol (PTP) Grandmaster (GM) in the last minute.

Expected Results
  • Success: The test will pass if the device was locked to the upstream GM in the last minute.
  • Failure: The test will fail if the device was not locked to the upstream GM in the last minute.
  • Skipped: The test will be skipped if PTP is not configured on the device.
Examples
anta.tests.ptp:\n  - VerifyPtpLockStatus:\n
Source code in anta/tests/ptp.py
class VerifyPtpLockStatus(AntaTest):\n    \"\"\"Verifies that the device was locked to the upstream Precision Time Protocol (PTP) Grandmaster (GM) in the last minute.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device was locked to the upstream GM in the last minute.\n    * Failure: The test will fail if the device was not locked to the upstream GM in the last minute.\n    * Skipped: The test will be skipped if PTP is not configured on the device.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.ptp:\n      - VerifyPtpLockStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifyPtpLockStatus\"\n    description = \"Verifies that the device was locked to the upstream PTP GM in the last minute.\"\n    categories: ClassVar[list[str]] = [\"ptp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ptp\", revision=2)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPtpLockStatus.\"\"\"\n        threshold = 60\n        command_output = self.instance_commands[0].json_output\n\n        if (ptp_clock_summary := command_output.get(\"ptpClockSummary\")) is None:\n            self.result.is_skipped(\"PTP is not configured\")\n            return\n\n        time_difference = ptp_clock_summary[\"currentPtpSystemTime\"] - ptp_clock_summary[\"lastSyncTime\"]\n\n        if time_difference >= threshold:\n            self.result.is_failure(f\"The device lock is more than {threshold}s old: {time_difference}s\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.ptp/#anta.tests.ptp.VerifyPtpModeStatus","title":"VerifyPtpModeStatus","text":"

Verifies that the device is configured as a Precision Time Protocol (PTP) Boundary Clock (BC).

Expected Results
  • Success: The test will pass if the device is a BC.
  • Failure: The test will fail if the device is not a BC.
  • Skipped: The test will be skipped if PTP is not configured on the device.
Examples
anta.tests.ptp:\n  - VerifyPtpModeStatus:\n
Source code in anta/tests/ptp.py
class VerifyPtpModeStatus(AntaTest):\n    \"\"\"Verifies that the device is configured as a Precision Time Protocol (PTP) Boundary Clock (BC).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is a BC.\n    * Failure: The test will fail if the device is not a BC.\n    * Skipped: The test will be skipped if PTP is not configured on the device.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.ptp:\n      - VerifyPtpModeStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifyPtpModeStatus\"\n    description = \"Verifies that the device is configured as a PTP Boundary Clock.\"\n    categories: ClassVar[list[str]] = [\"ptp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ptp\", revision=2)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPtpModeStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        if (ptp_mode := command_output.get(\"ptpMode\")) is None:\n            self.result.is_skipped(\"PTP is not configured\")\n            return\n\n        if ptp_mode != \"ptpBoundaryClock\":\n            self.result.is_failure(f\"The device is not configured as a PTP Boundary Clock: '{ptp_mode}'\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.ptp/#anta.tests.ptp.VerifyPtpOffset","title":"VerifyPtpOffset","text":"

Verifies that the Precision Time Protocol (PTP) timing offset is within \u00b1 1000ns from the master clock.

Expected Results
  • Success: The test will pass if the PTP timing offset is within \u00b1 1000ns from the master clock.
  • Failure: The test will fail if the PTP timing offset is greater than \u00b1 1000ns from the master clock.
  • Skipped: The test will be skipped if PTP is not configured on the device.
Examples
anta.tests.ptp:\n  - VerifyPtpOffset:\n
Source code in anta/tests/ptp.py
class VerifyPtpOffset(AntaTest):\n    \"\"\"Verifies that the Precision Time Protocol (PTP) timing offset is within +/- 1000ns from the master clock.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the PTP timing offset is within +/- 1000ns from the master clock.\n    * Failure: The test will fail if the PTP timing offset is greater than +/- 1000ns from the master clock.\n    * Skipped: The test will be skipped if PTP is not configured on the device.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.ptp:\n      - VerifyPtpOffset:\n    ```\n    \"\"\"\n\n    name = \"VerifyPtpOffset\"\n    description = \"Verifies that the PTP timing offset is within +/- 1000ns from the master clock.\"\n    categories: ClassVar[list[str]] = [\"ptp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ptp monitor\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPtpOffset.\"\"\"\n        threshold = 1000\n        offset_interfaces: dict[str, list[int]] = {}\n        command_output = self.instance_commands[0].json_output\n\n        if not command_output[\"ptpMonitorData\"]:\n            self.result.is_skipped(\"PTP is not configured\")\n            return\n\n        for interface in command_output[\"ptpMonitorData\"]:\n            if abs(interface[\"offsetFromMaster\"]) > threshold:\n                offset_interfaces.setdefault(interface[\"intf\"], []).append(interface[\"offsetFromMaster\"])\n\n        if offset_interfaces:\n            self.result.is_failure(f\"The device timing offset from master is greater than +/- {threshold}ns: {offset_interfaces}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.ptp/#anta.tests.ptp.VerifyPtpPortModeStatus","title":"VerifyPtpPortModeStatus","text":"

Verifies that all interfaces are in a valid Precision Time Protocol (PTP) state.

The interfaces can be in one of the following state: Master, Slave, Passive, or Disabled.

Expected Results
  • Success: The test will pass if all PTP enabled interfaces are in a valid state.
  • Failure: The test will fail if there are no PTP enabled interfaces or if some interfaces are not in a valid state.
Examples
anta.tests.ptp:\n  - VerifyPtpPortModeStatus:\n
Source code in anta/tests/ptp.py
class VerifyPtpPortModeStatus(AntaTest):\n    \"\"\"Verifies that all interfaces are in a valid Precision Time Protocol (PTP) state.\n\n    The interfaces can be in one of the following state: Master, Slave, Passive, or Disabled.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all PTP enabled interfaces are in a valid state.\n    * Failure: The test will fail if there are no PTP enabled interfaces or if some interfaces are not in a valid state.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.ptp:\n      - VerifyPtpPortModeStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifyPtpPortModeStatus\"\n    description = \"Verifies the PTP interfaces state.\"\n    categories: ClassVar[list[str]] = [\"ptp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ptp\", revision=2)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPtpPortModeStatus.\"\"\"\n        valid_state = (\"psMaster\", \"psSlave\", \"psPassive\", \"psDisabled\")\n        command_output = self.instance_commands[0].json_output\n\n        if not command_output[\"ptpIntfSummaries\"]:\n            self.result.is_failure(\"No interfaces are PTP enabled\")\n            return\n\n        invalid_interfaces = [\n            interface\n            for interface in command_output[\"ptpIntfSummaries\"]\n            for vlan in command_output[\"ptpIntfSummaries\"][interface][\"ptpIntfVlanSummaries\"]\n            if vlan[\"portState\"] not in valid_state\n        ]\n\n        if not invalid_interfaces:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following interface(s) are not in a valid PTP state: '{invalid_interfaces}'\")\n
"},{"location":"api/tests.routing.bgp/","title":"BGP","text":""},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPAdvCommunities","title":"VerifyBGPAdvCommunities","text":"

Verifies if the advertised communities of BGP peers are standard, extended, and large in the specified VRF.

Expected Results
  • Success: The test will pass if the advertised communities of BGP peers are standard, extended, and large in the specified VRF.
  • Failure: The test will fail if the advertised communities of BGP peers are not standard, extended, and large in the specified VRF.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPAdvCommunities:\n        bgp_peers:\n          - peer_address: 172.30.11.17\n            vrf: default\n          - peer_address: 172.30.11.21\n            vrf: default\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPAdvCommunities(AntaTest):\n    \"\"\"Verifies if the advertised communities of BGP peers are standard, extended, and large in the specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the advertised communities of BGP peers are standard, extended, and large in the specified VRF.\n    * Failure: The test will fail if the advertised communities of BGP peers are not standard, extended, and large in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPAdvCommunities:\n            bgp_peers:\n              - peer_address: 172.30.11.17\n                vrf: default\n              - peer_address: 172.30.11.21\n                vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPAdvCommunities\"\n    description = \"Verifies the advertised communities of a BGP peer.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bgp neighbors vrf all\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPAdvCommunities test.\"\"\"\n\n        bgp_peers: list[BgpPeer]\n        \"\"\"List of BGP peers.\"\"\"\n\n        class BgpPeer(BaseModel):\n            \"\"\"Model for a BGP peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPAdvCommunities.\"\"\"\n        failures: dict[str, Any] = {\"bgp_peers\": {}}\n\n        # Iterate over each bgp peer\n        for bgp_peer in self.inputs.bgp_peers:\n            peer = str(bgp_peer.peer_address)\n            vrf = bgp_peer.vrf\n            failure: dict[str, dict[str, dict[str, Any]]] = {\"bgp_peers\": {peer: {vrf: {}}}}\n\n            # Verify BGP peer\n            if (\n                not (bgp_output := get_value(self.instance_commands[0].json_output, f\"vrfs.{vrf}.peerList\"))\n                or (bgp_output := get_item(bgp_output, \"peerAddress\", peer)) is None\n            ):\n                failure[\"bgp_peers\"][peer][vrf] = {\"status\": \"Not configured\"}\n                failures = deep_update(failures, failure)\n                continue\n\n            # Verify BGP peer's advertised communities\n            bgp_output = bgp_output.get(\"advertisedCommunities\")\n            if not bgp_output[\"standard\"] or not bgp_output[\"extended\"] or not bgp_output[\"large\"]:\n                failure[\"bgp_peers\"][peer][vrf] = {\"advertised_communities\": bgp_output}\n                failures = deep_update(failures, failure)\n\n        if not failures[\"bgp_peers\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peers are not configured or advertised communities are not standard, extended, and large:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPAdvCommunities-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpPeer] List of BGP peers. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPAdvCommunities-attributes","title":"BgpPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default'"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPExchangedRoutes","title":"VerifyBGPExchangedRoutes","text":"

Verifies if the BGP peers have correctly advertised and received routes.

The route type should be \u2018valid\u2019 and \u2018active\u2019 for a specified VRF.

Expected Results
  • Success: If the BGP peers have correctly advertised and received routes of type \u2018valid\u2019 and \u2018active\u2019 for a specified VRF.
  • Failure: If a BGP peer is not found, the expected advertised/received routes are not found, or the routes are not \u2018valid\u2019 or \u2018active\u2019.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPExchangedRoutes:\n        bgp_peers:\n          - peer_address: 172.30.255.5\n            vrf: default\n            advertised_routes:\n              - 192.0.254.5/32\n            received_routes:\n              - 192.0.255.4/32\n          - peer_address: 172.30.255.1\n            vrf: default\n            advertised_routes:\n              - 192.0.255.1/32\n              - 192.0.254.5/32\n            received_routes:\n              - 192.0.254.3/32\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPExchangedRoutes(AntaTest):\n    \"\"\"Verifies if the BGP peers have correctly advertised and received routes.\n\n    The route type should be 'valid' and 'active' for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: If the BGP peers have correctly advertised and received routes of type 'valid' and 'active' for a specified VRF.\n    * Failure: If a BGP peer is not found, the expected advertised/received routes are not found, or the routes are not 'valid' or 'active'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPExchangedRoutes:\n            bgp_peers:\n              - peer_address: 172.30.255.5\n                vrf: default\n                advertised_routes:\n                  - 192.0.254.5/32\n                received_routes:\n                  - 192.0.255.4/32\n              - peer_address: 172.30.255.1\n                vrf: default\n                advertised_routes:\n                  - 192.0.255.1/32\n                  - 192.0.254.5/32\n                received_routes:\n                  - 192.0.254.3/32\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPExchangedRoutes\"\n    description = \"Verifies the advertised and received routes of BGP peers.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaTemplate(template=\"show bgp neighbors {peer} advertised-routes vrf {vrf}\", revision=3),\n        AntaTemplate(template=\"show bgp neighbors {peer} routes vrf {vrf}\", revision=3),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPExchangedRoutes test.\"\"\"\n\n        bgp_peers: list[BgpNeighbor]\n        \"\"\"List of BGP neighbors.\"\"\"\n\n        class BgpNeighbor(BaseModel):\n            \"\"\"Model for a BGP neighbor.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n            advertised_routes: list[IPv4Network]\n            \"\"\"List of advertised routes in CIDR format.\"\"\"\n            received_routes: list[IPv4Network]\n            \"\"\"List of received routes in CIDR format.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each BGP neighbor in the input list.\"\"\"\n        return [template.render(peer=str(bgp_peer.peer_address), vrf=bgp_peer.vrf) for bgp_peer in self.inputs.bgp_peers]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPExchangedRoutes.\"\"\"\n        failures: dict[str, dict[str, Any]] = {\"bgp_peers\": {}}\n\n        # Iterating over command output for different peers\n        for command in self.instance_commands:\n            peer = command.params.peer\n            vrf = command.params.vrf\n            for input_entry in self.inputs.bgp_peers:\n                if str(input_entry.peer_address) == peer and input_entry.vrf == vrf:\n                    advertised_routes = input_entry.advertised_routes\n                    received_routes = input_entry.received_routes\n                    break\n            failure = {vrf: \"\"}\n\n            # Verify if a BGP peer is configured with the provided vrf\n            if not (bgp_routes := get_value(command.json_output, f\"vrfs.{vrf}.bgpRouteEntries\")):\n                failure[vrf] = \"Not configured\"\n                failures[\"bgp_peers\"][peer] = failure\n                continue\n\n            # Validate advertised routes\n            if \"advertised-routes\" in command.command:\n                failure_routes = _add_bgp_routes_failure(advertised_routes, bgp_routes, peer, vrf)\n\n            # Validate received routes\n            else:\n                failure_routes = _add_bgp_routes_failure(received_routes, bgp_routes, peer, vrf, route_type=\"received_routes\")\n            failures = deep_update(failures, failure_routes)\n\n        if not failures[\"bgp_peers\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peers are not found or routes are not exchanged properly:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPExchangedRoutes-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpNeighbor] List of BGP neighbors. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPExchangedRoutes-attributes","title":"BgpNeighbor","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default' advertised_routes list[IPv4Network] List of advertised routes in CIDR format. - received_routes list[IPv4Network] List of received routes in CIDR format. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerASNCap","title":"VerifyBGPPeerASNCap","text":"

Verifies the four octet asn capabilities of a BGP peer in a specified VRF.

Expected Results
  • Success: The test will pass if BGP peer\u2019s four octet asn capabilities are advertised, received, and enabled in the specified VRF.
  • Failure: The test will fail if BGP peers are not found or four octet asn capabilities are not advertised, received, and enabled in the specified VRF.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPPeerASNCap:\n        bgp_peers:\n          - peer_address: 172.30.11.1\n            vrf: default\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPPeerASNCap(AntaTest):\n    \"\"\"Verifies the four octet asn capabilities of a BGP peer in a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if BGP peer's four octet asn capabilities are advertised, received, and enabled in the specified VRF.\n    * Failure: The test will fail if BGP peers are not found or four octet asn capabilities are not advertised, received, and enabled in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPPeerASNCap:\n            bgp_peers:\n              - peer_address: 172.30.11.1\n                vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPPeerASNCap\"\n    description = \"Verifies the four octet asn capabilities of a BGP peer.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bgp neighbors vrf all\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPPeerASNCap test.\"\"\"\n\n        bgp_peers: list[BgpPeer]\n        \"\"\"List of BGP peers.\"\"\"\n\n        class BgpPeer(BaseModel):\n            \"\"\"Model for a BGP peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPPeerASNCap.\"\"\"\n        failures: dict[str, Any] = {\"bgp_peers\": {}}\n\n        # Iterate over each bgp peer\n        for bgp_peer in self.inputs.bgp_peers:\n            peer = str(bgp_peer.peer_address)\n            vrf = bgp_peer.vrf\n            failure: dict[str, dict[str, dict[str, Any]]] = {\"bgp_peers\": {peer: {vrf: {}}}}\n\n            # Check if BGP output exists\n            if (\n                not (bgp_output := get_value(self.instance_commands[0].json_output, f\"vrfs.{vrf}.peerList\"))\n                or (bgp_output := get_item(bgp_output, \"peerAddress\", peer)) is None\n            ):\n                failure[\"bgp_peers\"][peer][vrf] = {\"status\": \"Not configured\"}\n                failures = deep_update(failures, failure)\n                continue\n\n            bgp_output = get_value(bgp_output, \"neighborCapabilities.fourOctetAsnCap\")\n\n            # Check if  four octet asn capabilities are found\n            if not bgp_output:\n                failure[\"bgp_peers\"][peer][vrf] = {\"fourOctetAsnCap\": \"not found\"}\n                failures = deep_update(failures, failure)\n\n            # Check if capabilities are not advertised, received, or enabled\n            elif not all(bgp_output.get(prop, False) for prop in [\"advertised\", \"received\", \"enabled\"]):\n                failure[\"bgp_peers\"][peer][vrf] = {\"fourOctetAsnCap\": bgp_output}\n                failures = deep_update(failures, failure)\n\n        # Check if there are any failures\n        if not failures[\"bgp_peers\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peer four octet asn capabilities are not found or not ok:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerASNCap-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpPeer] List of BGP peers. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerASNCap-attributes","title":"BgpPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default'"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerCount","title":"VerifyBGPPeerCount","text":"

Verifies the count of BGP peers for a given address family.

It supports multiple types of Address Families Identifiers (AFI) and Subsequent Address Family Identifiers (SAFI).

For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6 (AFI) which is handled automatically in this test.

Please refer to the Input class attributes below for details.

Expected Results
  • Success: If the count of BGP peers matches the expected count for each address family and VRF.
  • Failure: If the count of BGP peers does not match the expected count, or if BGP is not configured for an expected VRF or address family.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPPeerCount:\n        address_families:\n          - afi: \"evpn\"\n            num_peers: 2\n          - afi: \"ipv4\"\n            safi: \"unicast\"\n            vrf: \"PROD\"\n            num_peers: 2\n          - afi: \"ipv4\"\n            safi: \"unicast\"\n            vrf: \"default\"\n            num_peers: 3\n          - afi: \"ipv4\"\n            safi: \"multicast\"\n            vrf: \"DEV\"\n            num_peers: 3\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPPeerCount(AntaTest):\n    \"\"\"Verifies the count of BGP peers for a given address family.\n\n    It supports multiple types of Address Families Identifiers (AFI) and Subsequent Address Family Identifiers (SAFI).\n\n    For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6 (AFI) which is handled automatically in this test.\n\n    Please refer to the Input class attributes below for details.\n\n    Expected Results\n    ----------------\n    * Success: If the count of BGP peers matches the expected count for each address family and VRF.\n    * Failure: If the count of BGP peers does not match the expected count, or if BGP is not configured for an expected VRF or address family.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPPeerCount:\n            address_families:\n              - afi: \"evpn\"\n                num_peers: 2\n              - afi: \"ipv4\"\n                safi: \"unicast\"\n                vrf: \"PROD\"\n                num_peers: 2\n              - afi: \"ipv4\"\n                safi: \"unicast\"\n                vrf: \"default\"\n                num_peers: 3\n              - afi: \"ipv4\"\n                safi: \"multicast\"\n                vrf: \"DEV\"\n                num_peers: 3\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPPeerCount\"\n    description = \"Verifies the count of BGP peers.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaTemplate(template=\"show bgp {afi} {safi} summary vrf {vrf}\", revision=3),\n        AntaTemplate(template=\"show bgp {afi} summary\", revision=3),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPPeerCount test.\"\"\"\n\n        address_families: list[BgpAfi]\n        \"\"\"List of BGP address families (BgpAfi).\"\"\"\n\n        class BgpAfi(BaseModel):\n            \"\"\"Model for a BGP address family (AFI) and subsequent address family (SAFI).\"\"\"\n\n            afi: Afi\n            \"\"\"BGP address family (AFI).\"\"\"\n            safi: Safi | None = None\n            \"\"\"Optional BGP subsequent service family (SAFI).\n\n            If the input `afi` is `ipv4` or `ipv6`, a valid `safi` must be provided.\n            \"\"\"\n            vrf: str = \"default\"\n            \"\"\"\n            Optional VRF for IPv4 and IPv6. If not provided, it defaults to `default`.\n\n            If the input `afi` is not `ipv4` or `ipv6`, e.g. `evpn`, `vrf` must be `default`.\n            \"\"\"\n            num_peers: PositiveInt\n            \"\"\"Number of expected BGP peer(s).\"\"\"\n\n            @model_validator(mode=\"after\")\n            def validate_inputs(self: BaseModel) -> BaseModel:\n                \"\"\"Validate the inputs provided to the BgpAfi class.\n\n                If afi is either ipv4 or ipv6, safi must be provided.\n\n                If afi is not ipv4 or ipv6, safi must not be provided and vrf must be default.\n                \"\"\"\n                if self.afi in [\"ipv4\", \"ipv6\"]:\n                    if self.safi is None:\n                        msg = \"'safi' must be provided when afi is ipv4 or ipv6\"\n                        raise ValueError(msg)\n                elif self.safi is not None:\n                    msg = \"'safi' must not be provided when afi is not ipv4 or ipv6\"\n                    raise ValueError(msg)\n                elif self.vrf != \"default\":\n                    msg = \"'vrf' must be default when afi is not ipv4 or ipv6\"\n                    raise ValueError(msg)\n                return self\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each BGP address family in the input list.\"\"\"\n        commands = []\n        for afi in self.inputs.address_families:\n            if template == VerifyBGPPeerCount.commands[0] and afi.afi in [\"ipv4\", \"ipv6\"] and afi.safi != \"sr-te\":\n                commands.append(template.render(afi=afi.afi, safi=afi.safi, vrf=afi.vrf))\n\n            # For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6\n            elif template == VerifyBGPPeerCount.commands[0] and afi.afi in [\"ipv4\", \"ipv6\"] and afi.safi == \"sr-te\":\n                commands.append(template.render(afi=afi.safi, safi=afi.afi, vrf=afi.vrf))\n            elif template == VerifyBGPPeerCount.commands[1] and afi.afi not in [\"ipv4\", \"ipv6\"]:\n                commands.append(template.render(afi=afi.afi))\n        return commands\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPPeerCount.\"\"\"\n        self.result.is_success()\n\n        failures: dict[tuple[str, Any], dict[str, Any]] = {}\n\n        for command in self.instance_commands:\n            num_peers = None\n            peer_count = 0\n            command_output = command.json_output\n\n            afi = command.params.afi\n            safi = command.params.safi if hasattr(command.params, \"safi\") else None\n            afi_vrf = command.params.vrf if hasattr(command.params, \"vrf\") else \"default\"\n\n            # Swapping AFI and SAFI in case of SR-TE\n            if afi == \"sr-te\":\n                afi, safi = safi, afi\n\n            for input_entry in self.inputs.address_families:\n                if input_entry.afi == afi and input_entry.safi == safi and input_entry.vrf == afi_vrf:\n                    num_peers = input_entry.num_peers\n                    break\n\n            if not (vrfs := command_output.get(\"vrfs\")):\n                _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=afi_vrf, issue=\"Not Configured\")\n                continue\n\n            if afi_vrf == \"all\":\n                for vrf_data in vrfs.values():\n                    peer_count += len(vrf_data[\"peers\"])\n            else:\n                peer_count += len(command_output[\"vrfs\"][afi_vrf][\"peers\"])\n\n            if peer_count != num_peers:\n                _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=afi_vrf, issue=f\"Expected: {num_peers}, Actual: {peer_count}\")\n\n        if failures:\n            self.result.is_failure(f\"Failures: {list(failures.values())}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerCount-attributes","title":"Inputs","text":"Name Type Description Default address_families list[BgpAfi] List of BGP address families (BgpAfi). -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerCount-attributes","title":"BgpAfi","text":"Name Type Description Default afi Afi BGP address family (AFI). - safi Safi | None Optional BGP subsequent service family (SAFI). If the input `afi` is `ipv4` or `ipv6`, a valid `safi` must be provided. None vrf str Optional VRF for IPv4 and IPv6. If not provided, it defaults to `default`. If the input `afi` is not `ipv4` or `ipv6`, e.g. `evpn`, `vrf` must be `default`. 'default' num_peers PositiveInt Number of expected BGP peer(s). -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerMD5Auth","title":"VerifyBGPPeerMD5Auth","text":"

Verifies the MD5 authentication and state of IPv4 BGP peers in a specified VRF.

Expected Results
  • Success: The test will pass if IPv4 BGP peers are configured with MD5 authentication and state as established in the specified VRF.
  • Failure: The test will fail if IPv4 BGP peers are not found, state is not as established or MD5 authentication is not enabled in the specified VRF.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPPeerMD5Auth:\n        bgp_peers:\n          - peer_address: 172.30.11.1\n            vrf: default\n          - peer_address: 172.30.11.5\n            vrf: default\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPPeerMD5Auth(AntaTest):\n    \"\"\"Verifies the MD5 authentication and state of IPv4 BGP peers in a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if IPv4 BGP peers are configured with MD5 authentication and state as established in the specified VRF.\n    * Failure: The test will fail if IPv4 BGP peers are not found, state is not as established or MD5 authentication is not enabled in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPPeerMD5Auth:\n            bgp_peers:\n              - peer_address: 172.30.11.1\n                vrf: default\n              - peer_address: 172.30.11.5\n                vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPPeerMD5Auth\"\n    description = \"Verifies the MD5 authentication and state of a BGP peer.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bgp neighbors vrf all\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPPeerMD5Auth test.\"\"\"\n\n        bgp_peers: list[BgpPeer]\n        \"\"\"List of IPv4 BGP peers.\"\"\"\n\n        class BgpPeer(BaseModel):\n            \"\"\"Model for a BGP peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPPeerMD5Auth.\"\"\"\n        failures: dict[str, Any] = {\"bgp_peers\": {}}\n\n        # Iterate over each command\n        for bgp_peer in self.inputs.bgp_peers:\n            peer = str(bgp_peer.peer_address)\n            vrf = bgp_peer.vrf\n            failure: dict[str, dict[str, dict[str, Any]]] = {\"bgp_peers\": {peer: {vrf: {}}}}\n\n            # Check if BGP output exists\n            if (\n                not (bgp_output := get_value(self.instance_commands[0].json_output, f\"vrfs.{vrf}.peerList\"))\n                or (bgp_output := get_item(bgp_output, \"peerAddress\", peer)) is None\n            ):\n                failure[\"bgp_peers\"][peer][vrf] = {\"status\": \"Not configured\"}\n                failures = deep_update(failures, failure)\n                continue\n\n            # Check if BGP peer state and authentication\n            state = bgp_output.get(\"state\")\n            md5_auth_enabled = bgp_output.get(\"md5AuthEnabled\")\n            if state != \"Established\" or not md5_auth_enabled:\n                failure[\"bgp_peers\"][peer][vrf] = {\"state\": state, \"md5_auth_enabled\": md5_auth_enabled}\n                failures = deep_update(failures, failure)\n\n        # Check if there are any failures\n        if not failures[\"bgp_peers\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peers are not configured, not established or MD5 authentication is not enabled:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerMD5Auth-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpPeer] List of IPv4 BGP peers. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerMD5Auth-attributes","title":"BgpPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default'"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerMPCaps","title":"VerifyBGPPeerMPCaps","text":"

Verifies the multiprotocol capabilities of a BGP peer in a specified VRF.

Expected Results
  • Success: The test will pass if the BGP peer\u2019s multiprotocol capabilities are advertised, received, and enabled in the specified VRF.
  • Failure: The test will fail if BGP peers are not found or multiprotocol capabilities are not advertised, received, and enabled in the specified VRF.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPPeerMPCaps:\n        bgp_peers:\n          - peer_address: 172.30.11.1\n            vrf: default\n            capabilities:\n              - ipv4Unicast\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPPeerMPCaps(AntaTest):\n    \"\"\"Verifies the multiprotocol capabilities of a BGP peer in a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the BGP peer's multiprotocol capabilities are advertised, received, and enabled in the specified VRF.\n    * Failure: The test will fail if BGP peers are not found or multiprotocol capabilities are not advertised, received, and enabled in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPPeerMPCaps:\n            bgp_peers:\n              - peer_address: 172.30.11.1\n                vrf: default\n                capabilities:\n                  - ipv4Unicast\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPPeerMPCaps\"\n    description = \"Verifies the multiprotocol capabilities of a BGP peer.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bgp neighbors vrf all\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPPeerMPCaps test.\"\"\"\n\n        bgp_peers: list[BgpPeer]\n        \"\"\"List of BGP peers\"\"\"\n\n        class BgpPeer(BaseModel):\n            \"\"\"Model for a BGP peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n            capabilities: list[MultiProtocolCaps]\n            \"\"\"List of multiprotocol capabilities to be verified.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPPeerMPCaps.\"\"\"\n        failures: dict[str, Any] = {\"bgp_peers\": {}}\n\n        # Iterate over each bgp peer\n        for bgp_peer in self.inputs.bgp_peers:\n            peer = str(bgp_peer.peer_address)\n            vrf = bgp_peer.vrf\n            capabilities = bgp_peer.capabilities\n            failure: dict[str, dict[str, dict[str, Any]]] = {\"bgp_peers\": {peer: {vrf: {}}}}\n\n            # Check if BGP output exists\n            if (\n                not (bgp_output := get_value(self.instance_commands[0].json_output, f\"vrfs.{vrf}.peerList\"))\n                or (bgp_output := get_item(bgp_output, \"peerAddress\", peer)) is None\n            ):\n                failure[\"bgp_peers\"][peer][vrf] = {\"status\": \"Not configured\"}\n                failures = deep_update(failures, failure)\n                continue\n\n            # Check each capability\n            bgp_output = get_value(bgp_output, \"neighborCapabilities.multiprotocolCaps\")\n            for capability in capabilities:\n                capability_output = bgp_output.get(capability)\n\n                # Check if capabilities are missing\n                if not capability_output:\n                    failure[\"bgp_peers\"][peer][vrf][capability] = \"not found\"\n                    failures = deep_update(failures, failure)\n\n                # Check if capabilities are not advertised, received, or enabled\n                elif not all(capability_output.get(prop, False) for prop in [\"advertised\", \"received\", \"enabled\"]):\n                    failure[\"bgp_peers\"][peer][vrf][capability] = capability_output\n                    failures = deep_update(failures, failure)\n\n        # Check if there are any failures\n        if not failures[\"bgp_peers\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peer multiprotocol capabilities are not found or not ok:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerMPCaps-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpPeer] List of BGP peers -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerMPCaps-attributes","title":"BgpPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default' capabilities list[MultiProtocolCaps] List of multiprotocol capabilities to be verified. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerRouteRefreshCap","title":"VerifyBGPPeerRouteRefreshCap","text":"

Verifies the route refresh capabilities of a BGP peer in a specified VRF.

Expected Results
  • Success: The test will pass if the BGP peer\u2019s route refresh capabilities are advertised, received, and enabled in the specified VRF.
  • Failure: The test will fail if BGP peers are not found or route refresh capabilities are not advertised, received, and enabled in the specified VRF.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPPeerRouteRefreshCap:\n        bgp_peers:\n          - peer_address: 172.30.11.1\n            vrf: default\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPPeerRouteRefreshCap(AntaTest):\n    \"\"\"Verifies the route refresh capabilities of a BGP peer in a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the BGP peer's route refresh capabilities are advertised, received, and enabled in the specified VRF.\n    * Failure: The test will fail if BGP peers are not found or route refresh capabilities are not advertised, received, and enabled in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPPeerRouteRefreshCap:\n            bgp_peers:\n              - peer_address: 172.30.11.1\n                vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPPeerRouteRefreshCap\"\n    description = \"Verifies the route refresh capabilities of a BGP peer.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bgp neighbors vrf all\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPPeerRouteRefreshCap test.\"\"\"\n\n        bgp_peers: list[BgpPeer]\n        \"\"\"List of BGP peers\"\"\"\n\n        class BgpPeer(BaseModel):\n            \"\"\"Model for a BGP peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPPeerRouteRefreshCap.\"\"\"\n        failures: dict[str, Any] = {\"bgp_peers\": {}}\n\n        # Iterate over each bgp peer\n        for bgp_peer in self.inputs.bgp_peers:\n            peer = str(bgp_peer.peer_address)\n            vrf = bgp_peer.vrf\n            failure: dict[str, dict[str, dict[str, Any]]] = {\"bgp_peers\": {peer: {vrf: {}}}}\n\n            # Check if BGP output exists\n            if (\n                not (bgp_output := get_value(self.instance_commands[0].json_output, f\"vrfs.{vrf}.peerList\"))\n                or (bgp_output := get_item(bgp_output, \"peerAddress\", peer)) is None\n            ):\n                failure[\"bgp_peers\"][peer][vrf] = {\"status\": \"Not configured\"}\n                failures = deep_update(failures, failure)\n                continue\n\n            bgp_output = get_value(bgp_output, \"neighborCapabilities.routeRefreshCap\")\n\n            # Check if route refresh capabilities are found\n            if not bgp_output:\n                failure[\"bgp_peers\"][peer][vrf] = {\"routeRefreshCap\": \"not found\"}\n                failures = deep_update(failures, failure)\n\n            # Check if capabilities are not advertised, received, or enabled\n            elif not all(bgp_output.get(prop, False) for prop in [\"advertised\", \"received\", \"enabled\"]):\n                failure[\"bgp_peers\"][peer][vrf] = {\"routeRefreshCap\": bgp_output}\n                failures = deep_update(failures, failure)\n\n        # Check if there are any failures\n        if not failures[\"bgp_peers\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peer route refresh capabilities are not found or not ok:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerRouteRefreshCap-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpPeer] List of BGP peers -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerRouteRefreshCap-attributes","title":"BgpPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default'"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeersHealth","title":"VerifyBGPPeersHealth","text":"

Verifies the health of BGP peers.

It will validate that all BGP sessions are established and all message queues for these BGP sessions are empty for a given address family.

It supports multiple types of Address Families Identifiers (AFI) and Subsequent Address Family Identifiers (SAFI).

For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6 (AFI) which is handled automatically in this test.

Please refer to the Input class attributes below for details.

Expected Results
  • Success: If all BGP sessions are established and all messages queues are empty for each address family and VRF.
  • Failure: If there are issues with any of the BGP sessions, or if BGP is not configured for an expected VRF or address family.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPPeersHealth:\n        address_families:\n          - afi: \"evpn\"\n          - afi: \"ipv4\"\n            safi: \"unicast\"\n            vrf: \"default\"\n          - afi: \"ipv6\"\n            safi: \"unicast\"\n            vrf: \"DEV\"\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPPeersHealth(AntaTest):\n    \"\"\"Verifies the health of BGP peers.\n\n    It will validate that all BGP sessions are established and all message queues for these BGP sessions are empty for a given address family.\n\n    It supports multiple types of Address Families Identifiers (AFI) and Subsequent Address Family Identifiers (SAFI).\n\n    For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6 (AFI) which is handled automatically in this test.\n\n    Please refer to the Input class attributes below for details.\n\n    Expected Results\n    ----------------\n    * Success: If all BGP sessions are established and all messages queues are empty for each address family and VRF.\n    * Failure: If there are issues with any of the BGP sessions, or if BGP is not configured for an expected VRF or address family.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPPeersHealth:\n            address_families:\n              - afi: \"evpn\"\n              - afi: \"ipv4\"\n                safi: \"unicast\"\n                vrf: \"default\"\n              - afi: \"ipv6\"\n                safi: \"unicast\"\n                vrf: \"DEV\"\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPPeersHealth\"\n    description = \"Verifies the health of BGP peers\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaTemplate(template=\"show bgp {afi} {safi} summary vrf {vrf}\", revision=3),\n        AntaTemplate(template=\"show bgp {afi} summary\", revision=3),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPPeersHealth test.\"\"\"\n\n        address_families: list[BgpAfi]\n        \"\"\"List of BGP address families (BgpAfi).\"\"\"\n\n        class BgpAfi(BaseModel):\n            \"\"\"Model for a BGP address family (AFI) and subsequent address family (SAFI).\"\"\"\n\n            afi: Afi\n            \"\"\"BGP address family (AFI).\"\"\"\n            safi: Safi | None = None\n            \"\"\"Optional BGP subsequent service family (SAFI).\n\n            If the input `afi` is `ipv4` or `ipv6`, a valid `safi` must be provided.\n            \"\"\"\n            vrf: str = \"default\"\n            \"\"\"\n            Optional VRF for IPv4 and IPv6. If not provided, it defaults to `default`.\n\n            If the input `afi` is not `ipv4` or `ipv6`, e.g. `evpn`, `vrf` must be `default`.\n            \"\"\"\n\n            @model_validator(mode=\"after\")\n            def validate_inputs(self: BaseModel) -> BaseModel:\n                \"\"\"Validate the inputs provided to the BgpAfi class.\n\n                If afi is either ipv4 or ipv6, safi must be provided.\n\n                If afi is not ipv4 or ipv6, safi must not be provided and vrf must be default.\n                \"\"\"\n                if self.afi in [\"ipv4\", \"ipv6\"]:\n                    if self.safi is None:\n                        msg = \"'safi' must be provided when afi is ipv4 or ipv6\"\n                        raise ValueError(msg)\n                elif self.safi is not None:\n                    msg = \"'safi' must not be provided when afi is not ipv4 or ipv6\"\n                    raise ValueError(msg)\n                elif self.vrf != \"default\":\n                    msg = \"'vrf' must be default when afi is not ipv4 or ipv6\"\n                    raise ValueError(msg)\n                return self\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each BGP address family in the input list.\"\"\"\n        commands = []\n        for afi in self.inputs.address_families:\n            if template == VerifyBGPPeersHealth.commands[0] and afi.afi in [\"ipv4\", \"ipv6\"] and afi.safi != \"sr-te\":\n                commands.append(template.render(afi=afi.afi, safi=afi.safi, vrf=afi.vrf))\n\n            # For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6\n            elif template == VerifyBGPPeersHealth.commands[0] and afi.afi in [\"ipv4\", \"ipv6\"] and afi.safi == \"sr-te\":\n                commands.append(template.render(afi=afi.safi, safi=afi.afi, vrf=afi.vrf))\n            elif template == VerifyBGPPeersHealth.commands[1] and afi.afi not in [\"ipv4\", \"ipv6\"]:\n                commands.append(template.render(afi=afi.afi))\n        return commands\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPPeersHealth.\"\"\"\n        self.result.is_success()\n\n        failures: dict[tuple[str, Any], dict[str, Any]] = {}\n\n        for command in self.instance_commands:\n            command_output = command.json_output\n\n            afi = command.params.afi\n            safi = command.params.safi if hasattr(command.params, \"safi\") else None\n            afi_vrf = command.params.vrf if hasattr(command.params, \"vrf\") else \"default\"\n\n            # Swapping AFI and SAFI in case of SR-TE\n            if afi == \"sr-te\":\n                afi, safi = safi, afi\n\n            if not (vrfs := command_output.get(\"vrfs\")):\n                _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=afi_vrf, issue=\"Not Configured\")\n                continue\n\n            for vrf, vrf_data in vrfs.items():\n                if not (peers := vrf_data.get(\"peers\")):\n                    _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=afi_vrf, issue=\"No Peers\")\n                    continue\n\n                peer_issues = {}\n                for peer, peer_data in peers.items():\n                    issues = _check_peer_issues(peer_data)\n\n                    if issues:\n                        peer_issues[peer] = issues\n\n                if peer_issues:\n                    _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=vrf, issue=peer_issues)\n\n        if failures:\n            self.result.is_failure(f\"Failures: {list(failures.values())}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeersHealth-attributes","title":"Inputs","text":"Name Type Description Default address_families list[BgpAfi] List of BGP address families (BgpAfi). -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeersHealth-attributes","title":"BgpAfi","text":"Name Type Description Default afi Afi BGP address family (AFI). - safi Safi | None Optional BGP subsequent service family (SAFI). If the input `afi` is `ipv4` or `ipv6`, a valid `safi` must be provided. None vrf str Optional VRF for IPv4 and IPv6. If not provided, it defaults to `default`. If the input `afi` is not `ipv4` or `ipv6`, e.g. `evpn`, `vrf` must be `default`. 'default'"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPSpecificPeers","title":"VerifyBGPSpecificPeers","text":"

Verifies the health of specific BGP peer(s).

It will validate that the BGP session is established and all message queues for this BGP session are empty for the given peer(s).

It supports multiple types of Address Families Identifiers (AFI) and Subsequent Address Family Identifiers (SAFI).

For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6 (AFI) which is handled automatically in this test.

Please refer to the Input class attributes below for details.

Expected Results
  • Success: If the BGP session is established and all messages queues are empty for each given peer.
  • Failure: If the BGP session has issues or is not configured, or if BGP is not configured for an expected VRF or address family.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPSpecificPeers:\n        address_families:\n          - afi: \"evpn\"\n            peers:\n              - 10.1.0.1\n              - 10.1.0.2\n          - afi: \"ipv4\"\n            safi: \"unicast\"\n            peers:\n              - 10.1.254.1\n              - 10.1.255.0\n              - 10.1.255.2\n              - 10.1.255.4\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPSpecificPeers(AntaTest):\n    \"\"\"Verifies the health of specific BGP peer(s).\n\n    It will validate that the BGP session is established and all message queues for this BGP session are empty for the given peer(s).\n\n    It supports multiple types of Address Families Identifiers (AFI) and Subsequent Address Family Identifiers (SAFI).\n\n    For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6 (AFI) which is handled automatically in this test.\n\n    Please refer to the Input class attributes below for details.\n\n    Expected Results\n    ----------------\n    * Success: If the BGP session is established and all messages queues are empty for each given peer.\n    * Failure: If the BGP session has issues or is not configured, or if BGP is not configured for an expected VRF or address family.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPSpecificPeers:\n            address_families:\n              - afi: \"evpn\"\n                peers:\n                  - 10.1.0.1\n                  - 10.1.0.2\n              - afi: \"ipv4\"\n                safi: \"unicast\"\n                peers:\n                  - 10.1.254.1\n                  - 10.1.255.0\n                  - 10.1.255.2\n                  - 10.1.255.4\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPSpecificPeers\"\n    description = \"Verifies the health of specific BGP peer(s).\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaTemplate(template=\"show bgp {afi} {safi} summary vrf {vrf}\", revision=3),\n        AntaTemplate(template=\"show bgp {afi} summary\", revision=3),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPSpecificPeers test.\"\"\"\n\n        address_families: list[BgpAfi]\n        \"\"\"List of BGP address families (BgpAfi).\"\"\"\n\n        class BgpAfi(BaseModel):\n            \"\"\"Model for a BGP address family (AFI) and subsequent address family (SAFI).\"\"\"\n\n            afi: Afi\n            \"\"\"BGP address family (AFI).\"\"\"\n            safi: Safi | None = None\n            \"\"\"Optional BGP subsequent service family (SAFI).\n\n            If the input `afi` is `ipv4` or `ipv6`, a valid `safi` must be provided.\n            \"\"\"\n            vrf: str = \"default\"\n            \"\"\"\n            Optional VRF for IPv4 and IPv6. If not provided, it defaults to `default`.\n\n            `all` is NOT supported.\n\n            If the input `afi` is not `ipv4` or `ipv6`, e.g. `evpn`, `vrf` must be `default`.\n            \"\"\"\n            peers: list[IPv4Address | IPv6Address]\n            \"\"\"List of BGP IPv4 or IPv6 peer.\"\"\"\n\n            @model_validator(mode=\"after\")\n            def validate_inputs(self: BaseModel) -> BaseModel:\n                \"\"\"Validate the inputs provided to the BgpAfi class.\n\n                If afi is either ipv4 or ipv6, safi must be provided and vrf must NOT be all.\n\n                If afi is not ipv4 or ipv6, safi must not be provided and vrf must be default.\n                \"\"\"\n                if self.afi in [\"ipv4\", \"ipv6\"]:\n                    if self.safi is None:\n                        msg = \"'safi' must be provided when afi is ipv4 or ipv6\"\n                        raise ValueError(msg)\n                    if self.vrf == \"all\":\n                        msg = \"'all' is not supported in this test. Use VerifyBGPPeersHealth test instead.\"\n                        raise ValueError(msg)\n                elif self.safi is not None:\n                    msg = \"'safi' must not be provided when afi is not ipv4 or ipv6\"\n                    raise ValueError(msg)\n                elif self.vrf != \"default\":\n                    msg = \"'vrf' must be default when afi is not ipv4 or ipv6\"\n                    raise ValueError(msg)\n                return self\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each BGP address family in the input list.\"\"\"\n        commands = []\n\n        for afi in self.inputs.address_families:\n            if template == VerifyBGPSpecificPeers.commands[0] and afi.afi in [\"ipv4\", \"ipv6\"] and afi.safi != \"sr-te\":\n                commands.append(template.render(afi=afi.afi, safi=afi.safi, vrf=afi.vrf))\n\n            # For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6\n            elif template == VerifyBGPSpecificPeers.commands[0] and afi.afi in [\"ipv4\", \"ipv6\"] and afi.safi == \"sr-te\":\n                commands.append(template.render(afi=afi.safi, safi=afi.afi, vrf=afi.vrf))\n            elif template == VerifyBGPSpecificPeers.commands[1] and afi.afi not in [\"ipv4\", \"ipv6\"]:\n                commands.append(template.render(afi=afi.afi))\n        return commands\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPSpecificPeers.\"\"\"\n        self.result.is_success()\n\n        failures: dict[tuple[str, Any], dict[str, Any]] = {}\n\n        for command in self.instance_commands:\n            command_output = command.json_output\n\n            afi = command.params.afi\n            safi = command.params.safi if hasattr(command.params, \"safi\") else None\n            afi_vrf = command.params.vrf if hasattr(command.params, \"vrf\") else \"default\"\n\n            # Swapping AFI and SAFI in case of SR-TE\n            if afi == \"sr-te\":\n                afi, safi = safi, afi\n\n            for input_entry in self.inputs.address_families:\n                if input_entry.afi == afi and input_entry.safi == safi and input_entry.vrf == afi_vrf:\n                    afi_peers = input_entry.peers\n                    break\n\n            if not (vrfs := command_output.get(\"vrfs\")):\n                _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=afi_vrf, issue=\"Not Configured\")\n                continue\n\n            peer_issues = {}\n            for peer in afi_peers:\n                peer_ip = str(peer)\n                peer_data = get_value(dictionary=vrfs, key=f\"{afi_vrf}_peers_{peer_ip}\", separator=\"_\")\n                issues = _check_peer_issues(peer_data)\n                if issues:\n                    peer_issues[peer_ip] = issues\n\n            if peer_issues:\n                _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=afi_vrf, issue=peer_issues)\n\n        if failures:\n            self.result.is_failure(f\"Failures: {list(failures.values())}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPSpecificPeers-attributes","title":"Inputs","text":"Name Type Description Default address_families list[BgpAfi] List of BGP address families (BgpAfi). -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPSpecificPeers-attributes","title":"BgpAfi","text":"Name Type Description Default afi Afi BGP address family (AFI). - safi Safi | None Optional BGP subsequent service family (SAFI). If the input `afi` is `ipv4` or `ipv6`, a valid `safi` must be provided. None vrf str Optional VRF for IPv4 and IPv6. If not provided, it defaults to `default`. `all` is NOT supported. If the input `afi` is not `ipv4` or `ipv6`, e.g. `evpn`, `vrf` must be `default`. 'default' peers list[IPv4Address | IPv6Address] List of BGP IPv4 or IPv6 peer. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPTimers","title":"VerifyBGPTimers","text":"

Verifies if the BGP peers are configured with the correct hold and keep-alive timers in the specified VRF.

Expected Results
  • Success: The test will pass if the hold and keep-alive timers are correct for BGP peers in the specified VRF.
  • Failure: The test will fail if BGP peers are not found or hold and keep-alive timers are not correct in the specified VRF.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPTimers:\n        bgp_peers:\n          - peer_address: 172.30.11.1\n            vrf: default\n            hold_time: 180\n            keep_alive_time: 60\n          - peer_address: 172.30.11.5\n            vrf: default\n            hold_time: 180\n            keep_alive_time: 60\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPTimers(AntaTest):\n    \"\"\"Verifies if the BGP peers are configured with the correct hold and keep-alive timers in the specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the hold and keep-alive timers are correct for BGP peers in the specified VRF.\n    * Failure: The test will fail if BGP peers are not found or hold and keep-alive timers are not correct in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPTimers:\n            bgp_peers:\n              - peer_address: 172.30.11.1\n                vrf: default\n                hold_time: 180\n                keep_alive_time: 60\n              - peer_address: 172.30.11.5\n                vrf: default\n                hold_time: 180\n                keep_alive_time: 60\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPTimers\"\n    description = \"Verifies the timers of a BGP peer.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bgp neighbors vrf all\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPTimers test.\"\"\"\n\n        bgp_peers: list[BgpPeer]\n        \"\"\"List of BGP peers\"\"\"\n\n        class BgpPeer(BaseModel):\n            \"\"\"Model for a BGP peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n            hold_time: int = Field(ge=3, le=7200)\n            \"\"\"BGP hold time in seconds.\"\"\"\n            keep_alive_time: int = Field(ge=0, le=3600)\n            \"\"\"BGP keep-alive time in seconds.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPTimers.\"\"\"\n        failures: dict[str, Any] = {}\n\n        # Iterate over each bgp peer\n        for bgp_peer in self.inputs.bgp_peers:\n            peer_address = str(bgp_peer.peer_address)\n            vrf = bgp_peer.vrf\n            hold_time = bgp_peer.hold_time\n            keep_alive_time = bgp_peer.keep_alive_time\n\n            # Verify BGP peer\n            if (\n                not (bgp_output := get_value(self.instance_commands[0].json_output, f\"vrfs.{vrf}.peerList\"))\n                or (bgp_output := get_item(bgp_output, \"peerAddress\", peer_address)) is None\n            ):\n                failures[peer_address] = {vrf: \"Not configured\"}\n                continue\n\n            # Verify BGP peer's hold and keep alive timers\n            if bgp_output.get(\"holdTime\") != hold_time or bgp_output.get(\"keepaliveTime\") != keep_alive_time:\n                failures[peer_address] = {vrf: {\"hold_time\": bgp_output.get(\"holdTime\"), \"keep_alive_time\": bgp_output.get(\"keepaliveTime\")}}\n\n        if not failures:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peers are not configured or hold and keep-alive timers are not correct:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPTimers-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpPeer] List of BGP peers -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPTimers-attributes","title":"BgpPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default' hold_time int BGP hold time in seconds. Field(ge=3, le=7200) keep_alive_time int BGP keep-alive time in seconds. Field(ge=0, le=3600)"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyEVPNType2Route","title":"VerifyEVPNType2Route","text":"

Verifies the EVPN Type-2 routes for a given IPv4 or MAC address and VNI.

Expected Results
  • Success: If all provided VXLAN endpoints have at least one valid and active path to their EVPN Type-2 routes.
  • Failure: If any of the provided VXLAN endpoints do not have at least one valid and active path to their EVPN Type-2 routes.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyEVPNType2Route:\n        vxlan_endpoints:\n          - address: 192.168.20.102\n            vni: 10020\n          - address: aac1.ab5d.b41e\n            vni: 10010\n
Source code in anta/tests/routing/bgp.py
class VerifyEVPNType2Route(AntaTest):\n    \"\"\"Verifies the EVPN Type-2 routes for a given IPv4 or MAC address and VNI.\n\n    Expected Results\n    ----------------\n    * Success: If all provided VXLAN endpoints have at least one valid and active path to their EVPN Type-2 routes.\n    * Failure: If any of the provided VXLAN endpoints do not have at least one valid and active path to their EVPN Type-2 routes.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyEVPNType2Route:\n            vxlan_endpoints:\n              - address: 192.168.20.102\n                vni: 10020\n              - address: aac1.ab5d.b41e\n                vni: 10010\n    ```\n    \"\"\"\n\n    name = \"VerifyEVPNType2Route\"\n    description = \"Verifies the EVPN Type-2 routes for a given IPv4 or MAC address and VNI.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show bgp evpn route-type mac-ip {address} vni {vni}\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyEVPNType2Route test.\"\"\"\n\n        vxlan_endpoints: list[VxlanEndpoint]\n        \"\"\"List of VXLAN endpoints to verify.\"\"\"\n\n        class VxlanEndpoint(BaseModel):\n            \"\"\"Model for a VXLAN endpoint.\"\"\"\n\n            address: IPv4Address | MacAddress\n            \"\"\"IPv4 or MAC address of the VXLAN endpoint.\"\"\"\n            vni: Vni\n            \"\"\"VNI of the VXLAN endpoint.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each VXLAN endpoint in the input list.\"\"\"\n        return [template.render(address=str(endpoint.address), vni=endpoint.vni) for endpoint in self.inputs.vxlan_endpoints]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyEVPNType2Route.\"\"\"\n        self.result.is_success()\n        no_evpn_routes = []\n        bad_evpn_routes = []\n\n        for command in self.instance_commands:\n            address = command.params.address\n            vni = command.params.vni\n            # Verify that the VXLAN endpoint is in the BGP EVPN table\n            evpn_routes = command.json_output[\"evpnRoutes\"]\n            if not evpn_routes:\n                no_evpn_routes.append((address, vni))\n                continue\n            # Verify that each EVPN route has at least one valid and active path\n            for route, route_data in evpn_routes.items():\n                has_active_path = False\n                for path in route_data[\"evpnRoutePaths\"]:\n                    if path[\"routeType\"][\"valid\"] is True and path[\"routeType\"][\"active\"] is True:\n                        # At least one path is valid and active, no need to check the other paths\n                        has_active_path = True\n                        break\n                if not has_active_path:\n                    bad_evpn_routes.append(route)\n\n        if no_evpn_routes:\n            self.result.is_failure(f\"The following VXLAN endpoint do not have any EVPN Type-2 route: {no_evpn_routes}\")\n        if bad_evpn_routes:\n            self.result.is_failure(f\"The following EVPN Type-2 routes do not have at least one valid and active path: {bad_evpn_routes}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyEVPNType2Route-attributes","title":"Inputs","text":"Name Type Description Default vxlan_endpoints list[VxlanEndpoint] List of VXLAN endpoints to verify. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyEVPNType2Route-attributes","title":"VxlanEndpoint","text":"Name Type Description Default address IPv4Address | MacAddress IPv4 or MAC address of the VXLAN endpoint. - vni Vni VNI of the VXLAN endpoint. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp._add_bgp_failures","title":"_add_bgp_failures","text":"
_add_bgp_failures(failures: dict[tuple[str, str | None], dict[str, Any]], afi: Afi, safi: Safi | None, vrf: str, issue: str | dict[str, Any]) -> None\n

Add a BGP failure entry to the given failures dictionary.

Note: This function modifies failures in-place.

Example:

The failures dictionary will have the following structure: { (\u2018afi1\u2019, \u2018safi1\u2019): { \u2018afi\u2019: \u2018afi1\u2019, \u2018safi\u2019: \u2018safi1\u2019, \u2018vrfs\u2019: { \u2018vrf1\u2019: issue1, \u2018vrf2\u2019: issue2 } }, (\u2018afi2\u2019, None): { \u2018afi\u2019: \u2018afi2\u2019, \u2018vrfs\u2019: { \u2018vrf1\u2019: issue3 } } }

Source code in anta/tests/routing/bgp.py
def _add_bgp_failures(failures: dict[tuple[str, str | None], dict[str, Any]], afi: Afi, safi: Safi | None, vrf: str, issue: str | dict[str, Any]) -> None:\n    \"\"\"Add a BGP failure entry to the given `failures` dictionary.\n\n    Note: This function modifies `failures` in-place.\n\n    Parameters\n    ----------\n        failures: The dictionary to which the failure will be added.\n        afi: The address family identifier.\n        vrf: The VRF name.\n        safi: The subsequent address family identifier.\n        issue: A description of the issue. Can be of any type.\n\n    Example:\n    -------\n    The `failures` dictionary will have the following structure:\n        {\n            ('afi1', 'safi1'): {\n                'afi': 'afi1',\n                'safi': 'safi1',\n                'vrfs': {\n                    'vrf1': issue1,\n                    'vrf2': issue2\n                }\n            },\n            ('afi2', None): {\n                'afi': 'afi2',\n                'vrfs': {\n                    'vrf1': issue3\n                }\n            }\n        }\n\n    \"\"\"\n    key = (afi, safi)\n\n    failure_entry = failures.setdefault(key, {\"afi\": afi, \"safi\": safi, \"vrfs\": {}}) if safi else failures.setdefault(key, {\"afi\": afi, \"vrfs\": {}})\n\n    failure_entry[\"vrfs\"][vrf] = issue\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp._add_bgp_routes_failure","title":"_add_bgp_routes_failure","text":"
_add_bgp_routes_failure(bgp_routes: list[str], bgp_output: dict[str, Any], peer: str, vrf: str, route_type: str = 'advertised_routes') -> dict[str, dict[str, dict[str, dict[str, list[str]]]]]\n

Identify missing BGP routes and invalid or inactive route entries.

This function checks the BGP output from the device against the expected routes.

It identifies any missing routes as well as any routes that are invalid or inactive. The results are returned in a dictionary.

Returns:

Type Description dict[str, dict[str, dict[str, dict[str, list[str]]]]]: A dictionary containing the missing routes and invalid or inactive routes. Source code in anta/tests/routing/bgp.py
def _add_bgp_routes_failure(\n    bgp_routes: list[str], bgp_output: dict[str, Any], peer: str, vrf: str, route_type: str = \"advertised_routes\"\n) -> dict[str, dict[str, dict[str, dict[str, list[str]]]]]:\n    \"\"\"Identify missing BGP routes and invalid or inactive route entries.\n\n    This function checks the BGP output from the device against the expected routes.\n\n    It identifies any missing routes as well as any routes that are invalid or inactive. The results are returned in a dictionary.\n\n    Parameters\n    ----------\n        bgp_routes: The list of expected routes.\n        bgp_output: The BGP output from the device.\n        peer: The IP address of the BGP peer.\n        vrf: The name of the VRF for which the routes need to be verified.\n        route_type: The type of BGP routes. Defaults to 'advertised_routes'.\n\n    Returns\n    -------\n        dict[str, dict[str, dict[str, dict[str, list[str]]]]]: A dictionary containing the missing routes and invalid or inactive routes.\n\n    \"\"\"\n    # Prepare the failure routes dictionary\n    failure_routes: dict[str, dict[str, Any]] = {}\n\n    # Iterate over the expected BGP routes\n    for route in bgp_routes:\n        str_route = str(route)\n        failure = {\"bgp_peers\": {peer: {vrf: {route_type: {str_route: Any}}}}}\n\n        # Check if the route is missing in the BGP output\n        if str_route not in bgp_output:\n            # If missing, add it to the failure routes dictionary\n            failure[\"bgp_peers\"][peer][vrf][route_type][str_route] = \"Not found\"\n            failure_routes = deep_update(failure_routes, failure)\n            continue\n\n        # Check if the route is active and valid\n        is_active = bgp_output[str_route][\"bgpRoutePaths\"][0][\"routeType\"][\"valid\"]\n        is_valid = bgp_output[str_route][\"bgpRoutePaths\"][0][\"routeType\"][\"active\"]\n\n        # If the route is either inactive or invalid, add it to the failure routes dictionary\n        if not is_active or not is_valid:\n            failure[\"bgp_peers\"][peer][vrf][route_type][str_route] = {\"valid\": is_valid, \"active\": is_active}\n            failure_routes = deep_update(failure_routes, failure)\n\n    return failure_routes\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp._check_peer_issues","title":"_check_peer_issues","text":"
_check_peer_issues(peer_data: dict[str, Any] | None) -> dict[str, Any]\n

Check for issues in BGP peer data.

Returns:

Type Description dict: Dictionary with keys indicating issues or an empty dictionary if no issues.

Raises:

Type Description ValueError: If any of the required keys (\"peerState\", \"inMsgQueue\", \"outMsgQueue\") are missing in `peer_data`, i.e. invalid BGP peer data. Example:
{\"peerNotFound\": True}\n{\"peerState\": \"Idle\", \"inMsgQueue\": 2, \"outMsgQueue\": 0}\n{}\n
Source code in anta/tests/routing/bgp.py
def _check_peer_issues(peer_data: dict[str, Any] | None) -> dict[str, Any]:\n    \"\"\"Check for issues in BGP peer data.\n\n    Parameters\n    ----------\n        peer_data: The BGP peer data dictionary nested in the `show bgp <afi> <safi> summary` command.\n\n    Returns\n    -------\n        dict: Dictionary with keys indicating issues or an empty dictionary if no issues.\n\n    Raises\n    ------\n        ValueError: If any of the required keys (\"peerState\", \"inMsgQueue\", \"outMsgQueue\") are missing in `peer_data`, i.e. invalid BGP peer data.\n\n    Example:\n    -------\n        {\"peerNotFound\": True}\n        {\"peerState\": \"Idle\", \"inMsgQueue\": 2, \"outMsgQueue\": 0}\n        {}\n\n    \"\"\"\n    if peer_data is None:\n        return {\"peerNotFound\": True}\n\n    if any(key not in peer_data for key in [\"peerState\", \"inMsgQueue\", \"outMsgQueue\"]):\n        msg = \"Provided BGP peer data is invalid.\"\n        raise ValueError(msg)\n\n    if peer_data[\"peerState\"] != \"Established\" or peer_data[\"inMsgQueue\"] != 0 or peer_data[\"outMsgQueue\"] != 0:\n        return {\"peerState\": peer_data[\"peerState\"], \"inMsgQueue\": peer_data[\"inMsgQueue\"], \"outMsgQueue\": peer_data[\"outMsgQueue\"]}\n\n    return {}\n
"},{"location":"api/tests.routing.generic/","title":"Generic","text":""},{"location":"api/tests.routing.generic/#anta.tests.routing.generic.VerifyRoutingProtocolModel","title":"VerifyRoutingProtocolModel","text":"

Verifies the configured routing protocol model is the one we expect.

Expected Results
  • Success: The test will pass if the configured routing protocol model is the one we expect.
  • Failure: The test will fail if the configured routing protocol model is not the one we expect.
Examples
anta.tests.routing:\n  generic:\n    - VerifyRoutingProtocolModel:\n        model: multi-agent\n
Source code in anta/tests/routing/generic.py
class VerifyRoutingProtocolModel(AntaTest):\n    \"\"\"Verifies the configured routing protocol model is the one we expect.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the configured routing protocol model is the one we expect.\n    * Failure: The test will fail if the configured routing protocol model is not the one we expect.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      generic:\n        - VerifyRoutingProtocolModel:\n            model: multi-agent\n    ```\n    \"\"\"\n\n    name = \"VerifyRoutingProtocolModel\"\n    description = \"Verifies the configured routing protocol model.\"\n    categories: ClassVar[list[str]] = [\"routing\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip route summary\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyRoutingProtocolModel test.\"\"\"\n\n        model: Literal[\"multi-agent\", \"ribd\"] = \"multi-agent\"\n        \"\"\"Expected routing protocol model. Defaults to `multi-agent`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyRoutingProtocolModel.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        configured_model = command_output[\"protoModelStatus\"][\"configuredProtoModel\"]\n        operating_model = command_output[\"protoModelStatus\"][\"operatingProtoModel\"]\n        if configured_model == operating_model == self.inputs.model:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"routing model is misconfigured: configured: {configured_model} - operating: {operating_model} - expected: {self.inputs.model}\")\n
"},{"location":"api/tests.routing.generic/#anta.tests.routing.generic.VerifyRoutingProtocolModel-attributes","title":"Inputs","text":"Name Type Description Default model Literal['multi-agent', 'ribd'] Expected routing protocol model. Defaults to `multi-agent`. 'multi-agent'"},{"location":"api/tests.routing.generic/#anta.tests.routing.generic.VerifyRoutingTableEntry","title":"VerifyRoutingTableEntry","text":"

Verifies that the provided routes are present in the routing table of a specified VRF.

Expected Results
  • Success: The test will pass if the provided routes are present in the routing table.
  • Failure: The test will fail if one or many provided routes are missing from the routing table.
Examples
anta.tests.routing:\n  generic:\n    - VerifyRoutingTableEntry:\n        vrf: default\n        routes:\n          - 10.1.0.1\n          - 10.1.0.2\n
Source code in anta/tests/routing/generic.py
class VerifyRoutingTableEntry(AntaTest):\n    \"\"\"Verifies that the provided routes are present in the routing table of a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided routes are present in the routing table.\n    * Failure: The test will fail if one or many provided routes are missing from the routing table.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      generic:\n        - VerifyRoutingTableEntry:\n            vrf: default\n            routes:\n              - 10.1.0.1\n              - 10.1.0.2\n    ```\n    \"\"\"\n\n    name = \"VerifyRoutingTableEntry\"\n    description = \"Verifies that the provided routes are present in the routing table of a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"routing\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show ip route vrf {vrf} {route}\", revision=4)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyRoutingTableEntry test.\"\"\"\n\n        vrf: str = \"default\"\n        \"\"\"VRF context. Defaults to `default` VRF.\"\"\"\n        routes: list[IPv4Address]\n        \"\"\"List of routes to verify.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each route in the input list.\"\"\"\n        return [template.render(vrf=self.inputs.vrf, route=route) for route in self.inputs.routes]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyRoutingTableEntry.\"\"\"\n        missing_routes = []\n\n        for command in self.instance_commands:\n            vrf, route = command.params.vrf, command.params.route\n            if len(routes := command.json_output[\"vrfs\"][vrf][\"routes\"]) == 0 or route != ip_interface(next(iter(routes))).ip:\n                missing_routes.append(str(route))\n\n        if not missing_routes:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following route(s) are missing from the routing table of VRF {self.inputs.vrf}: {missing_routes}\")\n
"},{"location":"api/tests.routing.generic/#anta.tests.routing.generic.VerifyRoutingTableEntry-attributes","title":"Inputs","text":"Name Type Description Default vrf str VRF context. Defaults to `default` VRF. 'default' routes list[IPv4Address] List of routes to verify. -"},{"location":"api/tests.routing.generic/#anta.tests.routing.generic.VerifyRoutingTableSize","title":"VerifyRoutingTableSize","text":"

Verifies the size of the IP routing table of the default VRF.

Expected Results
  • Success: The test will pass if the routing table size is between the provided minimum and maximum values.
  • Failure: The test will fail if the routing table size is not between the provided minimum and maximum values.
Examples
anta.tests.routing:\n  generic:\n    - VerifyRoutingTableSize:\n        minimum: 2\n        maximum: 20\n
Source code in anta/tests/routing/generic.py
class VerifyRoutingTableSize(AntaTest):\n    \"\"\"Verifies the size of the IP routing table of the default VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the routing table size is between the provided minimum and maximum values.\n    * Failure: The test will fail if the routing table size is not between the provided minimum and maximum values.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      generic:\n        - VerifyRoutingTableSize:\n            minimum: 2\n            maximum: 20\n    ```\n    \"\"\"\n\n    name = \"VerifyRoutingTableSize\"\n    description = \"Verifies the size of the IP routing table of the default VRF.\"\n    categories: ClassVar[list[str]] = [\"routing\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip route summary\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyRoutingTableSize test.\"\"\"\n\n        minimum: int\n        \"\"\"Expected minimum routing table size.\"\"\"\n        maximum: int\n        \"\"\"Expected maximum routing table size.\"\"\"\n\n        @model_validator(mode=\"after\")  # type: ignore[misc]\n        def check_min_max(self) -> AntaTest.Input:\n            \"\"\"Validate that maximum is greater than minimum.\"\"\"\n            if self.minimum > self.maximum:\n                msg = f\"Minimum {self.minimum} is greater than maximum {self.maximum}\"\n                raise ValueError(msg)\n            return self\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyRoutingTableSize.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        total_routes = int(command_output[\"vrfs\"][\"default\"][\"totalRoutes\"])\n        if self.inputs.minimum <= total_routes <= self.inputs.maximum:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"routing-table has {total_routes} routes and not between min ({self.inputs.minimum}) and maximum ({self.inputs.maximum})\")\n
"},{"location":"api/tests.routing.generic/#anta.tests.routing.generic.VerifyRoutingTableSize-attributes","title":"Inputs","text":"Name Type Description Default minimum int Expected minimum routing table size. - maximum int Expected maximum routing table size. -"},{"location":"api/tests.routing.isis/","title":"ISIS","text":""},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISInterfaceMode","title":"VerifyISISInterfaceMode","text":"

Verifies ISIS Interfaces are running in correct mode.

Expected Results
  • Success: The test will pass if all listed interfaces are running in correct mode.
  • Failure: The test will fail if any of the listed interfaces is not running in correct mode.
  • Skipped: The test will be skipped if no ISIS neighbor is found.
Examples
anta.tests.routing:\n  isis:\n    - VerifyISISInterfaceMode:\n        interfaces:\n          - name: Loopback0\n            mode: passive\n            # vrf is set to default by default\n          - name: Ethernet2\n            mode: passive\n            level: 2\n            # vrf is set to default by default\n          - name: Ethernet1\n            mode: point-to-point\n            vrf: default\n            # level is set to 2 by default\n
Source code in anta/tests/routing/isis.py
class VerifyISISInterfaceMode(AntaTest):\n    \"\"\"Verifies ISIS Interfaces are running in correct mode.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all listed interfaces are running in correct mode.\n    * Failure: The test will fail if any of the listed interfaces is not running in correct mode.\n    * Skipped: The test will be skipped if no ISIS neighbor is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      isis:\n        - VerifyISISInterfaceMode:\n            interfaces:\n              - name: Loopback0\n                mode: passive\n                # vrf is set to default by default\n              - name: Ethernet2\n                mode: passive\n                level: 2\n                # vrf is set to default by default\n              - name: Ethernet1\n                mode: point-to-point\n                vrf: default\n                # level is set to 2 by default\n    ```\n    \"\"\"\n\n    name = \"VerifyISISInterfaceMode\"\n    description = \"Verifies interface mode for IS-IS\"\n    categories: ClassVar[list[str]] = [\"isis\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show isis interface brief\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyISISNeighborCount test.\"\"\"\n\n        interfaces: list[InterfaceState]\n        \"\"\"list of interfaces with their information.\"\"\"\n\n        class InterfaceState(BaseModel):\n            \"\"\"Input model for the VerifyISISNeighborCount test.\"\"\"\n\n            name: Interface\n            \"\"\"Interface name to check.\"\"\"\n            level: Literal[1, 2] = 2\n            \"\"\"ISIS level configured for interface. Default is 2.\"\"\"\n            mode: Literal[\"point-to-point\", \"broadcast\", \"passive\"]\n            \"\"\"Number of IS-IS neighbors.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"VRF where the interface should be configured\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyISISInterfaceMode.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n\n        if len(command_output[\"vrfs\"]) == 0:\n            self.result.is_skipped(\"IS-IS is not configured on device\")\n            return\n\n        # Check for p2p interfaces\n        for interface in self.inputs.interfaces:\n            interface_data = _get_interface_data(\n                interface=interface.name,\n                vrf=interface.vrf,\n                command_output=command_output,\n            )\n            # Check for correct VRF\n            if interface_data is not None:\n                interface_type = get_value(dictionary=interface_data, key=\"interfaceType\", default=\"unset\")\n                # Check for interfaceType\n                if interface.mode == \"point-to-point\" and interface.mode != interface_type:\n                    self.result.is_failure(f\"Interface {interface.name} in VRF {interface.vrf} is not running in {interface.mode} reporting {interface_type}\")\n                # Check for passive\n                elif interface.mode == \"passive\":\n                    json_path = f\"intfLevels.{interface.level}.passive\"\n                    if interface_data is None or get_value(dictionary=interface_data, key=json_path, default=False) is False:\n                        self.result.is_failure(f\"Interface {interface.name} in VRF {interface.vrf} is not running in passive mode\")\n            else:\n                self.result.is_failure(f\"Interface {interface.name} not found in VRF {interface.vrf}\")\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISInterfaceMode-attributes","title":"Inputs","text":"Name Type Description Default interfaces list[InterfaceState] list of interfaces with their information. -"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISInterfaceMode-attributes","title":"InterfaceState","text":"Name Type Description Default name Interface Interface name to check. - level Literal[1, 2] ISIS level configured for interface. Default is 2. 2 mode Literal['point-to-point', 'broadcast', 'passive'] Number of IS-IS neighbors. - vrf str VRF where the interface should be configured 'default'"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISNeighborCount","title":"VerifyISISNeighborCount","text":"

Verifies number of IS-IS neighbors per level and per interface.

Expected Results
  • Success: The test will pass if the number of neighbors is correct.
  • Failure: The test will fail if the number of neighbors is incorrect.
  • Skipped: The test will be skipped if no IS-IS neighbor is found.
Examples
anta.tests.routing:\n  isis:\n    - VerifyISISNeighborCount:\n        interfaces:\n          - name: Ethernet1\n            level: 1\n            count: 2\n          - name: Ethernet2\n            level: 2\n            count: 1\n          - name: Ethernet3\n            count: 2\n            # level is set to 2 by default\n
Source code in anta/tests/routing/isis.py
class VerifyISISNeighborCount(AntaTest):\n    \"\"\"Verifies number of IS-IS neighbors per level and per interface.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the number of neighbors is correct.\n    * Failure: The test will fail if the number of neighbors is incorrect.\n    * Skipped: The test will be skipped if no IS-IS neighbor is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      isis:\n        - VerifyISISNeighborCount:\n            interfaces:\n              - name: Ethernet1\n                level: 1\n                count: 2\n              - name: Ethernet2\n                level: 2\n                count: 1\n              - name: Ethernet3\n                count: 2\n                # level is set to 2 by default\n    ```\n    \"\"\"\n\n    name = \"VerifyISISNeighborCount\"\n    description = \"Verifies count of IS-IS interface per level\"\n    categories: ClassVar[list[str]] = [\"isis\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show isis interface brief\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyISISNeighborCount test.\"\"\"\n\n        interfaces: list[InterfaceCount]\n        \"\"\"list of interfaces with their information.\"\"\"\n\n        class InterfaceCount(BaseModel):\n            \"\"\"Input model for the VerifyISISNeighborCount test.\"\"\"\n\n            name: Interface\n            \"\"\"Interface name to check.\"\"\"\n            level: int = 2\n            \"\"\"IS-IS level to check.\"\"\"\n            count: int\n            \"\"\"Number of IS-IS neighbors.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyISISNeighborCount.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n        isis_neighbor_count = _get_isis_neighbors_count(command_output)\n        if len(isis_neighbor_count) == 0:\n            self.result.is_skipped(\"No IS-IS neighbor detected\")\n            return\n        for interface in self.inputs.interfaces:\n            eos_data = [ifl_data for ifl_data in isis_neighbor_count if ifl_data[\"interface\"] == interface.name and ifl_data[\"level\"] == interface.level]\n            if not eos_data:\n                self.result.is_failure(f\"No neighbor detected for interface {interface.name}\")\n                continue\n            if eos_data[0][\"count\"] != interface.count:\n                self.result.is_failure(\n                    f\"Interface {interface.name}: \"\n                    f\"expected Level {interface.level}: count {interface.count}, \"\n                    f\"got Level {eos_data[0]['level']}: count {eos_data[0]['count']}\"\n                )\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISNeighborCount-attributes","title":"Inputs","text":"Name Type Description Default interfaces list[InterfaceCount] list of interfaces with their information. -"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISNeighborCount-attributes","title":"InterfaceCount","text":"Name Type Description Default name Interface Interface name to check. - level int IS-IS level to check. 2 count int Number of IS-IS neighbors. -"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISNeighborState","title":"VerifyISISNeighborState","text":"

Verifies all IS-IS neighbors are in UP state.

Expected Results
  • Success: The test will pass if all IS-IS neighbors are in UP state.
  • Failure: The test will fail if some IS-IS neighbors are not in UP state.
  • Skipped: The test will be skipped if no IS-IS neighbor is found.
Examples
anta.tests.routing:\n  isis:\n    - VerifyISISNeighborState:\n
Source code in anta/tests/routing/isis.py
class VerifyISISNeighborState(AntaTest):\n    \"\"\"Verifies all IS-IS neighbors are in UP state.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all IS-IS neighbors are in UP state.\n    * Failure: The test will fail if some IS-IS neighbors are not in UP state.\n    * Skipped: The test will be skipped if no IS-IS neighbor is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      isis:\n        - VerifyISISNeighborState:\n    ```\n    \"\"\"\n\n    name = \"VerifyISISNeighborState\"\n    description = \"Verifies all IS-IS neighbors are in UP state.\"\n    categories: ClassVar[list[str]] = [\"isis\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show isis neighbors\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyISISNeighborState.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if _count_isis_neighbor(command_output) == 0:\n            self.result.is_skipped(\"No IS-IS neighbor detected\")\n            return\n        self.result.is_success()\n        not_full_neighbors = _get_not_full_isis_neighbors(command_output)\n        if not_full_neighbors:\n            self.result.is_failure(f\"Some neighbors are not in the correct state (UP): {not_full_neighbors}.\")\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingAdjacencySegments","title":"VerifyISISSegmentRoutingAdjacencySegments","text":"

Verifies ISIS Segment Routing Adjacency Segments.

Verify that all expected Adjacency segments are correctly visible for each interface.

Expected Results
  • Success: The test will pass if all listed interfaces have correct adjacencies.
  • Failure: The test will fail if any of the listed interfaces has not expected list of adjacencies.
  • Skipped: The test will be skipped if no ISIS SR Adjacency is found.
Examples
anta.tests.routing:\n  isis:\n    - VerifyISISSegmentRoutingAdjacencySegments:\n        instances:\n          - name: CORE-ISIS\n            vrf: default\n            segments:\n              - interface: Ethernet2\n                address: 10.0.1.3\n                sid_origin: dynamic\n
Source code in anta/tests/routing/isis.py
class VerifyISISSegmentRoutingAdjacencySegments(AntaTest):\n    \"\"\"Verifies ISIS Segment Routing Adjacency Segments.\n\n    Verify that all expected Adjacency segments are correctly visible for each interface.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all listed interfaces have correct adjacencies.\n    * Failure: The test will fail if any of the listed interfaces has not expected list of adjacencies.\n    * Skipped: The test will be skipped if no ISIS SR Adjacency is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      isis:\n        - VerifyISISSegmentRoutingAdjacencySegments:\n            instances:\n              - name: CORE-ISIS\n                vrf: default\n                segments:\n                  - interface: Ethernet2\n                    address: 10.0.1.3\n                    sid_origin: dynamic\n\n    ```\n    \"\"\"\n\n    name = \"VerifyISISSegmentRoutingAdjacencySegments\"\n    description = \"Verify expected Adjacency segments are correctly visible for each interface.\"\n    categories: ClassVar[list[str]] = [\"isis\", \"segment-routing\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show isis segment-routing adjacency-segments\", ofmt=\"json\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyISISSegmentRoutingAdjacencySegments test.\"\"\"\n\n        instances: list[IsisInstance]\n\n        class IsisInstance(BaseModel):\n            \"\"\"ISIS Instance model definition.\"\"\"\n\n            name: str\n            \"\"\"ISIS instance name.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"VRF name where ISIS instance is configured.\"\"\"\n            segments: list[Segment]\n            \"\"\"List of Adjacency segments configured in this instance.\"\"\"\n\n            class Segment(BaseModel):\n                \"\"\"Segment model definition.\"\"\"\n\n                interface: Interface\n                \"\"\"Interface name to check.\"\"\"\n                level: Literal[1, 2] = 2\n                \"\"\"ISIS level configured for interface. Default is 2.\"\"\"\n                sid_origin: Literal[\"dynamic\"] = \"dynamic\"\n                \"\"\"Adjacency type\"\"\"\n                address: IPv4Address\n                \"\"\"IP address of remote end of segment.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyISISSegmentRoutingAdjacencySegments.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n\n        if len(command_output[\"vrfs\"]) == 0:\n            self.result.is_skipped(\"IS-IS is not configured on device\")\n            return\n\n        # initiate defaults\n        failure_message = []\n        skip_vrfs = []\n        skip_instances = []\n\n        # Check if VRFs and instances are present in output.\n        for instance in self.inputs.instances:\n            vrf_data = get_value(\n                dictionary=command_output,\n                key=f\"vrfs.{instance.vrf}\",\n                default=None,\n            )\n            if vrf_data is None:\n                skip_vrfs.append(instance.vrf)\n                failure_message.append(f\"VRF {instance.vrf} is not configured to run segment routging.\")\n\n            elif get_value(dictionary=vrf_data, key=f\"isisInstances.{instance.name}\", default=None) is None:\n                skip_instances.append(instance.name)\n                failure_message.append(f\"Instance {instance.name} is not found in vrf {instance.vrf}.\")\n\n        # Check Adjacency segments\n        for instance in self.inputs.instances:\n            if instance.vrf not in skip_vrfs and instance.name not in skip_instances:\n                for input_segment in instance.segments:\n                    eos_segment = _get_adjacency_segment_data_by_neighbor(\n                        neighbor=str(input_segment.address),\n                        instance=instance.name,\n                        vrf=instance.vrf,\n                        command_output=command_output,\n                    )\n                    if eos_segment is None:\n                        failure_message.append(f\"Your segment has not been found: {input_segment}.\")\n\n                    elif (\n                        eos_segment[\"localIntf\"] != input_segment.interface\n                        or eos_segment[\"level\"] != input_segment.level\n                        or eos_segment[\"sidOrigin\"] != input_segment.sid_origin\n                    ):\n                        failure_message.append(f\"Your segment is not correct: Expected: {input_segment} - Found: {eos_segment}.\")\n        if failure_message:\n            self.result.is_failure(\"\\n\".join(failure_message))\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingAdjacencySegments-attributes","title":"Inputs","text":"Name Type Description Default"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingAdjacencySegments-attributes","title":"IsisInstance","text":"Name Type Description Default name str ISIS instance name. - vrf str VRF name where ISIS instance is configured. 'default' segments list[Segment] List of Adjacency segments configured in this instance. -"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingAdjacencySegments-attributes","title":"Segment","text":"Name Type Description Default interface Interface Interface name to check. - level Literal[1, 2] ISIS level configured for interface. Default is 2. 2 sid_origin Literal['dynamic'] Adjacency type 'dynamic' address IPv4Address IP address of remote end of segment. -"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingDataplane","title":"VerifyISISSegmentRoutingDataplane","text":"

Verify dataplane of a list of ISIS-SR instances.

Expected Results
  • Success: The test will pass if all instances have correct dataplane configured
  • Failure: The test will fail if one of the instances has incorrect dataplane configured
  • Skipped: The test will be skipped if ISIS is not running
Examples
anta.tests.routing:\n  isis:\n    - VerifyISISSegmentRoutingDataplane:\n        instances:\n          - name: CORE-ISIS\n            vrf: default\n            dataplane: MPLS\n
Source code in anta/tests/routing/isis.py
class VerifyISISSegmentRoutingDataplane(AntaTest):\n    \"\"\"\n    Verify dataplane of a list of ISIS-SR instances.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all instances have correct dataplane configured\n    * Failure: The test will fail if one of the instances has incorrect dataplane configured\n    * Skipped: The test will be skipped if ISIS is not running\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      isis:\n        - VerifyISISSegmentRoutingDataplane:\n            instances:\n              - name: CORE-ISIS\n                vrf: default\n                dataplane: MPLS\n    ```\n    \"\"\"\n\n    name = \"VerifyISISSegmentRoutingDataplane\"\n    description = \"Verify dataplane of a list of ISIS-SR instances\"\n    categories: ClassVar[list[str]] = [\"isis\", \"segment-routing\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show isis segment-routing\", ofmt=\"json\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyISISSegmentRoutingDataplane test.\"\"\"\n\n        instances: list[IsisInstance]\n\n        class IsisInstance(BaseModel):\n            \"\"\"ISIS Instance model definition.\"\"\"\n\n            name: str\n            \"\"\"ISIS instance name.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"VRF name where ISIS instance is configured.\"\"\"\n            dataplane: Literal[\"MPLS\", \"mpls\", \"unset\"] = \"MPLS\"\n            \"\"\"Configured dataplane for the instance.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyISISSegmentRoutingDataplane.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n\n        if len(command_output[\"vrfs\"]) == 0:\n            self.result.is_skipped(\"IS-IS-SR is not running on device.\")\n            return\n\n        # initiate defaults\n        failure_message = []\n        skip_vrfs = []\n        skip_instances = []\n\n        # Check if VRFs and instances are present in output.\n        for instance in self.inputs.instances:\n            vrf_data = get_value(\n                dictionary=command_output,\n                key=f\"vrfs.{instance.vrf}\",\n                default=None,\n            )\n            if vrf_data is None:\n                skip_vrfs.append(instance.vrf)\n                failure_message.append(f\"VRF {instance.vrf} is not configured to run segment routing.\")\n\n            elif get_value(dictionary=vrf_data, key=f\"isisInstances.{instance.name}\", default=None) is None:\n                skip_instances.append(instance.name)\n                failure_message.append(f\"Instance {instance.name} is not found in vrf {instance.vrf}.\")\n\n        # Check Adjacency segments\n        for instance in self.inputs.instances:\n            if instance.vrf not in skip_vrfs and instance.name not in skip_instances:\n                eos_dataplane = get_value(dictionary=command_output, key=f\"vrfs.{instance.vrf}.isisInstances.{instance.name}.dataPlane\", default=None)\n                if instance.dataplane.upper() != eos_dataplane:\n                    failure_message.append(f\"ISIS instance {instance.name} is not running dataplane {instance.dataplane} ({eos_dataplane})\")\n\n        if failure_message:\n            self.result.is_failure(\"\\n\".join(failure_message))\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingDataplane-attributes","title":"Inputs","text":"Name Type Description Default"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingDataplane-attributes","title":"IsisInstance","text":"Name Type Description Default name str ISIS instance name. - vrf str VRF name where ISIS instance is configured. 'default' dataplane Literal['MPLS', 'mpls', 'unset'] Configured dataplane for the instance. 'MPLS'"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingTunnels","title":"VerifyISISSegmentRoutingTunnels","text":"

Verify ISIS-SR tunnels computed by device.

Expected Results
  • Success: The test will pass if all listed tunnels are computed on device.
  • Failure: The test will fail if one of the listed tunnels is missing.
  • Skipped: The test will be skipped if ISIS-SR is not configured.
Examples
anta.tests.routing:\nisis:\n    - VerifyISISSegmentRoutingTunnels:\n        entries:\n        # Check only endpoint\n        - endpoint: 1.0.0.122/32\n        # Check endpoint and via TI-LFA\n        - endpoint: 1.0.0.13/32\n          vias:\n            - type: tunnel\n              tunnel_id: ti-lfa\n        # Check endpoint and via IP routers\n        - endpoint: 1.0.0.14/32\n          vias:\n            - type: ip\n              nexthop: 1.1.1.1\n
Source code in anta/tests/routing/isis.py
class VerifyISISSegmentRoutingTunnels(AntaTest):\n    \"\"\"\n    Verify ISIS-SR tunnels computed by device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all listed tunnels are computed on device.\n    * Failure: The test will fail if one of the listed tunnels is missing.\n    * Skipped: The test will be skipped if ISIS-SR is not configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n    isis:\n        - VerifyISISSegmentRoutingTunnels:\n            entries:\n            # Check only endpoint\n            - endpoint: 1.0.0.122/32\n            # Check endpoint and via TI-LFA\n            - endpoint: 1.0.0.13/32\n              vias:\n                - type: tunnel\n                  tunnel_id: ti-lfa\n            # Check endpoint and via IP routers\n            - endpoint: 1.0.0.14/32\n              vias:\n                - type: ip\n                  nexthop: 1.1.1.1\n    ```\n    \"\"\"\n\n    name = \"VerifyISISSegmentRoutingTunnels\"\n    description = \"Verify ISIS-SR tunnels computed by device\"\n    categories: ClassVar[list[str]] = [\"isis\", \"segment-routing\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show isis segment-routing tunnel\", ofmt=\"json\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyISISSegmentRoutingTunnels test.\"\"\"\n\n        entries: list[Entry]\n        \"\"\"List of tunnels to check on device.\"\"\"\n\n        class Entry(BaseModel):\n            \"\"\"Definition of a tunnel entry.\"\"\"\n\n            endpoint: IPv4Network\n            \"\"\"Endpoint IP of the tunnel.\"\"\"\n            vias: list[Vias] | None = None\n            \"\"\"Optional list of path to reach endpoint.\"\"\"\n\n            class Vias(BaseModel):\n                \"\"\"Definition of a tunnel path.\"\"\"\n\n                nexthop: IPv4Address | None = None\n                \"\"\"Nexthop of the tunnel. If None, then it is not tested. Default: None\"\"\"\n                type: Literal[\"ip\", \"tunnel\"] | None = None\n                \"\"\"Type of the tunnel. If None, then it is not tested. Default: None\"\"\"\n                interface: Interface | None = None\n                \"\"\"Interface of the tunnel. If None, then it is not tested. Default: None\"\"\"\n                tunnel_id: Literal[\"TI-LFA\", \"ti-lfa\", \"unset\"] | None = None\n                \"\"\"Computation method of the tunnel. If None, then it is not tested. Default: None\"\"\"\n\n    def _eos_entry_lookup(self, search_value: IPv4Network, entries: dict[str, Any], search_key: str = \"endpoint\") -> dict[str, Any] | None:\n        return next(\n            (entry_value for entry_id, entry_value in entries.items() if str(entry_value[search_key]) == str(search_value)),\n            None,\n        )\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyISISSegmentRoutingTunnels.\n\n        This method performs the main test logic for verifying ISIS Segment Routing tunnels.\n        It checks the command output, initiates defaults, and performs various checks on the tunnels.\n\n        Returns\n        -------\n            None\n        \"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n\n        # initiate defaults\n        failure_message = []\n\n        if len(command_output[\"entries\"]) == 0:\n            self.result.is_skipped(\"IS-IS-SR is not running on device.\")\n            return\n\n        for input_entry in self.inputs.entries:\n            eos_entry = self._eos_entry_lookup(search_value=input_entry.endpoint, entries=command_output[\"entries\"])\n            if eos_entry is None:\n                failure_message.append(f\"Tunnel to {input_entry} is not found.\")\n            elif input_entry.vias is not None:\n                failure_src = []\n                for via_input in input_entry.vias:\n                    if not self._check_tunnel_type(via_input, eos_entry):\n                        failure_src.append(\"incorrect tunnel type\")\n                    if not self._check_tunnel_nexthop(via_input, eos_entry):\n                        failure_src.append(\"incorrect nexthop\")\n                    if not self._check_tunnel_interface(via_input, eos_entry):\n                        failure_src.append(\"incorrect interface\")\n                    if not self._check_tunnel_id(via_input, eos_entry):\n                        failure_src.append(\"incorrect tunnel ID\")\n\n                if failure_src:\n                    failure_message.append(f\"Tunnel to {input_entry.endpoint!s} is incorrect: {', '.join(failure_src)}\")\n\n        if failure_message:\n            self.result.is_failure(\"\\n\".join(failure_message))\n\n    def _check_tunnel_type(self, via_input: VerifyISISSegmentRoutingTunnels.Input.Entry.Vias, eos_entry: dict[str, Any]) -> bool:\n        \"\"\"\n        Check if the tunnel type specified in `via_input` matches any of the tunnel types in `eos_entry`.\n\n        Parameters\n        ----------\n            via_input (VerifyISISSegmentRoutingTunnels.Input.Entry.Vias): The input tunnel type to check.\n            eos_entry (dict[str, Any]): The EOS entry containing the tunnel types.\n\n        Returns\n        -------\n            bool: True if the tunnel type matches any of the tunnel types in `eos_entry`, False otherwise.\n        \"\"\"\n        if via_input.type is not None:\n            return any(\n                via_input.type\n                == get_value(\n                    dictionary=eos_via,\n                    key=\"type\",\n                    default=\"undefined\",\n                )\n                for eos_via in eos_entry[\"vias\"]\n            )\n        return True\n\n    def _check_tunnel_nexthop(self, via_input: VerifyISISSegmentRoutingTunnels.Input.Entry.Vias, eos_entry: dict[str, Any]) -> bool:\n        \"\"\"\n        Check if the tunnel nexthop matches the given input.\n\n        Parameters\n        ----------\n            via_input (VerifyISISSegmentRoutingTunnels.Input.Entry.Vias): The input via object.\n            eos_entry (dict[str, Any]): The EOS entry dictionary.\n\n        Returns\n        -------\n            bool: True if the tunnel nexthop matches, False otherwise.\n        \"\"\"\n        if via_input.nexthop is not None:\n            return any(\n                str(via_input.nexthop)\n                == get_value(\n                    dictionary=eos_via,\n                    key=\"nexthop\",\n                    default=\"undefined\",\n                )\n                for eos_via in eos_entry[\"vias\"]\n            )\n        return True\n\n    def _check_tunnel_interface(self, via_input: VerifyISISSegmentRoutingTunnels.Input.Entry.Vias, eos_entry: dict[str, Any]) -> bool:\n        \"\"\"\n        Check if the tunnel interface exists in the given EOS entry.\n\n        Parameters\n        ----------\n            via_input (VerifyISISSegmentRoutingTunnels.Input.Entry.Vias): The input via object.\n            eos_entry (dict[str, Any]): The EOS entry dictionary.\n\n        Returns\n        -------\n            bool: True if the tunnel interface exists, False otherwise.\n        \"\"\"\n        if via_input.interface is not None:\n            return any(\n                via_input.interface\n                == get_value(\n                    dictionary=eos_via,\n                    key=\"interface\",\n                    default=\"undefined\",\n                )\n                for eos_via in eos_entry[\"vias\"]\n            )\n        return True\n\n    def _check_tunnel_id(self, via_input: VerifyISISSegmentRoutingTunnels.Input.Entry.Vias, eos_entry: dict[str, Any]) -> bool:\n        \"\"\"\n        Check if the tunnel ID matches any of the tunnel IDs in the EOS entry's vias.\n\n        Parameters\n        ----------\n            via_input (VerifyISISSegmentRoutingTunnels.Input.Entry.Vias): The input vias to check.\n            eos_entry (dict[str, Any]): The EOS entry to compare against.\n\n        Returns\n        -------\n            bool: True if the tunnel ID matches any of the tunnel IDs in the EOS entry's vias, False otherwise.\n        \"\"\"\n        if via_input.tunnel_id is not None:\n            return any(\n                via_input.tunnel_id.upper()\n                == get_value(\n                    dictionary=eos_via,\n                    key=\"tunnelId.type\",\n                    default=\"undefined\",\n                ).upper()\n                for eos_via in eos_entry[\"vias\"]\n            )\n        return True\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingTunnels-attributes","title":"Inputs","text":"Name Type Description Default entries list[Entry] List of tunnels to check on device. -"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingTunnels-attributes","title":"Entry","text":"Name Type Description Default endpoint IPv4Network Endpoint IP of the tunnel. - vias list[Vias] | None Optional list of path to reach endpoint. None"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingTunnels-attributes","title":"Vias","text":"Name Type Description Default nexthop IPv4Address | None Nexthop of the tunnel. If None, then it is not tested. Default: None None type Literal['ip', 'tunnel'] | None Type of the tunnel. If None, then it is not tested. Default: None None interface Interface | None Interface of the tunnel. If None, then it is not tested. Default: None None tunnel_id Literal['TI-LFA', 'ti-lfa', 'unset'] | None Computation method of the tunnel. If None, then it is not tested. Default: None None"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis._count_isis_neighbor","title":"_count_isis_neighbor","text":"
_count_isis_neighbor(isis_neighbor_json: dict[str, Any]) -> int\n

Count the number of isis neighbors.

Args

isis_neighbor_json: The JSON output of the show isis neighbors command.

Returns:

Type Description int: The number of isis neighbors. Source code in anta/tests/routing/isis.py
def _count_isis_neighbor(isis_neighbor_json: dict[str, Any]) -> int:\n    \"\"\"Count the number of isis neighbors.\n\n    Args\n    ----\n      isis_neighbor_json: The JSON output of the `show isis neighbors` command.\n\n    Returns\n    -------\n      int: The number of isis neighbors.\n\n    \"\"\"\n    count = 0\n    for vrf_data in isis_neighbor_json[\"vrfs\"].values():\n        for instance_data in vrf_data[\"isisInstances\"].values():\n            count += len(instance_data.get(\"neighbors\", {}))\n    return count\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis._get_adjacency_segment_data_by_neighbor","title":"_get_adjacency_segment_data_by_neighbor","text":"
_get_adjacency_segment_data_by_neighbor(neighbor: str, instance: str, vrf: str, command_output: dict[str, Any]) -> dict[str, Any] | None\n

Extract data related to an IS-IS interface for testing.

Source code in anta/tests/routing/isis.py
def _get_adjacency_segment_data_by_neighbor(neighbor: str, instance: str, vrf: str, command_output: dict[str, Any]) -> dict[str, Any] | None:\n    \"\"\"Extract data related to an IS-IS interface for testing.\"\"\"\n    search_path = f\"vrfs.{vrf}.isisInstances.{instance}.adjacencySegments\"\n    if get_value(dictionary=command_output, key=search_path, default=None) is None:\n        return None\n\n    isis_instance = get_value(dictionary=command_output, key=search_path, default=None)\n\n    return next(\n        (segment_data for segment_data in isis_instance if neighbor == segment_data[\"ipAddress\"]),\n        None,\n    )\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis._get_full_isis_neighbors","title":"_get_full_isis_neighbors","text":"
_get_full_isis_neighbors(isis_neighbor_json: dict[str, Any], neighbor_state: Literal['up', 'down'] = 'up') -> list[dict[str, Any]]\n

Return the isis neighbors whose adjacency state is up.

Args

isis_neighbor_json: The JSON output of the show isis neighbors command. neighbor_state: Value of the neihbor state we are looking for. Default up

Returns:

Type Description list[dict[str, Any]]: A list of isis neighbors whose adjacency state is not `UP`. Source code in anta/tests/routing/isis.py
def _get_full_isis_neighbors(isis_neighbor_json: dict[str, Any], neighbor_state: Literal[\"up\", \"down\"] = \"up\") -> list[dict[str, Any]]:\n    \"\"\"Return the isis neighbors whose adjacency state is `up`.\n\n    Args\n    ----\n      isis_neighbor_json: The JSON output of the `show isis neighbors` command.\n      neighbor_state: Value of the neihbor state we are looking for. Default up\n\n    Returns\n    -------\n      list[dict[str, Any]]: A list of isis neighbors whose adjacency state is not `UP`.\n\n    \"\"\"\n    return [\n        {\n            \"vrf\": vrf,\n            \"instance\": instance,\n            \"neighbor\": adjacency[\"hostname\"],\n            \"neighbor_address\": adjacency[\"routerIdV4\"],\n            \"interface\": adjacency[\"interfaceName\"],\n            \"state\": state,\n        }\n        for vrf, vrf_data in isis_neighbor_json[\"vrfs\"].items()\n        for instance, instance_data in vrf_data.get(\"isisInstances\").items()\n        for neighbor, neighbor_data in instance_data.get(\"neighbors\").items()\n        for adjacency in neighbor_data.get(\"adjacencies\")\n        if (state := adjacency[\"state\"]) == neighbor_state\n    ]\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis._get_interface_data","title":"_get_interface_data","text":"
_get_interface_data(interface: str, vrf: str, command_output: dict[str, Any]) -> dict[str, Any] | None\n

Extract data related to an IS-IS interface for testing.

Source code in anta/tests/routing/isis.py
def _get_interface_data(interface: str, vrf: str, command_output: dict[str, Any]) -> dict[str, Any] | None:\n    \"\"\"Extract data related to an IS-IS interface for testing.\"\"\"\n    if (vrf_data := get_value(command_output, f\"vrfs.{vrf}\")) is None:\n        return None\n\n    for instance_data in vrf_data.get(\"isisInstances\").values():\n        if (intf_dict := get_value(dictionary=instance_data, key=\"interfaces\")) is not None:\n            try:\n                return next(ifl_data for ifl, ifl_data in intf_dict.items() if ifl == interface)\n            except StopIteration:\n                return None\n    return None\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis._get_isis_neighbors_count","title":"_get_isis_neighbors_count","text":"
_get_isis_neighbors_count(isis_neighbor_json: dict[str, Any]) -> list[dict[str, Any]]\n

Count number of IS-IS neighbor of the device.

Source code in anta/tests/routing/isis.py
def _get_isis_neighbors_count(isis_neighbor_json: dict[str, Any]) -> list[dict[str, Any]]:\n    \"\"\"Count number of IS-IS neighbor of the device.\"\"\"\n    return [\n        {\"vrf\": vrf, \"interface\": interface, \"mode\": mode, \"count\": int(level_data[\"numAdjacencies\"]), \"level\": int(level)}\n        for vrf, vrf_data in isis_neighbor_json[\"vrfs\"].items()\n        for instance, instance_data in vrf_data.get(\"isisInstances\").items()\n        for interface, interface_data in instance_data.get(\"interfaces\").items()\n        for level, level_data in interface_data.get(\"intfLevels\").items()\n        if (mode := level_data[\"passive\"]) is not True\n    ]\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis._get_not_full_isis_neighbors","title":"_get_not_full_isis_neighbors","text":"
_get_not_full_isis_neighbors(isis_neighbor_json: dict[str, Any]) -> list[dict[str, Any]]\n

Return the isis neighbors whose adjacency state is not up.

Args

isis_neighbor_json: The JSON output of the show isis neighbors command.

Returns:

Type Description list[dict[str, Any]]: A list of isis neighbors whose adjacency state is not `UP`. Source code in anta/tests/routing/isis.py
def _get_not_full_isis_neighbors(isis_neighbor_json: dict[str, Any]) -> list[dict[str, Any]]:\n    \"\"\"Return the isis neighbors whose adjacency state is not `up`.\n\n    Args\n    ----\n      isis_neighbor_json: The JSON output of the `show isis neighbors` command.\n\n    Returns\n    -------\n      list[dict[str, Any]]: A list of isis neighbors whose adjacency state is not `UP`.\n\n    \"\"\"\n    return [\n        {\n            \"vrf\": vrf,\n            \"instance\": instance,\n            \"neighbor\": adjacency[\"hostname\"],\n            \"state\": state,\n        }\n        for vrf, vrf_data in isis_neighbor_json[\"vrfs\"].items()\n        for instance, instance_data in vrf_data.get(\"isisInstances\").items()\n        for neighbor, neighbor_data in instance_data.get(\"neighbors\").items()\n        for adjacency in neighbor_data.get(\"adjacencies\")\n        if (state := adjacency[\"state\"]) != \"up\"\n    ]\n
"},{"location":"api/tests.routing.ospf/","title":"OSPF","text":""},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf.VerifyOSPFMaxLSA","title":"VerifyOSPFMaxLSA","text":"

Verifies LSAs present in the OSPF link state database did not cross the maximum LSA Threshold.

Expected Results
  • Success: The test will pass if all OSPF instances did not cross the maximum LSA Threshold.
  • Failure: The test will fail if some OSPF instances crossed the maximum LSA Threshold.
  • Skipped: The test will be skipped if no OSPF instance is found.
Examples
anta.tests.routing:\n  ospf:\n    - VerifyOSPFMaxLSA:\n
Source code in anta/tests/routing/ospf.py
class VerifyOSPFMaxLSA(AntaTest):\n    \"\"\"Verifies LSAs present in the OSPF link state database did not cross the maximum LSA Threshold.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all OSPF instances did not cross the maximum LSA Threshold.\n    * Failure: The test will fail if some OSPF instances crossed the maximum LSA Threshold.\n    * Skipped: The test will be skipped if no OSPF instance is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      ospf:\n        - VerifyOSPFMaxLSA:\n    ```\n    \"\"\"\n\n    name = \"VerifyOSPFMaxLSA\"\n    description = \"Verifies all OSPF instances did not cross the maximum LSA threshold.\"\n    categories: ClassVar[list[str]] = [\"ospf\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip ospf\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyOSPFMaxLSA.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ospf_instance_info = _get_ospf_max_lsa_info(command_output)\n        if not ospf_instance_info:\n            self.result.is_skipped(\"No OSPF instance found.\")\n            return\n        all_instances_within_threshold = all(instance[\"numLsa\"] <= instance[\"maxLsa\"] * (instance[\"maxLsaThreshold\"] / 100) for instance in ospf_instance_info)\n        if all_instances_within_threshold:\n            self.result.is_success()\n        else:\n            exceeded_instances = [\n                instance[\"instance\"] for instance in ospf_instance_info if instance[\"numLsa\"] > instance[\"maxLsa\"] * (instance[\"maxLsaThreshold\"] / 100)\n            ]\n            self.result.is_failure(f\"OSPF Instances {exceeded_instances} crossed the maximum LSA threshold.\")\n
"},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf.VerifyOSPFNeighborCount","title":"VerifyOSPFNeighborCount","text":"

Verifies the number of OSPF neighbors in FULL state is the one we expect.

Expected Results
  • Success: The test will pass if the number of OSPF neighbors in FULL state is the one we expect.
  • Failure: The test will fail if the number of OSPF neighbors in FULL state is not the one we expect.
  • Skipped: The test will be skipped if no OSPF neighbor is found.
Examples
anta.tests.routing:\n  ospf:\n    - VerifyOSPFNeighborCount:\n        number: 3\n
Source code in anta/tests/routing/ospf.py
class VerifyOSPFNeighborCount(AntaTest):\n    \"\"\"Verifies the number of OSPF neighbors in FULL state is the one we expect.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the number of OSPF neighbors in FULL state is the one we expect.\n    * Failure: The test will fail if the number of OSPF neighbors in FULL state is not the one we expect.\n    * Skipped: The test will be skipped if no OSPF neighbor is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      ospf:\n        - VerifyOSPFNeighborCount:\n            number: 3\n    ```\n    \"\"\"\n\n    name = \"VerifyOSPFNeighborCount\"\n    description = \"Verifies the number of OSPF neighbors in FULL state is the one we expect.\"\n    categories: ClassVar[list[str]] = [\"ospf\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip ospf neighbor\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyOSPFNeighborCount test.\"\"\"\n\n        number: int\n        \"\"\"The expected number of OSPF neighbors in FULL state.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyOSPFNeighborCount.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if (neighbor_count := _count_ospf_neighbor(command_output)) == 0:\n            self.result.is_skipped(\"no OSPF neighbor found\")\n            return\n        self.result.is_success()\n        if neighbor_count != self.inputs.number:\n            self.result.is_failure(f\"device has {neighbor_count} neighbors (expected {self.inputs.number})\")\n        not_full_neighbors = _get_not_full_ospf_neighbors(command_output)\n        if not_full_neighbors:\n            self.result.is_failure(f\"Some neighbors are not correctly configured: {not_full_neighbors}.\")\n
"},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf.VerifyOSPFNeighborCount-attributes","title":"Inputs","text":"Name Type Description Default number int The expected number of OSPF neighbors in FULL state. -"},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf.VerifyOSPFNeighborState","title":"VerifyOSPFNeighborState","text":"

Verifies all OSPF neighbors are in FULL state.

Expected Results
  • Success: The test will pass if all OSPF neighbors are in FULL state.
  • Failure: The test will fail if some OSPF neighbors are not in FULL state.
  • Skipped: The test will be skipped if no OSPF neighbor is found.
Examples
anta.tests.routing:\n  ospf:\n    - VerifyOSPFNeighborState:\n
Source code in anta/tests/routing/ospf.py
class VerifyOSPFNeighborState(AntaTest):\n    \"\"\"Verifies all OSPF neighbors are in FULL state.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all OSPF neighbors are in FULL state.\n    * Failure: The test will fail if some OSPF neighbors are not in FULL state.\n    * Skipped: The test will be skipped if no OSPF neighbor is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      ospf:\n        - VerifyOSPFNeighborState:\n    ```\n    \"\"\"\n\n    name = \"VerifyOSPFNeighborState\"\n    description = \"Verifies all OSPF neighbors are in FULL state.\"\n    categories: ClassVar[list[str]] = [\"ospf\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip ospf neighbor\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyOSPFNeighborState.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if _count_ospf_neighbor(command_output) == 0:\n            self.result.is_skipped(\"no OSPF neighbor found\")\n            return\n        self.result.is_success()\n        not_full_neighbors = _get_not_full_ospf_neighbors(command_output)\n        if not_full_neighbors:\n            self.result.is_failure(f\"Some neighbors are not correctly configured: {not_full_neighbors}.\")\n
"},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf._count_ospf_neighbor","title":"_count_ospf_neighbor","text":"
_count_ospf_neighbor(ospf_neighbor_json: dict[str, Any]) -> int\n

Count the number of OSPF neighbors.

Returns:

Type Description int: The number of OSPF neighbors. Source code in anta/tests/routing/ospf.py
def _count_ospf_neighbor(ospf_neighbor_json: dict[str, Any]) -> int:\n    \"\"\"Count the number of OSPF neighbors.\n\n    Parameters\n    ----------\n      ospf_neighbor_json: The JSON output of the `show ip ospf neighbor` command.\n\n    Returns\n    -------\n      int: The number of OSPF neighbors.\n\n    \"\"\"\n    count = 0\n    for vrf_data in ospf_neighbor_json[\"vrfs\"].values():\n        for instance_data in vrf_data[\"instList\"].values():\n            count += len(instance_data.get(\"ospfNeighborEntries\", []))\n    return count\n
"},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf._get_not_full_ospf_neighbors","title":"_get_not_full_ospf_neighbors","text":"
_get_not_full_ospf_neighbors(ospf_neighbor_json: dict[str, Any]) -> list[dict[str, Any]]\n

Return the OSPF neighbors whose adjacency state is not full.

Returns:

Type Description list[dict[str, Any]]: A list of OSPF neighbors whose adjacency state is not `full`. Source code in anta/tests/routing/ospf.py
def _get_not_full_ospf_neighbors(ospf_neighbor_json: dict[str, Any]) -> list[dict[str, Any]]:\n    \"\"\"Return the OSPF neighbors whose adjacency state is not `full`.\n\n    Parameters\n    ----------\n      ospf_neighbor_json: The JSON output of the `show ip ospf neighbor` command.\n\n    Returns\n    -------\n      list[dict[str, Any]]: A list of OSPF neighbors whose adjacency state is not `full`.\n\n    \"\"\"\n    return [\n        {\n            \"vrf\": vrf,\n            \"instance\": instance,\n            \"neighbor\": neighbor_data[\"routerId\"],\n            \"state\": state,\n        }\n        for vrf, vrf_data in ospf_neighbor_json[\"vrfs\"].items()\n        for instance, instance_data in vrf_data[\"instList\"].items()\n        for neighbor_data in instance_data.get(\"ospfNeighborEntries\", [])\n        if (state := neighbor_data[\"adjacencyState\"]) != \"full\"\n    ]\n
"},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf._get_ospf_max_lsa_info","title":"_get_ospf_max_lsa_info","text":"
_get_ospf_max_lsa_info(ospf_process_json: dict[str, Any]) -> list[dict[str, Any]]\n

Return information about OSPF instances and their LSAs.

Returns:

Type Description list[dict[str, Any]]: A list of dictionaries containing OSPF LSAs information. Source code in anta/tests/routing/ospf.py
def _get_ospf_max_lsa_info(ospf_process_json: dict[str, Any]) -> list[dict[str, Any]]:\n    \"\"\"Return information about OSPF instances and their LSAs.\n\n    Parameters\n    ----------\n      ospf_process_json: OSPF process information in JSON format.\n\n    Returns\n    -------\n      list[dict[str, Any]]: A list of dictionaries containing OSPF LSAs information.\n\n    \"\"\"\n    return [\n        {\n            \"vrf\": vrf,\n            \"instance\": instance,\n            \"maxLsa\": instance_data.get(\"maxLsaInformation\", {}).get(\"maxLsa\"),\n            \"maxLsaThreshold\": instance_data.get(\"maxLsaInformation\", {}).get(\"maxLsaThreshold\"),\n            \"numLsa\": instance_data.get(\"lsaInformation\", {}).get(\"numLsa\"),\n        }\n        for vrf, vrf_data in ospf_process_json.get(\"vrfs\", {}).items()\n        for instance, instance_data in vrf_data.get(\"instList\", {}).items()\n    ]\n
"},{"location":"api/tests.security/","title":"Security","text":""},{"location":"api/tests.security/#anta.tests.security.VerifyAPIHttpStatus","title":"VerifyAPIHttpStatus","text":"

Verifies if eAPI HTTP server is disabled globally.

Expected Results
  • Success: The test will pass if eAPI HTTP server is disabled globally.
  • Failure: The test will fail if eAPI HTTP server is NOT disabled globally.
Examples
anta.tests.security:\n  - VerifyAPIHttpStatus:\n
Source code in anta/tests/security.py
class VerifyAPIHttpStatus(AntaTest):\n    \"\"\"Verifies if eAPI HTTP server is disabled globally.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if eAPI HTTP server is disabled globally.\n    * Failure: The test will fail if eAPI HTTP server is NOT disabled globally.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyAPIHttpStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifyAPIHttpStatus\"\n    description = \"Verifies if eAPI HTTP server is disabled globally.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management api http-commands\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAPIHttpStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"enabled\"] and not command_output[\"httpServer\"][\"running\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"eAPI HTTP server is enabled globally\")\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyAPIHttpsSSL","title":"VerifyAPIHttpsSSL","text":"

Verifies if eAPI HTTPS server SSL profile is configured and valid.

Expected Results
  • Success: The test will pass if the eAPI HTTPS server SSL profile is configured and valid.
  • Failure: The test will fail if the eAPI HTTPS server SSL profile is NOT configured, misconfigured or invalid.
Examples
anta.tests.security:\n  - VerifyAPIHttpsSSL:\n      profile: default\n
Source code in anta/tests/security.py
class VerifyAPIHttpsSSL(AntaTest):\n    \"\"\"Verifies if eAPI HTTPS server SSL profile is configured and valid.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the eAPI HTTPS server SSL profile is configured and valid.\n    * Failure: The test will fail if the eAPI HTTPS server SSL profile is NOT configured, misconfigured or invalid.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyAPIHttpsSSL:\n          profile: default\n    ```\n    \"\"\"\n\n    name = \"VerifyAPIHttpsSSL\"\n    description = \"Verifies if the eAPI has a valid SSL profile.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management api http-commands\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAPIHttpsSSL test.\"\"\"\n\n        profile: str\n        \"\"\"SSL profile to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAPIHttpsSSL.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        try:\n            if command_output[\"sslProfile\"][\"name\"] == self.inputs.profile and command_output[\"sslProfile\"][\"state\"] == \"valid\":\n                self.result.is_success()\n            else:\n                self.result.is_failure(f\"eAPI HTTPS server SSL profile ({self.inputs.profile}) is misconfigured or invalid\")\n\n        except KeyError:\n            self.result.is_failure(f\"eAPI HTTPS server SSL profile ({self.inputs.profile}) is not configured\")\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyAPIHttpsSSL-attributes","title":"Inputs","text":"Name Type Description Default profile str SSL profile to verify. -"},{"location":"api/tests.security/#anta.tests.security.VerifyAPIIPv4Acl","title":"VerifyAPIIPv4Acl","text":"

Verifies if eAPI has the right number IPv4 ACL(s) configured for a specified VRF.

Expected Results
  • Success: The test will pass if eAPI has the provided number of IPv4 ACL(s) in the specified VRF.
  • Failure: The test will fail if eAPI has not the right number of IPv4 ACL(s) in the specified VRF.
Examples
anta.tests.security:\n  - VerifyAPIIPv4Acl:\n      number: 3\n      vrf: default\n
Source code in anta/tests/security.py
class VerifyAPIIPv4Acl(AntaTest):\n    \"\"\"Verifies if eAPI has the right number IPv4 ACL(s) configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if eAPI has the provided number of IPv4 ACL(s) in the specified VRF.\n    * Failure: The test will fail if eAPI has not the right number of IPv4 ACL(s) in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyAPIIPv4Acl:\n          number: 3\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyAPIIPv4Acl\"\n    description = \"Verifies if eAPI has the right number IPv4 ACL(s) configured for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management api http-commands ip access-list summary\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input parameters for the VerifyAPIIPv4Acl test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"The number of expected IPv4 ACL(s).\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for eAPI. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAPIIPv4Acl.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ipv4_acl_list = command_output[\"ipAclList\"][\"aclList\"]\n        ipv4_acl_number = len(ipv4_acl_list)\n        if ipv4_acl_number != self.inputs.number:\n            self.result.is_failure(f\"Expected {self.inputs.number} eAPI IPv4 ACL(s) in vrf {self.inputs.vrf} but got {ipv4_acl_number}\")\n            return\n\n        not_configured_acl = [acl[\"name\"] for acl in ipv4_acl_list if self.inputs.vrf not in acl[\"configuredVrfs\"] or self.inputs.vrf not in acl[\"activeVrfs\"]]\n\n        if not_configured_acl:\n            self.result.is_failure(f\"eAPI IPv4 ACL(s) not configured or active in vrf {self.inputs.vrf}: {not_configured_acl}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyAPIIPv4Acl-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger The number of expected IPv4 ACL(s). - vrf str The name of the VRF in which to check for eAPI. Defaults to `default` VRF. 'default'"},{"location":"api/tests.security/#anta.tests.security.VerifyAPIIPv6Acl","title":"VerifyAPIIPv6Acl","text":"

Verifies if eAPI has the right number IPv6 ACL(s) configured for a specified VRF.

Expected Results
  • Success: The test will pass if eAPI has the provided number of IPv6 ACL(s) in the specified VRF.
  • Failure: The test will fail if eAPI has not the right number of IPv6 ACL(s) in the specified VRF.
  • Skipped: The test will be skipped if the number of IPv6 ACL(s) or VRF parameter is not provided.
Examples
anta.tests.security:\n  - VerifyAPIIPv6Acl:\n      number: 3\n      vrf: default\n
Source code in anta/tests/security.py
class VerifyAPIIPv6Acl(AntaTest):\n    \"\"\"Verifies if eAPI has the right number IPv6 ACL(s) configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if eAPI has the provided number of IPv6 ACL(s) in the specified VRF.\n    * Failure: The test will fail if eAPI has not the right number of IPv6 ACL(s) in the specified VRF.\n    * Skipped: The test will be skipped if the number of IPv6 ACL(s) or VRF parameter is not provided.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyAPIIPv6Acl:\n          number: 3\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyAPIIPv6Acl\"\n    description = \"Verifies if eAPI has the right number IPv6 ACL(s) configured for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management api http-commands ipv6 access-list summary\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input parameters for the VerifyAPIIPv6Acl test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"The number of expected IPv6 ACL(s).\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for eAPI. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAPIIPv6Acl.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ipv6_acl_list = command_output[\"ipv6AclList\"][\"aclList\"]\n        ipv6_acl_number = len(ipv6_acl_list)\n        if ipv6_acl_number != self.inputs.number:\n            self.result.is_failure(f\"Expected {self.inputs.number} eAPI IPv6 ACL(s) in vrf {self.inputs.vrf} but got {ipv6_acl_number}\")\n            return\n\n        not_configured_acl = [acl[\"name\"] for acl in ipv6_acl_list if self.inputs.vrf not in acl[\"configuredVrfs\"] or self.inputs.vrf not in acl[\"activeVrfs\"]]\n\n        if not_configured_acl:\n            self.result.is_failure(f\"eAPI IPv6 ACL(s) not configured or active in vrf {self.inputs.vrf}: {not_configured_acl}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyAPIIPv6Acl-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger The number of expected IPv6 ACL(s). - vrf str The name of the VRF in which to check for eAPI. Defaults to `default` VRF. 'default'"},{"location":"api/tests.security/#anta.tests.security.VerifyAPISSLCertificate","title":"VerifyAPISSLCertificate","text":"

Verifies the eAPI SSL certificate expiry, common subject name, encryption algorithm and key size.

Expected Results
  • Success: The test will pass if the certificate\u2019s expiry date is greater than the threshold, and the certificate has the correct name, encryption algorithm, and key size.
  • Failure: The test will fail if the certificate is expired or is going to expire, or if the certificate has an incorrect name, encryption algorithm, or key size.
Examples
anta.tests.security:\n  - VerifyAPISSLCertificate:\n      certificates:\n        - certificate_name: ARISTA_SIGNING_CA.crt\n          expiry_threshold: 30\n          common_name: AristaIT-ICA ECDSA Issuing Cert Authority\n          encryption_algorithm: ECDSA\n          key_size: 256\n        - certificate_name: ARISTA_ROOT_CA.crt\n          expiry_threshold: 30\n          common_name: Arista Networks Internal IT Root Cert Authority\n          encryption_algorithm: RSA\n          key_size: 4096\n
Source code in anta/tests/security.py
class VerifyAPISSLCertificate(AntaTest):\n    \"\"\"Verifies the eAPI SSL certificate expiry, common subject name, encryption algorithm and key size.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the certificate's expiry date is greater than the threshold,\n                   and the certificate has the correct name, encryption algorithm, and key size.\n    * Failure: The test will fail if the certificate is expired or is going to expire,\n                   or if the certificate has an incorrect name, encryption algorithm, or key size.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyAPISSLCertificate:\n          certificates:\n            - certificate_name: ARISTA_SIGNING_CA.crt\n              expiry_threshold: 30\n              common_name: AristaIT-ICA ECDSA Issuing Cert Authority\n              encryption_algorithm: ECDSA\n              key_size: 256\n            - certificate_name: ARISTA_ROOT_CA.crt\n              expiry_threshold: 30\n              common_name: Arista Networks Internal IT Root Cert Authority\n              encryption_algorithm: RSA\n              key_size: 4096\n    ```\n    \"\"\"\n\n    name = \"VerifyAPISSLCertificate\"\n    description = \"Verifies the eAPI SSL certificate expiry, common subject name, encryption algorithm and key size.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"show management security ssl certificate\", revision=1),\n        AntaCommand(command=\"show clock\", revision=1),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input parameters for the VerifyAPISSLCertificate test.\"\"\"\n\n        certificates: list[APISSLCertificate]\n        \"\"\"List of API SSL certificates.\"\"\"\n\n        class APISSLCertificate(BaseModel):\n            \"\"\"Model for an API SSL certificate.\"\"\"\n\n            certificate_name: str\n            \"\"\"The name of the certificate to be verified.\"\"\"\n            expiry_threshold: int\n            \"\"\"The expiry threshold of the certificate in days.\"\"\"\n            common_name: str\n            \"\"\"The common subject name of the certificate.\"\"\"\n            encryption_algorithm: EncryptionAlgorithm\n            \"\"\"The encryption algorithm of the certificate.\"\"\"\n            key_size: RsaKeySize | EcdsaKeySize\n            \"\"\"The encryption algorithm key size of the certificate.\"\"\"\n\n            @model_validator(mode=\"after\")\n            def validate_inputs(self: BaseModel) -> BaseModel:\n                \"\"\"Validate the key size provided to the APISSLCertificates class.\n\n                If encryption_algorithm is RSA then key_size should be in {2048, 3072, 4096}.\n\n                If encryption_algorithm is ECDSA then key_size should be in {256, 384, 521}.\n                \"\"\"\n                if self.encryption_algorithm == \"RSA\" and self.key_size not in RsaKeySize.__args__:\n                    msg = f\"`{self.certificate_name}` key size {self.key_size} is invalid for RSA encryption. Allowed sizes are {RsaKeySize.__args__}.\"\n                    raise ValueError(msg)\n\n                if self.encryption_algorithm == \"ECDSA\" and self.key_size not in EcdsaKeySize.__args__:\n                    msg = f\"`{self.certificate_name}` key size {self.key_size} is invalid for ECDSA encryption. Allowed sizes are {EcdsaKeySize.__args__}.\"\n                    raise ValueError(msg)\n\n                return self\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAPISSLCertificate.\"\"\"\n        # Mark the result as success by default\n        self.result.is_success()\n\n        # Extract certificate and clock output\n        certificate_output = self.instance_commands[0].json_output\n        clock_output = self.instance_commands[1].json_output\n        current_timestamp = clock_output[\"utcTime\"]\n\n        # Iterate over each API SSL certificate\n        for certificate in self.inputs.certificates:\n            # Collecting certificate expiry time and current EOS time.\n            # These times are used to calculate the number of days until the certificate expires.\n            if not (certificate_data := get_value(certificate_output, f\"certificates..{certificate.certificate_name}\", separator=\"..\")):\n                self.result.is_failure(f\"SSL certificate '{certificate.certificate_name}', is not configured.\\n\")\n                continue\n\n            expiry_time = certificate_data[\"notAfter\"]\n            day_difference = (datetime.fromtimestamp(expiry_time, tz=timezone.utc) - datetime.fromtimestamp(current_timestamp, tz=timezone.utc)).days\n\n            # Verify certificate expiry\n            if 0 < day_difference < certificate.expiry_threshold:\n                self.result.is_failure(f\"SSL certificate `{certificate.certificate_name}` is about to expire in {day_difference} days.\\n\")\n            elif day_difference < 0:\n                self.result.is_failure(f\"SSL certificate `{certificate.certificate_name}` is expired.\\n\")\n\n            # Verify certificate common subject name, encryption algorithm and key size\n            keys_to_verify = [\"subject.commonName\", \"publicKey.encryptionAlgorithm\", \"publicKey.size\"]\n            actual_certificate_details = {key: get_value(certificate_data, key) for key in keys_to_verify}\n\n            expected_certificate_details = {\n                \"subject.commonName\": certificate.common_name,\n                \"publicKey.encryptionAlgorithm\": certificate.encryption_algorithm,\n                \"publicKey.size\": certificate.key_size,\n            }\n\n            if actual_certificate_details != expected_certificate_details:\n                failed_log = f\"SSL certificate `{certificate.certificate_name}` is not configured properly:\"\n                failed_log += get_failed_logs(expected_certificate_details, actual_certificate_details)\n                self.result.is_failure(f\"{failed_log}\\n\")\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyAPISSLCertificate-attributes","title":"Inputs","text":"Name Type Description Default certificates list[APISSLCertificate] List of API SSL certificates. -"},{"location":"api/tests.security/#anta.tests.security.VerifyAPISSLCertificate-attributes","title":"APISSLCertificate","text":"Name Type Description Default certificate_name str The name of the certificate to be verified. - expiry_threshold int The expiry threshold of the certificate in days. - common_name str The common subject name of the certificate. - encryption_algorithm EncryptionAlgorithm The encryption algorithm of the certificate. - key_size RsaKeySize | EcdsaKeySize The encryption algorithm key size of the certificate. -"},{"location":"api/tests.security/#anta.tests.security.VerifyBannerLogin","title":"VerifyBannerLogin","text":"

Verifies the login banner of a device.

Expected Results
  • Success: The test will pass if the login banner matches the provided input.
  • Failure: The test will fail if the login banner does not match the provided input.
Examples
anta.tests.security:\n  - VerifyBannerLogin:\n        login_banner: |\n            # Copyright (c) 2023-2024 Arista Networks, Inc.\n            # Use of this source code is governed by the Apache License 2.0\n            # that can be found in the LICENSE file.\n
Source code in anta/tests/security.py
class VerifyBannerLogin(AntaTest):\n    \"\"\"Verifies the login banner of a device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the login banner matches the provided input.\n    * Failure: The test will fail if the login banner does not match the provided input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyBannerLogin:\n            login_banner: |\n                # Copyright (c) 2023-2024 Arista Networks, Inc.\n                # Use of this source code is governed by the Apache License 2.0\n                # that can be found in the LICENSE file.\n    ```\n    \"\"\"\n\n    name = \"VerifyBannerLogin\"\n    description = \"Verifies the login banner of a device.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show banner login\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBannerLogin test.\"\"\"\n\n        login_banner: str\n        \"\"\"Expected login banner of the device.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBannerLogin.\"\"\"\n        login_banner = self.instance_commands[0].json_output[\"loginBanner\"]\n\n        # Remove leading and trailing whitespaces from each line\n        cleaned_banner = \"\\n\".join(line.strip() for line in self.inputs.login_banner.split(\"\\n\"))\n        if login_banner != cleaned_banner:\n            self.result.is_failure(f\"Expected `{cleaned_banner}` as the login banner, but found `{login_banner}` instead.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyBannerLogin-attributes","title":"Inputs","text":"Name Type Description Default login_banner str Expected login banner of the device. -"},{"location":"api/tests.security/#anta.tests.security.VerifyBannerMotd","title":"VerifyBannerMotd","text":"

Verifies the motd banner of a device.

Expected Results
  • Success: The test will pass if the motd banner matches the provided input.
  • Failure: The test will fail if the motd banner does not match the provided input.
Examples
anta.tests.security:\n  - VerifyBannerMotd:\n        motd_banner: |\n            # Copyright (c) 2023-2024 Arista Networks, Inc.\n            # Use of this source code is governed by the Apache License 2.0\n            # that can be found in the LICENSE file.\n
Source code in anta/tests/security.py
class VerifyBannerMotd(AntaTest):\n    \"\"\"Verifies the motd banner of a device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the motd banner matches the provided input.\n    * Failure: The test will fail if the motd banner does not match the provided input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyBannerMotd:\n            motd_banner: |\n                # Copyright (c) 2023-2024 Arista Networks, Inc.\n                # Use of this source code is governed by the Apache License 2.0\n                # that can be found in the LICENSE file.\n    ```\n    \"\"\"\n\n    name = \"VerifyBannerMotd\"\n    description = \"Verifies the motd banner of a device.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show banner motd\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBannerMotd test.\"\"\"\n\n        motd_banner: str\n        \"\"\"Expected motd banner of the device.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBannerMotd.\"\"\"\n        motd_banner = self.instance_commands[0].json_output[\"motd\"]\n\n        # Remove leading and trailing whitespaces from each line\n        cleaned_banner = \"\\n\".join(line.strip() for line in self.inputs.motd_banner.split(\"\\n\"))\n        if motd_banner != cleaned_banner:\n            self.result.is_failure(f\"Expected `{cleaned_banner}` as the motd banner, but found `{motd_banner}` instead.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyBannerMotd-attributes","title":"Inputs","text":"Name Type Description Default motd_banner str Expected motd banner of the device. -"},{"location":"api/tests.security/#anta.tests.security.VerifyIPSecConnHealth","title":"VerifyIPSecConnHealth","text":"

Verifies all IPv4 security connections.

Expected Results
  • Success: The test will pass if all the IPv4 security connections are established in all vrf.
  • Failure: The test will fail if IPv4 security is not configured or any of IPv4 security connections are not established in any vrf.
Examples
anta.tests.security:\n  - VerifyIPSecConnHealth:\n
Source code in anta/tests/security.py
class VerifyIPSecConnHealth(AntaTest):\n    \"\"\"\n    Verifies all IPv4 security connections.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all the IPv4 security connections are established in all vrf.\n    * Failure: The test will fail if IPv4 security is not configured or any of IPv4 security connections are not established in any vrf.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyIPSecConnHealth:\n    ```\n    \"\"\"\n\n    name = \"VerifyIPSecConnHealth\"\n    description = \"Verifies all IPv4 security connections.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip security connection vrf all\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIPSecConnHealth.\"\"\"\n        self.result.is_success()\n        failure_conn = []\n        command_output = self.instance_commands[0].json_output[\"connections\"]\n\n        # Check if IP security connection is configured\n        if not command_output:\n            self.result.is_failure(\"No IPv4 security connection configured.\")\n            return\n\n        # Iterate over all ipsec connections\n        for conn_data in command_output.values():\n            state = next(iter(conn_data[\"pathDict\"].values()))\n            if state != \"Established\":\n                source = conn_data.get(\"saddr\")\n                destination = conn_data.get(\"daddr\")\n                vrf = conn_data.get(\"tunnelNs\")\n                failure_conn.append(f\"source:{source} destination:{destination} vrf:{vrf}\")\n        if failure_conn:\n            failure_msg = \"\\n\".join(failure_conn)\n            self.result.is_failure(f\"The following IPv4 security connections are not established:\\n{failure_msg}.\")\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyIPv4ACL","title":"VerifyIPv4ACL","text":"

Verifies the configuration of IPv4 ACLs.

Expected Results
  • Success: The test will pass if an IPv4 ACL is configured with the correct sequence entries.
  • Failure: The test will fail if an IPv4 ACL is not configured or entries are not in sequence.
Examples
anta.tests.security:\n  - VerifyIPv4ACL:\n      ipv4_access_lists:\n        - name: default-control-plane-acl\n          entries:\n            - sequence: 10\n              action: permit icmp any any\n            - sequence: 20\n              action: permit ip any any tracked\n            - sequence: 30\n              action: permit udp any any eq bfd ttl eq 255\n        - name: LabTest\n          entries:\n            - sequence: 10\n              action: permit icmp any any\n            - sequence: 20\n              action: permit tcp any any range 5900 5910\n
Source code in anta/tests/security.py
class VerifyIPv4ACL(AntaTest):\n    \"\"\"Verifies the configuration of IPv4 ACLs.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if an IPv4 ACL is configured with the correct sequence entries.\n    * Failure: The test will fail if an IPv4 ACL is not configured or entries are not in sequence.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyIPv4ACL:\n          ipv4_access_lists:\n            - name: default-control-plane-acl\n              entries:\n                - sequence: 10\n                  action: permit icmp any any\n                - sequence: 20\n                  action: permit ip any any tracked\n                - sequence: 30\n                  action: permit udp any any eq bfd ttl eq 255\n            - name: LabTest\n              entries:\n                - sequence: 10\n                  action: permit icmp any any\n                - sequence: 20\n                  action: permit tcp any any range 5900 5910\n    ```\n    \"\"\"\n\n    name = \"VerifyIPv4ACL\"\n    description = \"Verifies the configuration of IPv4 ACLs.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show ip access-lists {acl}\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyIPv4ACL test.\"\"\"\n\n        ipv4_access_lists: list[IPv4ACL]\n        \"\"\"List of IPv4 ACLs to verify.\"\"\"\n\n        class IPv4ACL(BaseModel):\n            \"\"\"Model for an IPv4 ACL.\"\"\"\n\n            name: str\n            \"\"\"Name of IPv4 ACL.\"\"\"\n\n            entries: list[IPv4ACLEntry]\n            \"\"\"List of IPv4 ACL entries.\"\"\"\n\n            class IPv4ACLEntry(BaseModel):\n                \"\"\"Model for an IPv4 ACL entry.\"\"\"\n\n                sequence: int = Field(ge=1, le=4294967295)\n                \"\"\"Sequence number of an ACL entry.\"\"\"\n                action: str\n                \"\"\"Action of an ACL entry.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each input ACL.\"\"\"\n        return [template.render(acl=acl.name) for acl in self.inputs.ipv4_access_lists]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIPv4ACL.\"\"\"\n        self.result.is_success()\n        for command_output, acl in zip(self.instance_commands, self.inputs.ipv4_access_lists):\n            # Collecting input ACL details\n            acl_name = command_output.params.acl\n            # Retrieve the expected entries from the inputs\n            acl_entries = acl.entries\n\n            # Check if ACL is configured\n            ipv4_acl_list = command_output.json_output[\"aclList\"]\n            if not ipv4_acl_list:\n                self.result.is_failure(f\"{acl_name}: Not found\")\n                continue\n\n            # Check if the sequence number is configured and has the correct action applied\n            failed_log = f\"{acl_name}:\\n\"\n            for acl_entry in acl_entries:\n                acl_seq = acl_entry.sequence\n                acl_action = acl_entry.action\n                if (actual_entry := get_item(ipv4_acl_list[0][\"sequence\"], \"sequenceNumber\", acl_seq)) is None:\n                    failed_log += f\"Sequence number `{acl_seq}` is not found.\\n\"\n                    continue\n\n                if actual_entry[\"text\"] != acl_action:\n                    failed_log += f\"Expected `{acl_action}` as sequence number {acl_seq} action but found `{actual_entry['text']}` instead.\\n\"\n\n            if failed_log != f\"{acl_name}:\\n\":\n                self.result.is_failure(f\"{failed_log}\")\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyIPv4ACL-attributes","title":"Inputs","text":"Name Type Description Default ipv4_access_lists list[IPv4ACL] List of IPv4 ACLs to verify. -"},{"location":"api/tests.security/#anta.tests.security.VerifyIPv4ACL-attributes","title":"IPv4ACL","text":"Name Type Description Default name str Name of IPv4 ACL. - entries list[IPv4ACLEntry] List of IPv4 ACL entries. -"},{"location":"api/tests.security/#anta.tests.security.VerifyIPv4ACL-attributes","title":"IPv4ACLEntry","text":"Name Type Description Default sequence int Sequence number of an ACL entry. Field(ge=1, le=4294967295) action str Action of an ACL entry. -"},{"location":"api/tests.security/#anta.tests.security.VerifySSHIPv4Acl","title":"VerifySSHIPv4Acl","text":"

Verifies if the SSHD agent has the right number IPv4 ACL(s) configured for a specified VRF.

Expected Results
  • Success: The test will pass if the SSHD agent has the provided number of IPv4 ACL(s) in the specified VRF.
  • Failure: The test will fail if the SSHD agent has not the right number of IPv4 ACL(s) in the specified VRF.
Examples
anta.tests.security:\n  - VerifySSHIPv4Acl:\n      number: 3\n      vrf: default\n
Source code in anta/tests/security.py
class VerifySSHIPv4Acl(AntaTest):\n    \"\"\"Verifies if the SSHD agent has the right number IPv4 ACL(s) configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SSHD agent has the provided number of IPv4 ACL(s) in the specified VRF.\n    * Failure: The test will fail if the SSHD agent has not the right number of IPv4 ACL(s) in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifySSHIPv4Acl:\n          number: 3\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifySSHIPv4Acl\"\n    description = \"Verifies if the SSHD agent has IPv4 ACL(s) configured.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management ssh ip access-list summary\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySSHIPv4Acl test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"The number of expected IPv4 ACL(s).\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for the SSHD agent. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySSHIPv4Acl.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ipv4_acl_list = command_output[\"ipAclList\"][\"aclList\"]\n        ipv4_acl_number = len(ipv4_acl_list)\n        if ipv4_acl_number != self.inputs.number:\n            self.result.is_failure(f\"Expected {self.inputs.number} SSH IPv4 ACL(s) in vrf {self.inputs.vrf} but got {ipv4_acl_number}\")\n            return\n\n        not_configured_acl = [acl[\"name\"] for acl in ipv4_acl_list if self.inputs.vrf not in acl[\"configuredVrfs\"] or self.inputs.vrf not in acl[\"activeVrfs\"]]\n\n        if not_configured_acl:\n            self.result.is_failure(f\"SSH IPv4 ACL(s) not configured or active in vrf {self.inputs.vrf}: {not_configured_acl}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.security/#anta.tests.security.VerifySSHIPv4Acl-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger The number of expected IPv4 ACL(s). - vrf str The name of the VRF in which to check for the SSHD agent. Defaults to `default` VRF. 'default'"},{"location":"api/tests.security/#anta.tests.security.VerifySSHIPv6Acl","title":"VerifySSHIPv6Acl","text":"

Verifies if the SSHD agent has the right number IPv6 ACL(s) configured for a specified VRF.

Expected Results
  • Success: The test will pass if the SSHD agent has the provided number of IPv6 ACL(s) in the specified VRF.
  • Failure: The test will fail if the SSHD agent has not the right number of IPv6 ACL(s) in the specified VRF.
Examples
anta.tests.security:\n  - VerifySSHIPv6Acl:\n      number: 3\n      vrf: default\n
Source code in anta/tests/security.py
class VerifySSHIPv6Acl(AntaTest):\n    \"\"\"Verifies if the SSHD agent has the right number IPv6 ACL(s) configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SSHD agent has the provided number of IPv6 ACL(s) in the specified VRF.\n    * Failure: The test will fail if the SSHD agent has not the right number of IPv6 ACL(s) in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifySSHIPv6Acl:\n          number: 3\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifySSHIPv6Acl\"\n    description = \"Verifies if the SSHD agent has IPv6 ACL(s) configured.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management ssh ipv6 access-list summary\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySSHIPv6Acl test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"The number of expected IPv6 ACL(s).\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for the SSHD agent. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySSHIPv6Acl.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ipv6_acl_list = command_output[\"ipv6AclList\"][\"aclList\"]\n        ipv6_acl_number = len(ipv6_acl_list)\n        if ipv6_acl_number != self.inputs.number:\n            self.result.is_failure(f\"Expected {self.inputs.number} SSH IPv6 ACL(s) in vrf {self.inputs.vrf} but got {ipv6_acl_number}\")\n            return\n\n        not_configured_acl = [acl[\"name\"] for acl in ipv6_acl_list if self.inputs.vrf not in acl[\"configuredVrfs\"] or self.inputs.vrf not in acl[\"activeVrfs\"]]\n\n        if not_configured_acl:\n            self.result.is_failure(f\"SSH IPv6 ACL(s) not configured or active in vrf {self.inputs.vrf}: {not_configured_acl}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.security/#anta.tests.security.VerifySSHIPv6Acl-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger The number of expected IPv6 ACL(s). - vrf str The name of the VRF in which to check for the SSHD agent. Defaults to `default` VRF. 'default'"},{"location":"api/tests.security/#anta.tests.security.VerifySSHStatus","title":"VerifySSHStatus","text":"

Verifies if the SSHD agent is disabled in the default VRF.

Expected Results
  • Success: The test will pass if the SSHD agent is disabled in the default VRF.
  • Failure: The test will fail if the SSHD agent is NOT disabled in the default VRF.
Examples
anta.tests.security:\n  - VerifySSHStatus:\n
Source code in anta/tests/security.py
class VerifySSHStatus(AntaTest):\n    \"\"\"Verifies if the SSHD agent is disabled in the default VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SSHD agent is disabled in the default VRF.\n    * Failure: The test will fail if the SSHD agent is NOT disabled in the default VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifySSHStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifySSHStatus\"\n    description = \"Verifies if the SSHD agent is disabled in the default VRF.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management ssh\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySSHStatus.\"\"\"\n        command_output = self.instance_commands[0].text_output\n\n        try:\n            line = next(line for line in command_output.split(\"\\n\") if line.startswith(\"SSHD status\"))\n        except StopIteration:\n            self.result.is_error(\"Could not find SSH status in returned output.\")\n            return\n        status = line.split(\"is \")[1]\n\n        if status == \"disabled\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(line)\n
"},{"location":"api/tests.security/#anta.tests.security.VerifySpecificIPSecConn","title":"VerifySpecificIPSecConn","text":"

Verifies the state of IPv4 security connections for a specified peer.

It optionally allows for the verification of a specific path for a peer by providing source and destination addresses. If these addresses are not provided, it will verify all paths for the specified peer.

Expected Results
  • Success: The test passes if the IPv4 security connection for a peer is established in the specified VRF.
  • Failure: The test fails if IPv4 security is not configured, a connection is not found for a peer, or the connection is not established in the specified VRF.
Examples
anta.tests.security:\n  - VerifySpecificIPSecConn:\n      ip_security_connections:\n        - peer: 10.255.0.1\n        - peer: 10.255.0.2\n          vrf: default\n          connections:\n            - source_address: 100.64.3.2\n              destination_address: 100.64.2.2\n            - source_address: 172.18.3.2\n              destination_address: 172.18.2.2\n
Source code in anta/tests/security.py
class VerifySpecificIPSecConn(AntaTest):\n    \"\"\"\n    Verifies the state of IPv4 security connections for a specified peer.\n\n    It optionally allows for the verification of a specific path for a peer by providing source and destination addresses.\n    If these addresses are not provided, it will verify all paths for the specified peer.\n\n    Expected Results\n    ----------------\n    * Success: The test passes if the IPv4 security connection for a peer is established in the specified VRF.\n    * Failure: The test fails if IPv4 security is not configured, a connection is not found for a peer, or the connection is not established in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifySpecificIPSecConn:\n          ip_security_connections:\n            - peer: 10.255.0.1\n            - peer: 10.255.0.2\n              vrf: default\n              connections:\n                - source_address: 100.64.3.2\n                  destination_address: 100.64.2.2\n                - source_address: 172.18.3.2\n                  destination_address: 172.18.2.2\n    ```\n    \"\"\"\n\n    name = \"VerifySpecificIPSecConn\"\n    description = \"Verifies IPv4 security connections for a peer.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show ip security connection vrf {vrf} path peer {peer}\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySpecificIPSecConn test.\"\"\"\n\n        ip_security_connections: list[IPSecPeers]\n        \"\"\"List of IP4v security peers.\"\"\"\n\n        class IPSecPeers(BaseModel):\n            \"\"\"Details of IPv4 security peers.\"\"\"\n\n            peer: IPv4Address\n            \"\"\"IPv4 address of the peer.\"\"\"\n\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for the IP security peer.\"\"\"\n\n            connections: list[IPSecConn] | None = None\n            \"\"\"Optional list of IPv4 security connections of a peer.\"\"\"\n\n            class IPSecConn(BaseModel):\n                \"\"\"Details of IPv4 security connections for a peer.\"\"\"\n\n                source_address: IPv4Address\n                \"\"\"Source IPv4 address of the connection.\"\"\"\n                destination_address: IPv4Address\n                \"\"\"Destination IPv4 address of the connection.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each input IP Sec connection.\"\"\"\n        return [template.render(peer=conn.peer, vrf=conn.vrf) for conn in self.inputs.ip_security_connections]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySpecificIPSecConn.\"\"\"\n        self.result.is_success()\n        for command_output, input_peer in zip(self.instance_commands, self.inputs.ip_security_connections):\n            conn_output = command_output.json_output[\"connections\"]\n            peer = command_output.params.peer\n            vrf = command_output.params.vrf\n            conn_input = input_peer.connections\n\n            # Check if IPv4 security connection is configured\n            if not conn_output:\n                self.result.is_failure(f\"No IPv4 security connection configured for peer `{peer}`.\")\n                continue\n\n            # If connection details are not provided then check all connections of a peer\n            if conn_input is None:\n                for conn_data in conn_output.values():\n                    state = next(iter(conn_data[\"pathDict\"].values()))\n                    if state != \"Established\":\n                        source = conn_data.get(\"saddr\")\n                        destination = conn_data.get(\"daddr\")\n                        vrf = conn_data.get(\"tunnelNs\")\n                        self.result.is_failure(\n                            f\"Expected state of IPv4 security connection `source:{source} destination:{destination} vrf:{vrf}` for peer `{peer}` is `Established` \"\n                            f\"but found `{state}` instead.\"\n                        )\n                continue\n\n            # Create a dictionary of existing connections for faster lookup\n            existing_connections = {\n                (conn_data.get(\"saddr\"), conn_data.get(\"daddr\"), conn_data.get(\"tunnelNs\")): next(iter(conn_data[\"pathDict\"].values()))\n                for conn_data in conn_output.values()\n            }\n            for connection in conn_input:\n                source_input = str(connection.source_address)\n                destination_input = str(connection.destination_address)\n\n                if (source_input, destination_input, vrf) in existing_connections:\n                    existing_state = existing_connections[(source_input, destination_input, vrf)]\n                    if existing_state != \"Established\":\n                        self.result.is_failure(\n                            f\"Expected state of IPv4 security connection `source:{source_input} destination:{destination_input} vrf:{vrf}` \"\n                            f\"for peer `{peer}` is `Established` but found `{existing_state}` instead.\"\n                        )\n                else:\n                    self.result.is_failure(\n                        f\"IPv4 security connection `source:{source_input} destination:{destination_input} vrf:{vrf}` for peer `{peer}` is not found.\"\n                    )\n
"},{"location":"api/tests.security/#anta.tests.security.VerifySpecificIPSecConn-attributes","title":"Inputs","text":"Name Type Description Default ip_security_connections list[IPSecPeers] List of IP4v security peers. -"},{"location":"api/tests.security/#anta.tests.security.VerifySpecificIPSecConn-attributes","title":"IPSecPeers","text":"Name Type Description Default peer IPv4Address IPv4 address of the peer. - vrf str Optional VRF for the IP security peer. 'default' connections list[IPSecConn] | None Optional list of IPv4 security connections of a peer. None"},{"location":"api/tests.security/#anta.tests.security.VerifySpecificIPSecConn-attributes","title":"IPSecConn","text":"Name Type Description Default source_address IPv4Address Source IPv4 address of the connection. - destination_address IPv4Address Destination IPv4 address of the connection. -"},{"location":"api/tests.security/#anta.tests.security.VerifyTelnetStatus","title":"VerifyTelnetStatus","text":"

Verifies if Telnet is disabled in the default VRF.

Expected Results
  • Success: The test will pass if Telnet is disabled in the default VRF.
  • Failure: The test will fail if Telnet is NOT disabled in the default VRF.
Examples
anta.tests.security:\n  - VerifyTelnetStatus:\n
Source code in anta/tests/security.py
class VerifyTelnetStatus(AntaTest):\n    \"\"\"Verifies if Telnet is disabled in the default VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if Telnet is disabled in the default VRF.\n    * Failure: The test will fail if Telnet is NOT disabled in the default VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyTelnetStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifyTelnetStatus\"\n    description = \"Verifies if Telnet is disabled in the default VRF.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management telnet\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTelnetStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"serverState\"] == \"disabled\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"Telnet status for Default VRF is enabled\")\n
"},{"location":"api/tests.services/","title":"Services","text":""},{"location":"api/tests.services/#anta.tests.services.VerifyDNSLookup","title":"VerifyDNSLookup","text":"

Verifies the DNS (Domain Name Service) name to IP address resolution.

Expected Results
  • Success: The test will pass if a domain name is resolved to an IP address.
  • Failure: The test will fail if a domain name does not resolve to an IP address.
  • Error: This test will error out if a domain name is invalid.
Examples
anta.tests.services:\n  - VerifyDNSLookup:\n      domain_names:\n        - arista.com\n        - www.google.com\n        - arista.ca\n
Source code in anta/tests/services.py
class VerifyDNSLookup(AntaTest):\n    \"\"\"Verifies the DNS (Domain Name Service) name to IP address resolution.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if a domain name is resolved to an IP address.\n    * Failure: The test will fail if a domain name does not resolve to an IP address.\n    * Error: This test will error out if a domain name is invalid.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.services:\n      - VerifyDNSLookup:\n          domain_names:\n            - arista.com\n            - www.google.com\n            - arista.ca\n    ```\n    \"\"\"\n\n    name = \"VerifyDNSLookup\"\n    description = \"Verifies the DNS name to IP address resolution.\"\n    categories: ClassVar[list[str]] = [\"services\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"bash timeout 10 nslookup {domain}\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyDNSLookup test.\"\"\"\n\n        domain_names: list[str]\n        \"\"\"List of domain names.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each domain name in the input list.\"\"\"\n        return [template.render(domain=domain_name) for domain_name in self.inputs.domain_names]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyDNSLookup.\"\"\"\n        self.result.is_success()\n        failed_domains = []\n        for command in self.instance_commands:\n            domain = command.params.domain\n            output = command.json_output[\"messages\"][0]\n            if f\"Can't find {domain}: No answer\" in output:\n                failed_domains.append(domain)\n        if failed_domains:\n            self.result.is_failure(f\"The following domain(s) are not resolved to an IP address: {', '.join(failed_domains)}\")\n
"},{"location":"api/tests.services/#anta.tests.services.VerifyDNSLookup-attributes","title":"Inputs","text":"Name Type Description Default domain_names list[str] List of domain names. -"},{"location":"api/tests.services/#anta.tests.services.VerifyDNSServers","title":"VerifyDNSServers","text":"

Verifies if the DNS (Domain Name Service) servers are correctly configured.

Expected Results
  • Success: The test will pass if the DNS server specified in the input is configured with the correct VRF and priority.
  • Failure: The test will fail if the DNS server is not configured or if the VRF and priority of the DNS server do not match the input.
Examples
anta.tests.services:\n  - VerifyDNSServers:\n      dns_servers:\n        - server_address: 10.14.0.1\n          vrf: default\n          priority: 1\n        - server_address: 10.14.0.11\n          vrf: MGMT\n          priority: 0\n
Source code in anta/tests/services.py
class VerifyDNSServers(AntaTest):\n    \"\"\"Verifies if the DNS (Domain Name Service) servers are correctly configured.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the DNS server specified in the input is configured with the correct VRF and priority.\n    * Failure: The test will fail if the DNS server is not configured or if the VRF and priority of the DNS server do not match the input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.services:\n      - VerifyDNSServers:\n          dns_servers:\n            - server_address: 10.14.0.1\n              vrf: default\n              priority: 1\n            - server_address: 10.14.0.11\n              vrf: MGMT\n              priority: 0\n    ```\n    \"\"\"\n\n    name = \"VerifyDNSServers\"\n    description = \"Verifies if the DNS servers are correctly configured.\"\n    categories: ClassVar[list[str]] = [\"services\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip name-server\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyDNSServers test.\"\"\"\n\n        dns_servers: list[DnsServer]\n        \"\"\"List of DNS servers to verify.\"\"\"\n\n        class DnsServer(BaseModel):\n            \"\"\"Model for a DNS server.\"\"\"\n\n            server_address: IPv4Address | IPv6Address\n            \"\"\"The IPv4/IPv6 address of the DNS server.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"The VRF for the DNS server. Defaults to 'default' if not provided.\"\"\"\n            priority: int = Field(ge=0, le=4)\n            \"\"\"The priority of the DNS server from 0 to 4, lower is first.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyDNSServers.\"\"\"\n        command_output = self.instance_commands[0].json_output[\"nameServerConfigs\"]\n        self.result.is_success()\n        for server in self.inputs.dns_servers:\n            address = str(server.server_address)\n            vrf = server.vrf\n            priority = server.priority\n            input_dict = {\"ipAddr\": address, \"vrf\": vrf}\n\n            if get_item(command_output, \"ipAddr\", address) is None:\n                self.result.is_failure(f\"DNS server `{address}` is not configured with any VRF.\")\n                continue\n\n            if (output := get_dict_superset(command_output, input_dict)) is None:\n                self.result.is_failure(f\"DNS server `{address}` is not configured with VRF `{vrf}`.\")\n                continue\n\n            if output[\"priority\"] != priority:\n                self.result.is_failure(f\"For DNS server `{address}`, the expected priority is `{priority}`, but `{output['priority']}` was found instead.\")\n
"},{"location":"api/tests.services/#anta.tests.services.VerifyDNSServers-attributes","title":"Inputs","text":"Name Type Description Default dns_servers list[DnsServer] List of DNS servers to verify. -"},{"location":"api/tests.services/#anta.tests.services.VerifyDNSServers-attributes","title":"DnsServer","text":"Name Type Description Default server_address IPv4Address | IPv6Address The IPv4/IPv6 address of the DNS server. - vrf str The VRF for the DNS server. Defaults to 'default' if not provided. 'default' priority int The priority of the DNS server from 0 to 4, lower is first. Field(ge=0, le=4)"},{"location":"api/tests.services/#anta.tests.services.VerifyErrdisableRecovery","title":"VerifyErrdisableRecovery","text":"

Verifies the errdisable recovery reason, status, and interval.

Expected Results
  • Success: The test will pass if the errdisable recovery reason status is enabled and the interval matches the input.
  • Failure: The test will fail if the errdisable recovery reason is not found, the status is not enabled, or the interval does not match the input.
Examples
anta.tests.services:\n  - VerifyErrdisableRecovery:\n      reasons:\n        - reason: acl\n          interval: 30\n        - reason: bpduguard\n          interval: 30\n
Source code in anta/tests/services.py
class VerifyErrdisableRecovery(AntaTest):\n    \"\"\"Verifies the errdisable recovery reason, status, and interval.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the errdisable recovery reason status is enabled and the interval matches the input.\n    * Failure: The test will fail if the errdisable recovery reason is not found, the status is not enabled, or the interval does not match the input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.services:\n      - VerifyErrdisableRecovery:\n          reasons:\n            - reason: acl\n              interval: 30\n            - reason: bpduguard\n              interval: 30\n    ```\n    \"\"\"\n\n    name = \"VerifyErrdisableRecovery\"\n    description = \"Verifies the errdisable recovery reason, status, and interval.\"\n    categories: ClassVar[list[str]] = [\"services\"]\n    # NOTE: Only `text` output format is supported for this command\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show errdisable recovery\", ofmt=\"text\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyErrdisableRecovery test.\"\"\"\n\n        reasons: list[ErrDisableReason]\n        \"\"\"List of errdisable reasons.\"\"\"\n\n        class ErrDisableReason(BaseModel):\n            \"\"\"Model for an errdisable reason.\"\"\"\n\n            reason: ErrDisableReasons\n            \"\"\"Type or name of the errdisable reason.\"\"\"\n            interval: ErrDisableInterval\n            \"\"\"Interval of the reason in seconds.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyErrdisableRecovery.\"\"\"\n        command_output = self.instance_commands[0].text_output\n        self.result.is_success()\n        for error_reason in self.inputs.reasons:\n            input_reason = error_reason.reason\n            input_interval = error_reason.interval\n            reason_found = False\n\n            # Skip header and last empty line\n            lines = command_output.split(\"\\n\")[2:-1]\n            for line in lines:\n                # Skip empty lines\n                if not line.strip():\n                    continue\n                # Split by first two whitespaces\n                reason, status, interval = line.split(None, 2)\n                if reason != input_reason:\n                    continue\n                reason_found = True\n                actual_reason_data = {\"interval\": interval, \"status\": status}\n                expected_reason_data = {\"interval\": str(input_interval), \"status\": \"Enabled\"}\n                if actual_reason_data != expected_reason_data:\n                    failed_log = get_failed_logs(expected_reason_data, actual_reason_data)\n                    self.result.is_failure(f\"`{input_reason}`:{failed_log}\\n\")\n                break\n\n            if not reason_found:\n                self.result.is_failure(f\"`{input_reason}`: Not found.\\n\")\n
"},{"location":"api/tests.services/#anta.tests.services.VerifyErrdisableRecovery-attributes","title":"Inputs","text":"Name Type Description Default reasons list[ErrDisableReason] List of errdisable reasons. -"},{"location":"api/tests.services/#anta.tests.services.VerifyErrdisableRecovery-attributes","title":"ErrDisableReason","text":"Name Type Description Default reason ErrDisableReasons Type or name of the errdisable reason. - interval ErrDisableInterval Interval of the reason in seconds. -"},{"location":"api/tests.services/#anta.tests.services.VerifyHostname","title":"VerifyHostname","text":"

Verifies the hostname of a device.

Expected Results
  • Success: The test will pass if the hostname matches the provided input.
  • Failure: The test will fail if the hostname does not match the provided input.
Examples
anta.tests.services:\n  - VerifyHostname:\n      hostname: s1-spine1\n
Source code in anta/tests/services.py
class VerifyHostname(AntaTest):\n    \"\"\"Verifies the hostname of a device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the hostname matches the provided input.\n    * Failure: The test will fail if the hostname does not match the provided input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.services:\n      - VerifyHostname:\n          hostname: s1-spine1\n    ```\n    \"\"\"\n\n    name = \"VerifyHostname\"\n    description = \"Verifies the hostname of a device.\"\n    categories: ClassVar[list[str]] = [\"services\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show hostname\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyHostname test.\"\"\"\n\n        hostname: str\n        \"\"\"Expected hostname of the device.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyHostname.\"\"\"\n        hostname = self.instance_commands[0].json_output[\"hostname\"]\n\n        if hostname != self.inputs.hostname:\n            self.result.is_failure(f\"Expected `{self.inputs.hostname}` as the hostname, but found `{hostname}` instead.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.services/#anta.tests.services.VerifyHostname-attributes","title":"Inputs","text":"Name Type Description Default hostname str Expected hostname of the device. -"},{"location":"api/tests.snmp/","title":"SNMP","text":""},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpContact","title":"VerifySnmpContact","text":"

Verifies the SNMP contact of a device.

Expected Results
  • Success: The test will pass if the SNMP contact matches the provided input.
  • Failure: The test will fail if the SNMP contact does not match the provided input.
Examples
anta.tests.snmp:\n  - VerifySnmpContact:\n      contact: Jon@example.com\n
Source code in anta/tests/snmp.py
class VerifySnmpContact(AntaTest):\n    \"\"\"Verifies the SNMP contact of a device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SNMP contact matches the provided input.\n    * Failure: The test will fail if the SNMP contact does not match the provided input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.snmp:\n      - VerifySnmpContact:\n          contact: Jon@example.com\n    ```\n    \"\"\"\n\n    name = \"VerifySnmpContact\"\n    description = \"Verifies the SNMP contact of a device.\"\n    categories: ClassVar[list[str]] = [\"snmp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show snmp\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySnmpContact test.\"\"\"\n\n        contact: str\n        \"\"\"Expected SNMP contact details of the device.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySnmpContact.\"\"\"\n        contact = self.instance_commands[0].json_output[\"contact\"][\"contact\"]\n\n        if contact != self.inputs.contact:\n            self.result.is_failure(f\"Expected `{self.inputs.contact}` as the contact, but found `{contact}` instead.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpContact-attributes","title":"Inputs","text":"Name Type Description Default contact str Expected SNMP contact details of the device. -"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpIPv4Acl","title":"VerifySnmpIPv4Acl","text":"

Verifies if the SNMP agent has the right number IPv4 ACL(s) configured for a specified VRF.

Expected Results
  • Success: The test will pass if the SNMP agent has the provided number of IPv4 ACL(s) in the specified VRF.
  • Failure: The test will fail if the SNMP agent has not the right number of IPv4 ACL(s) in the specified VRF.
Examples
anta.tests.snmp:\n  - VerifySnmpIPv4Acl:\n      number: 3\n      vrf: default\n
Source code in anta/tests/snmp.py
class VerifySnmpIPv4Acl(AntaTest):\n    \"\"\"Verifies if the SNMP agent has the right number IPv4 ACL(s) configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SNMP agent has the provided number of IPv4 ACL(s) in the specified VRF.\n    * Failure: The test will fail if the SNMP agent has not the right number of IPv4 ACL(s) in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.snmp:\n      - VerifySnmpIPv4Acl:\n          number: 3\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifySnmpIPv4Acl\"\n    description = \"Verifies if the SNMP agent has IPv4 ACL(s) configured.\"\n    categories: ClassVar[list[str]] = [\"snmp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show snmp ipv4 access-list summary\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySnmpIPv4Acl test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"The number of expected IPv4 ACL(s).\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for the SNMP agent. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySnmpIPv4Acl.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ipv4_acl_list = command_output[\"ipAclList\"][\"aclList\"]\n        ipv4_acl_number = len(ipv4_acl_list)\n        if ipv4_acl_number != self.inputs.number:\n            self.result.is_failure(f\"Expected {self.inputs.number} SNMP IPv4 ACL(s) in vrf {self.inputs.vrf} but got {ipv4_acl_number}\")\n            return\n\n        not_configured_acl = [acl[\"name\"] for acl in ipv4_acl_list if self.inputs.vrf not in acl[\"configuredVrfs\"] or self.inputs.vrf not in acl[\"activeVrfs\"]]\n\n        if not_configured_acl:\n            self.result.is_failure(f\"SNMP IPv4 ACL(s) not configured or active in vrf {self.inputs.vrf}: {not_configured_acl}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpIPv4Acl-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger The number of expected IPv4 ACL(s). - vrf str The name of the VRF in which to check for the SNMP agent. Defaults to `default` VRF. 'default'"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpIPv6Acl","title":"VerifySnmpIPv6Acl","text":"

Verifies if the SNMP agent has the right number IPv6 ACL(s) configured for a specified VRF.

Expected Results
  • Success: The test will pass if the SNMP agent has the provided number of IPv6 ACL(s) in the specified VRF.
  • Failure: The test will fail if the SNMP agent has not the right number of IPv6 ACL(s) in the specified VRF.
Examples
anta.tests.snmp:\n  - VerifySnmpIPv6Acl:\n      number: 3\n      vrf: default\n
Source code in anta/tests/snmp.py
class VerifySnmpIPv6Acl(AntaTest):\n    \"\"\"Verifies if the SNMP agent has the right number IPv6 ACL(s) configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SNMP agent has the provided number of IPv6 ACL(s) in the specified VRF.\n    * Failure: The test will fail if the SNMP agent has not the right number of IPv6 ACL(s) in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.snmp:\n      - VerifySnmpIPv6Acl:\n          number: 3\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifySnmpIPv6Acl\"\n    description = \"Verifies if the SNMP agent has IPv6 ACL(s) configured.\"\n    categories: ClassVar[list[str]] = [\"snmp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show snmp ipv6 access-list summary\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySnmpIPv6Acl test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"The number of expected IPv6 ACL(s).\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for the SNMP agent. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySnmpIPv6Acl.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ipv6_acl_list = command_output[\"ipv6AclList\"][\"aclList\"]\n        ipv6_acl_number = len(ipv6_acl_list)\n        if ipv6_acl_number != self.inputs.number:\n            self.result.is_failure(f\"Expected {self.inputs.number} SNMP IPv6 ACL(s) in vrf {self.inputs.vrf} but got {ipv6_acl_number}\")\n            return\n\n        acl_not_configured = [acl[\"name\"] for acl in ipv6_acl_list if self.inputs.vrf not in acl[\"configuredVrfs\"] or self.inputs.vrf not in acl[\"activeVrfs\"]]\n\n        if acl_not_configured:\n            self.result.is_failure(f\"SNMP IPv6 ACL(s) not configured or active in vrf {self.inputs.vrf}: {acl_not_configured}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpIPv6Acl-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger The number of expected IPv6 ACL(s). - vrf str The name of the VRF in which to check for the SNMP agent. Defaults to `default` VRF. 'default'"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpLocation","title":"VerifySnmpLocation","text":"

Verifies the SNMP location of a device.

Expected Results
  • Success: The test will pass if the SNMP location matches the provided input.
  • Failure: The test will fail if the SNMP location does not match the provided input.
Examples
anta.tests.snmp:\n  - VerifySnmpLocation:\n      location: New York\n
Source code in anta/tests/snmp.py
class VerifySnmpLocation(AntaTest):\n    \"\"\"Verifies the SNMP location of a device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SNMP location matches the provided input.\n    * Failure: The test will fail if the SNMP location does not match the provided input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.snmp:\n      - VerifySnmpLocation:\n          location: New York\n    ```\n    \"\"\"\n\n    name = \"VerifySnmpLocation\"\n    description = \"Verifies the SNMP location of a device.\"\n    categories: ClassVar[list[str]] = [\"snmp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show snmp\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySnmpLocation test.\"\"\"\n\n        location: str\n        \"\"\"Expected SNMP location of the device.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySnmpLocation.\"\"\"\n        location = self.instance_commands[0].json_output[\"location\"][\"location\"]\n\n        if location != self.inputs.location:\n            self.result.is_failure(f\"Expected `{self.inputs.location}` as the location, but found `{location}` instead.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpLocation-attributes","title":"Inputs","text":"Name Type Description Default location str Expected SNMP location of the device. -"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpStatus","title":"VerifySnmpStatus","text":"

Verifies whether the SNMP agent is enabled in a specified VRF.

Expected Results
  • Success: The test will pass if the SNMP agent is enabled in the specified VRF.
  • Failure: The test will fail if the SNMP agent is disabled in the specified VRF.
Examples
anta.tests.snmp:\n  - VerifySnmpStatus:\n      vrf: default\n
Source code in anta/tests/snmp.py
class VerifySnmpStatus(AntaTest):\n    \"\"\"Verifies whether the SNMP agent is enabled in a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SNMP agent is enabled in the specified VRF.\n    * Failure: The test will fail if the SNMP agent is disabled in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.snmp:\n      - VerifySnmpStatus:\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifySnmpStatus\"\n    description = \"Verifies if the SNMP agent is enabled.\"\n    categories: ClassVar[list[str]] = [\"snmp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show snmp\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySnmpStatus test.\"\"\"\n\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for the SNMP agent. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySnmpStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"enabled\"] and self.inputs.vrf in command_output[\"vrfs\"][\"snmpVrfs\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"SNMP agent disabled in vrf {self.inputs.vrf}\")\n
"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpStatus-attributes","title":"Inputs","text":"Name Type Description Default vrf str The name of the VRF in which to check for the SNMP agent. Defaults to `default` VRF. 'default'"},{"location":"api/tests.software/","title":"Software","text":""},{"location":"api/tests.software/#anta.tests.software.VerifyEOSExtensions","title":"VerifyEOSExtensions","text":"

Verifies that all EOS extensions installed on the device are enabled for boot persistence.

Expected Results
  • Success: The test will pass if all EOS extensions installed on the device are enabled for boot persistence.
  • Failure: The test will fail if some EOS extensions installed on the device are not enabled for boot persistence.
Examples
anta.tests.software:\n  - VerifyEOSExtensions:\n
Source code in anta/tests/software.py
class VerifyEOSExtensions(AntaTest):\n    \"\"\"Verifies that all EOS extensions installed on the device are enabled for boot persistence.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all EOS extensions installed on the device are enabled for boot persistence.\n    * Failure: The test will fail if some EOS extensions installed on the device are not enabled for boot persistence.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.software:\n      - VerifyEOSExtensions:\n    ```\n    \"\"\"\n\n    name = \"VerifyEOSExtensions\"\n    description = \"Verifies that all EOS extensions installed on the device are enabled for boot persistence.\"\n    categories: ClassVar[list[str]] = [\"software\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"show extensions\", revision=2),\n        AntaCommand(command=\"show boot-extensions\", revision=1),\n    ]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyEOSExtensions.\"\"\"\n        boot_extensions = []\n        show_extensions_command_output = self.instance_commands[0].json_output\n        show_boot_extensions_command_output = self.instance_commands[1].json_output\n        installed_extensions = [\n            extension for extension, extension_data in show_extensions_command_output[\"extensions\"].items() if extension_data[\"status\"] == \"installed\"\n        ]\n        for extension in show_boot_extensions_command_output[\"extensions\"]:\n            formatted_extension = extension.strip(\"\\n\")\n            if formatted_extension != \"\":\n                boot_extensions.append(formatted_extension)\n        installed_extensions.sort()\n        boot_extensions.sort()\n        if installed_extensions == boot_extensions:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Missing EOS extensions: installed {installed_extensions} / configured: {boot_extensions}\")\n
"},{"location":"api/tests.software/#anta.tests.software.VerifyEOSVersion","title":"VerifyEOSVersion","text":"

Verifies that the device is running one of the allowed EOS version.

Expected Results
  • Success: The test will pass if the device is running one of the allowed EOS version.
  • Failure: The test will fail if the device is not running one of the allowed EOS version.
Examples
anta.tests.software:\n  - VerifyEOSVersion:\n      versions:\n        - 4.25.4M\n        - 4.26.1F\n
Source code in anta/tests/software.py
class VerifyEOSVersion(AntaTest):\n    \"\"\"Verifies that the device is running one of the allowed EOS version.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is running one of the allowed EOS version.\n    * Failure: The test will fail if the device is not running one of the allowed EOS version.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.software:\n      - VerifyEOSVersion:\n          versions:\n            - 4.25.4M\n            - 4.26.1F\n    ```\n    \"\"\"\n\n    name = \"VerifyEOSVersion\"\n    description = \"Verifies the EOS version of the device.\"\n    categories: ClassVar[list[str]] = [\"software\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show version\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyEOSVersion test.\"\"\"\n\n        versions: list[str]\n        \"\"\"List of allowed EOS versions.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyEOSVersion.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"version\"] in self.inputs.versions:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f'device is running version \"{command_output[\"version\"]}\" not in expected versions: {self.inputs.versions}')\n
"},{"location":"api/tests.software/#anta.tests.software.VerifyEOSVersion-attributes","title":"Inputs","text":"Name Type Description Default versions list[str] List of allowed EOS versions. -"},{"location":"api/tests.software/#anta.tests.software.VerifyTerminAttrVersion","title":"VerifyTerminAttrVersion","text":"

Verifies that he device is running one of the allowed TerminAttr version.

Expected Results
  • Success: The test will pass if the device is running one of the allowed TerminAttr version.
  • Failure: The test will fail if the device is not running one of the allowed TerminAttr version.
Examples
anta.tests.software:\n  - VerifyTerminAttrVersion:\n      versions:\n        - v1.13.6\n        - v1.8.0\n
Source code in anta/tests/software.py
class VerifyTerminAttrVersion(AntaTest):\n    \"\"\"Verifies that he device is running one of the allowed TerminAttr version.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is running one of the allowed TerminAttr version.\n    * Failure: The test will fail if the device is not running one of the allowed TerminAttr version.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.software:\n      - VerifyTerminAttrVersion:\n          versions:\n            - v1.13.6\n            - v1.8.0\n    ```\n    \"\"\"\n\n    name = \"VerifyTerminAttrVersion\"\n    description = \"Verifies the TerminAttr version of the device.\"\n    categories: ClassVar[list[str]] = [\"software\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show version detail\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyTerminAttrVersion test.\"\"\"\n\n        versions: list[str]\n        \"\"\"List of allowed TerminAttr versions.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTerminAttrVersion.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        command_output_data = command_output[\"details\"][\"packages\"][\"TerminAttr-core\"][\"version\"]\n        if command_output_data in self.inputs.versions:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"device is running TerminAttr version {command_output_data} and is not in the allowed list: {self.inputs.versions}\")\n
"},{"location":"api/tests.software/#anta.tests.software.VerifyTerminAttrVersion-attributes","title":"Inputs","text":"Name Type Description Default versions list[str] List of allowed TerminAttr versions. -"},{"location":"api/tests.stp/","title":"STP","text":""},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPBlockedPorts","title":"VerifySTPBlockedPorts","text":"

Verifies there is no STP blocked ports.

Expected Results
  • Success: The test will pass if there are NO ports blocked by STP.
  • Failure: The test will fail if there are ports blocked by STP.
Examples
anta.tests.stp:\n  - VerifySTPBlockedPorts:\n
Source code in anta/tests/stp.py
class VerifySTPBlockedPorts(AntaTest):\n    \"\"\"Verifies there is no STP blocked ports.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are NO ports blocked by STP.\n    * Failure: The test will fail if there are ports blocked by STP.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stp:\n      - VerifySTPBlockedPorts:\n    ```\n    \"\"\"\n\n    name = \"VerifySTPBlockedPorts\"\n    description = \"Verifies there is no STP blocked ports.\"\n    categories: ClassVar[list[str]] = [\"stp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show spanning-tree blockedports\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySTPBlockedPorts.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if not (stp_instances := command_output[\"spanningTreeInstances\"]):\n            self.result.is_success()\n        else:\n            for key, value in stp_instances.items():\n                stp_instances[key] = value.pop(\"spanningTreeBlockedPorts\")\n            self.result.is_failure(f\"The following ports are blocked by STP: {stp_instances}\")\n
"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPCounters","title":"VerifySTPCounters","text":"

Verifies there is no errors in STP BPDU packets.

Expected Results
  • Success: The test will pass if there are NO STP BPDU packet errors under all interfaces participating in STP.
  • Failure: The test will fail if there are STP BPDU packet errors on one or many interface(s).
Examples
anta.tests.stp:\n  - VerifySTPCounters:\n
Source code in anta/tests/stp.py
class VerifySTPCounters(AntaTest):\n    \"\"\"Verifies there is no errors in STP BPDU packets.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are NO STP BPDU packet errors under all interfaces participating in STP.\n    * Failure: The test will fail if there are STP BPDU packet errors on one or many interface(s).\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stp:\n      - VerifySTPCounters:\n    ```\n    \"\"\"\n\n    name = \"VerifySTPCounters\"\n    description = \"Verifies there is no errors in STP BPDU packets.\"\n    categories: ClassVar[list[str]] = [\"stp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show spanning-tree counters\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySTPCounters.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        interfaces_with_errors = [\n            interface for interface, counters in command_output[\"interfaces\"].items() if counters[\"bpduTaggedError\"] or counters[\"bpduOtherError\"] != 0\n        ]\n        if interfaces_with_errors:\n            self.result.is_failure(f\"The following interfaces have STP BPDU packet errors: {interfaces_with_errors}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPForwardingPorts","title":"VerifySTPForwardingPorts","text":"

Verifies that all interfaces are in a forwarding state for a provided list of VLAN(s).

Expected Results
  • Success: The test will pass if all interfaces are in a forwarding state for the specified VLAN(s).
  • Failure: The test will fail if one or many interfaces are NOT in a forwarding state in the specified VLAN(s).
Examples
anta.tests.stp:\n  - VerifySTPForwardingPorts:\n      vlans:\n        - 10\n        - 20\n
Source code in anta/tests/stp.py
class VerifySTPForwardingPorts(AntaTest):\n    \"\"\"Verifies that all interfaces are in a forwarding state for a provided list of VLAN(s).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all interfaces are in a forwarding state for the specified VLAN(s).\n    * Failure: The test will fail if one or many interfaces are NOT in a forwarding state in the specified VLAN(s).\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stp:\n      - VerifySTPForwardingPorts:\n          vlans:\n            - 10\n            - 20\n    ```\n    \"\"\"\n\n    name = \"VerifySTPForwardingPorts\"\n    description = \"Verifies that all interfaces are forwarding for a provided list of VLAN(s).\"\n    categories: ClassVar[list[str]] = [\"stp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show spanning-tree topology vlan {vlan} status\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySTPForwardingPorts test.\"\"\"\n\n        vlans: list[Vlan]\n        \"\"\"List of VLAN on which to verify forwarding states.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each VLAN in the input list.\"\"\"\n        return [template.render(vlan=vlan) for vlan in self.inputs.vlans]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySTPForwardingPorts.\"\"\"\n        not_configured = []\n        not_forwarding = []\n        for command in self.instance_commands:\n            vlan_id = command.params.vlan\n            if not (topologies := get_value(command.json_output, \"topologies\")):\n                not_configured.append(vlan_id)\n            else:\n                interfaces_not_forwarding = []\n                for value in topologies.values():\n                    if vlan_id and int(vlan_id) in value[\"vlans\"]:\n                        interfaces_not_forwarding = [interface for interface, state in value[\"interfaces\"].items() if state[\"state\"] != \"forwarding\"]\n                if interfaces_not_forwarding:\n                    not_forwarding.append({f\"VLAN {vlan_id}\": interfaces_not_forwarding})\n        if not_configured:\n            self.result.is_failure(f\"STP instance is not configured for the following VLAN(s): {not_configured}\")\n        if not_forwarding:\n            self.result.is_failure(f\"The following VLAN(s) have interface(s) that are not in a forwarding state: {not_forwarding}\")\n        if not not_configured and not interfaces_not_forwarding:\n            self.result.is_success()\n
"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPForwardingPorts-attributes","title":"Inputs","text":"Name Type Description Default vlans list[Vlan] List of VLAN on which to verify forwarding states. -"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPMode","title":"VerifySTPMode","text":"

Verifies the configured STP mode for a provided list of VLAN(s).

Expected Results
  • Success: The test will pass if the STP mode is configured properly in the specified VLAN(s).
  • Failure: The test will fail if the STP mode is NOT configured properly for one or more specified VLAN(s).
Examples
anta.tests.stp:\n  - VerifySTPMode:\n      mode: rapidPvst\n      vlans:\n        - 10\n        - 20\n
Source code in anta/tests/stp.py
class VerifySTPMode(AntaTest):\n    \"\"\"Verifies the configured STP mode for a provided list of VLAN(s).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the STP mode is configured properly in the specified VLAN(s).\n    * Failure: The test will fail if the STP mode is NOT configured properly for one or more specified VLAN(s).\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stp:\n      - VerifySTPMode:\n          mode: rapidPvst\n          vlans:\n            - 10\n            - 20\n    ```\n    \"\"\"\n\n    name = \"VerifySTPMode\"\n    description = \"Verifies the configured STP mode for a provided list of VLAN(s).\"\n    categories: ClassVar[list[str]] = [\"stp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show spanning-tree vlan {vlan}\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySTPMode test.\"\"\"\n\n        mode: Literal[\"mstp\", \"rstp\", \"rapidPvst\"] = \"mstp\"\n        \"\"\"STP mode to verify. Supported values: mstp, rstp, rapidPvst. Defaults to mstp.\"\"\"\n        vlans: list[Vlan]\n        \"\"\"List of VLAN on which to verify STP mode.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each VLAN in the input list.\"\"\"\n        return [template.render(vlan=vlan) for vlan in self.inputs.vlans]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySTPMode.\"\"\"\n        not_configured = []\n        wrong_stp_mode = []\n        for command in self.instance_commands:\n            vlan_id = command.params.vlan\n            if not (\n                stp_mode := get_value(\n                    command.json_output,\n                    f\"spanningTreeVlanInstances.{vlan_id}.spanningTreeVlanInstance.protocol\",\n                )\n            ):\n                not_configured.append(vlan_id)\n            elif stp_mode != self.inputs.mode:\n                wrong_stp_mode.append(vlan_id)\n        if not_configured:\n            self.result.is_failure(f\"STP mode '{self.inputs.mode}' not configured for the following VLAN(s): {not_configured}\")\n        if wrong_stp_mode:\n            self.result.is_failure(f\"Wrong STP mode configured for the following VLAN(s): {wrong_stp_mode}\")\n        if not not_configured and not wrong_stp_mode:\n            self.result.is_success()\n
"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPMode-attributes","title":"Inputs","text":"Name Type Description Default mode Literal['mstp', 'rstp', 'rapidPvst'] STP mode to verify. Supported values: mstp, rstp, rapidPvst. Defaults to mstp. 'mstp' vlans list[Vlan] List of VLAN on which to verify STP mode. -"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPRootPriority","title":"VerifySTPRootPriority","text":"

Verifies the STP root priority for a provided list of VLAN or MST instance ID(s).

Expected Results
  • Success: The test will pass if the STP root priority is configured properly for the specified VLAN or MST instance ID(s).
  • Failure: The test will fail if the STP root priority is NOT configured properly for the specified VLAN or MST instance ID(s).
Examples
anta.tests.stp:\n  - VerifySTPRootPriority:\n      priority: 32768\n      instances:\n        - 10\n        - 20\n
Source code in anta/tests/stp.py
class VerifySTPRootPriority(AntaTest):\n    \"\"\"Verifies the STP root priority for a provided list of VLAN or MST instance ID(s).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the STP root priority is configured properly for the specified VLAN or MST instance ID(s).\n    * Failure: The test will fail if the STP root priority is NOT configured properly for the specified VLAN or MST instance ID(s).\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stp:\n      - VerifySTPRootPriority:\n          priority: 32768\n          instances:\n            - 10\n            - 20\n    ```\n    \"\"\"\n\n    name = \"VerifySTPRootPriority\"\n    description = \"Verifies the STP root priority for a provided list of VLAN or MST instance ID(s).\"\n    categories: ClassVar[list[str]] = [\"stp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show spanning-tree root detail\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySTPRootPriority test.\"\"\"\n\n        priority: int\n        \"\"\"STP root priority to verify.\"\"\"\n        instances: list[Vlan] = Field(default=[])\n        \"\"\"List of VLAN or MST instance ID(s). If empty, ALL VLAN or MST instance ID(s) will be verified.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySTPRootPriority.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if not (stp_instances := command_output[\"instances\"]):\n            self.result.is_failure(\"No STP instances configured\")\n            return\n        # Checking the type of instances based on first instance\n        first_name = next(iter(stp_instances))\n        if first_name.startswith(\"MST\"):\n            prefix = \"MST\"\n        elif first_name.startswith(\"VL\"):\n            prefix = \"VL\"\n        else:\n            self.result.is_failure(f\"Unsupported STP instance type: {first_name}\")\n            return\n        check_instances = [f\"{prefix}{instance_id}\" for instance_id in self.inputs.instances] if self.inputs.instances else command_output[\"instances\"].keys()\n        wrong_priority_instances = [\n            instance for instance in check_instances if get_value(command_output, f\"instances.{instance}.rootBridge.priority\") != self.inputs.priority\n        ]\n        if wrong_priority_instances:\n            self.result.is_failure(f\"The following instance(s) have the wrong STP root priority configured: {wrong_priority_instances}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPRootPriority-attributes","title":"Inputs","text":"Name Type Description Default priority int STP root priority to verify. - instances list[Vlan] List of VLAN or MST instance ID(s). If empty, ALL VLAN or MST instance ID(s) will be verified. Field(default=[])"},{"location":"api/tests.stun/","title":"STUN","text":""},{"location":"api/tests.stun/#anta.tests.stun.VerifyStunClient","title":"VerifyStunClient","text":"

Verifies the configuration of the STUN client, specifically the IPv4 source address and port.

Optionally, it can also verify the public address and port.

Expected Results
  • Success: The test will pass if the STUN client is correctly configured with the specified IPv4 source address/port and public address/port.
  • Failure: The test will fail if the STUN client is not configured or if the IPv4 source address, public address, or port details are incorrect.
Examples
anta.tests.stun:\n  - VerifyStunClient:\n      stun_clients:\n        - source_address: 172.18.3.2\n          public_address: 172.18.3.21\n          source_port: 4500\n          public_port: 6006\n        - source_address: 100.64.3.2\n          public_address: 100.64.3.21\n          source_port: 4500\n          public_port: 6006\n
Source code in anta/tests/stun.py
class VerifyStunClient(AntaTest):\n    \"\"\"\n    Verifies the configuration of the STUN client, specifically the IPv4 source address and port.\n\n    Optionally, it can also verify the public address and port.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the STUN client is correctly configured with the specified IPv4 source address/port and public address/port.\n    * Failure: The test will fail if the STUN client is not configured or if the IPv4 source address, public address, or port details are incorrect.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stun:\n      - VerifyStunClient:\n          stun_clients:\n            - source_address: 172.18.3.2\n              public_address: 172.18.3.21\n              source_port: 4500\n              public_port: 6006\n            - source_address: 100.64.3.2\n              public_address: 100.64.3.21\n              source_port: 4500\n              public_port: 6006\n    ```\n    \"\"\"\n\n    name = \"VerifyStunClient\"\n    description = \"Verifies the STUN client is configured with the specified IPv4 source address and port. Validate the public IP and port if provided.\"\n    categories: ClassVar[list[str]] = [\"stun\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show stun client translations {source_address} {source_port}\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyStunClient test.\"\"\"\n\n        stun_clients: list[ClientAddress]\n\n        class ClientAddress(BaseModel):\n            \"\"\"Source and public address/port details of STUN client.\"\"\"\n\n            source_address: IPv4Address\n            \"\"\"IPv4 source address of STUN client.\"\"\"\n            source_port: Port = 4500\n            \"\"\"Source port number for STUN client.\"\"\"\n            public_address: IPv4Address | None = None\n            \"\"\"Optional IPv4 public address of STUN client.\"\"\"\n            public_port: Port | None = None\n            \"\"\"Optional public port number for STUN client.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each STUN translation.\"\"\"\n        return [template.render(source_address=client.source_address, source_port=client.source_port) for client in self.inputs.stun_clients]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyStunClient.\"\"\"\n        self.result.is_success()\n\n        # Iterate over each command output and corresponding client input\n        for command, client_input in zip(self.instance_commands, self.inputs.stun_clients):\n            bindings = command.json_output[\"bindings\"]\n            source_address = str(command.params.source_address)\n            source_port = command.params.source_port\n\n            # If no bindings are found for the STUN client, mark the test as a failure and continue with the next client\n            if not bindings:\n                self.result.is_failure(f\"STUN client transaction for source `{source_address}:{source_port}` is not found.\")\n                continue\n\n            # Extract the public address and port from the client input\n            public_address = client_input.public_address\n            public_port = client_input.public_port\n\n            # Extract the transaction ID from the bindings\n            transaction_id = next(iter(bindings.keys()))\n\n            # Prepare the actual and expected STUN data for comparison\n            actual_stun_data = {\n                \"source ip\": get_value(bindings, f\"{transaction_id}.sourceAddress.ip\"),\n                \"source port\": get_value(bindings, f\"{transaction_id}.sourceAddress.port\"),\n            }\n            expected_stun_data = {\"source ip\": source_address, \"source port\": source_port}\n\n            # If public address is provided, add it to the actual and expected STUN data\n            if public_address is not None:\n                actual_stun_data[\"public ip\"] = get_value(bindings, f\"{transaction_id}.publicAddress.ip\")\n                expected_stun_data[\"public ip\"] = str(public_address)\n\n            # If public port is provided, add it to the actual and expected STUN data\n            if public_port is not None:\n                actual_stun_data[\"public port\"] = get_value(bindings, f\"{transaction_id}.publicAddress.port\")\n                expected_stun_data[\"public port\"] = public_port\n\n            # If the actual STUN data does not match the expected STUN data, mark the test as failure\n            if actual_stun_data != expected_stun_data:\n                failed_log = get_failed_logs(expected_stun_data, actual_stun_data)\n                self.result.is_failure(f\"For STUN source `{source_address}:{source_port}`:{failed_log}\")\n
"},{"location":"api/tests.stun/#anta.tests.stun.VerifyStunClient-attributes","title":"Inputs","text":"Name Type Description Default"},{"location":"api/tests.stun/#anta.tests.stun.VerifyStunClient-attributes","title":"ClientAddress","text":"Name Type Description Default source_address IPv4Address IPv4 source address of STUN client. - source_port Port Source port number for STUN client. 4500 public_address IPv4Address | None Optional IPv4 public address of STUN client. None public_port Port | None Optional public port number for STUN client. None"},{"location":"api/tests.stun/#anta.tests.stun.VerifyStunServer","title":"VerifyStunServer","text":"

Verifies the STUN server status is enabled and running.

Expected Results
  • Success: The test will pass if the STUN server status is enabled and running.
  • Failure: The test will fail if the STUN server is disabled or not running.
Examples
anta.tests.stun:\n  - VerifyStunServer:\n
Source code in anta/tests/stun.py
class VerifyStunServer(AntaTest):\n    \"\"\"\n    Verifies the STUN server status is enabled and running.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the STUN server status is enabled and running.\n    * Failure: The test will fail if the STUN server is disabled or not running.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stun:\n      - VerifyStunServer:\n    ```\n    \"\"\"\n\n    name = \"VerifyStunServer\"\n    description = \"Verifies the STUN server status is enabled and running.\"\n    categories: ClassVar[list[str]] = [\"stun\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show stun server status\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyStunServer.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        status_disabled = not command_output.get(\"enabled\")\n        not_running = command_output.get(\"pid\") == 0\n\n        if status_disabled and not_running:\n            self.result.is_failure(\"STUN server status is disabled and not running.\")\n        elif status_disabled:\n            self.result.is_failure(\"STUN server status is disabled.\")\n        elif not_running:\n            self.result.is_failure(\"STUN server is not running.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.system/","title":"System","text":""},{"location":"api/tests.system/#anta.tests.system.VerifyAgentLogs","title":"VerifyAgentLogs","text":"

Verifies that no agent crash reports are present on the device.

Expected Results
  • Success: The test will pass if there is NO agent crash reported.
  • Failure: The test will fail if any agent crashes are reported.
Examples
anta.tests.system:\n  - VerifyAgentLogs:\n
Source code in anta/tests/system.py
class VerifyAgentLogs(AntaTest):\n    \"\"\"Verifies that no agent crash reports are present on the device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there is NO agent crash reported.\n    * Failure: The test will fail if any agent crashes are reported.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyAgentLogs:\n    ```\n    \"\"\"\n\n    name = \"VerifyAgentLogs\"\n    description = \"Verifies there are no agent crash reports.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show agent logs crash\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAgentLogs.\"\"\"\n        command_output = self.instance_commands[0].text_output\n        if len(command_output) == 0:\n            self.result.is_success()\n        else:\n            pattern = re.compile(r\"^===> (.*?) <===$\", re.MULTILINE)\n            agents = \"\\n * \".join(pattern.findall(command_output))\n            self.result.is_failure(f\"Device has reported agent crashes:\\n * {agents}\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyCPUUtilization","title":"VerifyCPUUtilization","text":"

Verifies whether the CPU utilization is below 75%.

Expected Results
  • Success: The test will pass if the CPU utilization is below 75%.
  • Failure: The test will fail if the CPU utilization is over 75%.
Examples
anta.tests.system:\n  - VerifyCPUUtilization:\n
Source code in anta/tests/system.py
class VerifyCPUUtilization(AntaTest):\n    \"\"\"Verifies whether the CPU utilization is below 75%.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the CPU utilization is below 75%.\n    * Failure: The test will fail if the CPU utilization is over 75%.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyCPUUtilization:\n    ```\n    \"\"\"\n\n    name = \"VerifyCPUUtilization\"\n    description = \"Verifies whether the CPU utilization is below 75%.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show processes top once\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyCPUUtilization.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        command_output_data = command_output[\"cpuInfo\"][\"%Cpu(s)\"][\"idle\"]\n        if command_output_data > CPU_IDLE_THRESHOLD:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device has reported a high CPU utilization: {100 - command_output_data}%\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyCoredump","title":"VerifyCoredump","text":"

Verifies if there are core dump files in the /var/core directory.

Expected Results
  • Success: The test will pass if there are NO core dump(s) in /var/core.
  • Failure: The test will fail if there are core dump(s) in /var/core.
Info
  • This test will NOT check for minidump(s) generated by certain agents in /var/core/minidump.
Examples
anta.tests.system:\n  - VerifyCoreDump:\n
Source code in anta/tests/system.py
class VerifyCoredump(AntaTest):\n    \"\"\"Verifies if there are core dump files in the /var/core directory.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are NO core dump(s) in /var/core.\n    * Failure: The test will fail if there are core dump(s) in /var/core.\n\n    Info\n    ----\n    * This test will NOT check for minidump(s) generated by certain agents in /var/core/minidump.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyCoreDump:\n    ```\n    \"\"\"\n\n    name = \"VerifyCoredump\"\n    description = \"Verifies there are no core dump files.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system coredump\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyCoredump.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        core_files = command_output[\"coreFiles\"]\n        if \"minidump\" in core_files:\n            core_files.remove(\"minidump\")\n        if not core_files:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Core dump(s) have been found: {core_files}\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyFileSystemUtilization","title":"VerifyFileSystemUtilization","text":"

Verifies that no partition is utilizing more than 75% of its disk space.

Expected Results
  • Success: The test will pass if all partitions are using less than 75% of its disk space.
  • Failure: The test will fail if any partitions are using more than 75% of its disk space.
Examples
anta.tests.system:\n  - VerifyFileSystemUtilization:\n
Source code in anta/tests/system.py
class VerifyFileSystemUtilization(AntaTest):\n    \"\"\"Verifies that no partition is utilizing more than 75% of its disk space.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all partitions are using less than 75% of its disk space.\n    * Failure: The test will fail if any partitions are using more than 75% of its disk space.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyFileSystemUtilization:\n    ```\n    \"\"\"\n\n    name = \"VerifyFileSystemUtilization\"\n    description = \"Verifies that no partition is utilizing more than 75% of its disk space.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"bash timeout 10 df -h\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyFileSystemUtilization.\"\"\"\n        command_output = self.instance_commands[0].text_output\n        self.result.is_success()\n        for line in command_output.split(\"\\n\")[1:]:\n            if \"loop\" not in line and len(line) > 0 and (percentage := int(line.split()[4].replace(\"%\", \"\"))) > DISK_SPACE_THRESHOLD:\n                self.result.is_failure(f\"Mount point {line} is higher than 75%: reported {percentage}%\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyMemoryUtilization","title":"VerifyMemoryUtilization","text":"

Verifies whether the memory utilization is below 75%.

Expected Results
  • Success: The test will pass if the memory utilization is below 75%.
  • Failure: The test will fail if the memory utilization is over 75%.
Examples
anta.tests.system:\n  - VerifyMemoryUtilization:\n
Source code in anta/tests/system.py
class VerifyMemoryUtilization(AntaTest):\n    \"\"\"Verifies whether the memory utilization is below 75%.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the memory utilization is below 75%.\n    * Failure: The test will fail if the memory utilization is over 75%.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyMemoryUtilization:\n    ```\n    \"\"\"\n\n    name = \"VerifyMemoryUtilization\"\n    description = \"Verifies whether the memory utilization is below 75%.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show version\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMemoryUtilization.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        memory_usage = command_output[\"memFree\"] / command_output[\"memTotal\"]\n        if memory_usage > MEMORY_THRESHOLD:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device has reported a high memory usage: {(1 - memory_usage)*100:.2f}%\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyNTP","title":"VerifyNTP","text":"

Verifies that the Network Time Protocol (NTP) is synchronized.

Expected Results
  • Success: The test will pass if the NTP is synchronised.
  • Failure: The test will fail if the NTP is NOT synchronised.
Examples
anta.tests.system:\n  - VerifyNTP:\n
Source code in anta/tests/system.py
class VerifyNTP(AntaTest):\n    \"\"\"Verifies that the Network Time Protocol (NTP) is synchronized.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the NTP is synchronised.\n    * Failure: The test will fail if the NTP is NOT synchronised.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyNTP:\n    ```\n    \"\"\"\n\n    name = \"VerifyNTP\"\n    description = \"Verifies if NTP is synchronised.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ntp status\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyNTP.\"\"\"\n        command_output = self.instance_commands[0].text_output\n        if command_output.split(\"\\n\")[0].split(\" \")[0] == \"synchronised\":\n            self.result.is_success()\n        else:\n            data = command_output.split(\"\\n\")[0]\n            self.result.is_failure(f\"The device is not synchronized with the configured NTP server(s): '{data}'\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyReloadCause","title":"VerifyReloadCause","text":"

Verifies the last reload cause of the device.

Expected Results
  • Success: The test will pass if there are NO reload causes or if the last reload was caused by the user or after an FPGA upgrade.
  • Failure: The test will fail if the last reload was NOT caused by the user or after an FPGA upgrade.
  • Error: The test will report an error if the reload cause is NOT available.
Examples
anta.tests.system:\n  - VerifyReloadCause:\n
Source code in anta/tests/system.py
class VerifyReloadCause(AntaTest):\n    \"\"\"Verifies the last reload cause of the device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are NO reload causes or if the last reload was caused by the user or after an FPGA upgrade.\n    * Failure: The test will fail if the last reload was NOT caused by the user or after an FPGA upgrade.\n    * Error: The test will report an error if the reload cause is NOT available.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyReloadCause:\n    ```\n    \"\"\"\n\n    name = \"VerifyReloadCause\"\n    description = \"Verifies the last reload cause of the device.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show reload cause\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyReloadCause.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if \"resetCauses\" not in command_output:\n            self.result.is_error(message=\"No reload causes available\")\n            return\n        if len(command_output[\"resetCauses\"]) == 0:\n            # No reload causes\n            self.result.is_success()\n            return\n        reset_causes = command_output[\"resetCauses\"]\n        command_output_data = reset_causes[0].get(\"description\")\n        if command_output_data in [\n            \"Reload requested by the user.\",\n            \"Reload requested after FPGA upgrade\",\n        ]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Reload cause is: '{command_output_data}'\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyUptime","title":"VerifyUptime","text":"

Verifies if the device uptime is higher than the provided minimum uptime value.

Expected Results
  • Success: The test will pass if the device uptime is higher than the provided value.
  • Failure: The test will fail if the device uptime is lower than the provided value.
Examples
anta.tests.system:\n  - VerifyUptime:\n      minimum: 86400\n
Source code in anta/tests/system.py
class VerifyUptime(AntaTest):\n    \"\"\"Verifies if the device uptime is higher than the provided minimum uptime value.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device uptime is higher than the provided value.\n    * Failure: The test will fail if the device uptime is lower than the provided value.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyUptime:\n          minimum: 86400\n    ```\n    \"\"\"\n\n    name = \"VerifyUptime\"\n    description = \"Verifies the device uptime.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show uptime\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyUptime test.\"\"\"\n\n        minimum: PositiveInteger\n        \"\"\"Minimum uptime in seconds.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyUptime.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"upTime\"] > self.inputs.minimum:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device uptime is {command_output['upTime']} seconds\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyUptime-attributes","title":"Inputs","text":"Name Type Description Default minimum PositiveInteger Minimum uptime in seconds. -"},{"location":"api/tests.vlan/","title":"VLAN","text":""},{"location":"api/tests.vlan/#anta.tests.vlan.VerifyVlanInternalPolicy","title":"VerifyVlanInternalPolicy","text":"

Verifies if the VLAN internal allocation policy is ascending or descending and if the VLANs are within the specified range.

Expected Results
  • Success: The test will pass if the VLAN internal allocation policy is either ascending or descending and the VLANs are within the specified range.
  • Failure: The test will fail if the VLAN internal allocation policy is neither ascending nor descending or the VLANs are outside the specified range.
Examples
anta.tests.vlan:\n  - VerifyVlanInternalPolicy:\n      policy: ascending\n      start_vlan_id: 1006\n      end_vlan_id: 4094\n
Source code in anta/tests/vlan.py
class VerifyVlanInternalPolicy(AntaTest):\n    \"\"\"Verifies if the VLAN internal allocation policy is ascending or descending and if the VLANs are within the specified range.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the VLAN internal allocation policy is either ascending or descending\n                 and the VLANs are within the specified range.\n    * Failure: The test will fail if the VLAN internal allocation policy is neither ascending nor descending\n                 or the VLANs are outside the specified range.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.vlan:\n      - VerifyVlanInternalPolicy:\n          policy: ascending\n          start_vlan_id: 1006\n          end_vlan_id: 4094\n    ```\n    \"\"\"\n\n    name = \"VerifyVlanInternalPolicy\"\n    description = \"Verifies the VLAN internal allocation policy and the range of VLANs.\"\n    categories: ClassVar[list[str]] = [\"vlan\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show vlan internal allocation policy\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyVlanInternalPolicy test.\"\"\"\n\n        policy: Literal[\"ascending\", \"descending\"]\n        \"\"\"The VLAN internal allocation policy. Supported values: ascending, descending.\"\"\"\n        start_vlan_id: Vlan\n        \"\"\"The starting VLAN ID in the range.\"\"\"\n        end_vlan_id: Vlan\n        \"\"\"The ending VLAN ID in the range.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyVlanInternalPolicy.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        keys_to_verify = [\"policy\", \"startVlanId\", \"endVlanId\"]\n        actual_policy_output = {key: get_value(command_output, key) for key in keys_to_verify}\n        expected_policy_output = {\"policy\": self.inputs.policy, \"startVlanId\": self.inputs.start_vlan_id, \"endVlanId\": self.inputs.end_vlan_id}\n\n        # Check if the actual output matches the expected output\n        if actual_policy_output != expected_policy_output:\n            failed_log = \"The VLAN internal allocation policy is not configured properly:\"\n            failed_log += get_failed_logs(expected_policy_output, actual_policy_output)\n            self.result.is_failure(failed_log)\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.vlan/#anta.tests.vlan.VerifyVlanInternalPolicy-attributes","title":"Inputs","text":"Name Type Description Default policy Literal['ascending', 'descending'] The VLAN internal allocation policy. Supported values: ascending, descending. - start_vlan_id Vlan The starting VLAN ID in the range. - end_vlan_id Vlan The ending VLAN ID in the range. -"},{"location":"api/tests.vxlan/","title":"VXLAN","text":""},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlan1ConnSettings","title":"VerifyVxlan1ConnSettings","text":"

Verifies the interface vxlan1 source interface and UDP port.

Expected Results
  • Success: Passes if the interface vxlan1 source interface and UDP port are correct.
  • Failure: Fails if the interface vxlan1 source interface or UDP port are incorrect.
  • Skipped: Skips if the Vxlan1 interface is not configured.
Examples
anta.tests.vxlan:\n  - VerifyVxlan1ConnSettings:\n      source_interface: Loopback1\n      udp_port: 4789\n
Source code in anta/tests/vxlan.py
class VerifyVxlan1ConnSettings(AntaTest):\n    \"\"\"Verifies the interface vxlan1 source interface and UDP port.\n\n    Expected Results\n    ----------------\n    * Success: Passes if the interface vxlan1 source interface and UDP port are correct.\n    * Failure: Fails if the interface vxlan1 source interface or UDP port are incorrect.\n    * Skipped: Skips if the Vxlan1 interface is not configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.vxlan:\n      - VerifyVxlan1ConnSettings:\n          source_interface: Loopback1\n          udp_port: 4789\n    ```\n    \"\"\"\n\n    name = \"VerifyVxlan1ConnSettings\"\n    description = \"Verifies the interface vxlan1 source interface and UDP port.\"\n    categories: ClassVar[list[str]] = [\"vxlan\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyVxlan1ConnSettings test.\"\"\"\n\n        source_interface: VxlanSrcIntf\n        \"\"\"Source loopback interface of vxlan1 interface.\"\"\"\n        udp_port: int = Field(ge=1024, le=65335)\n        \"\"\"UDP port used for vxlan1 interface.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyVxlan1ConnSettings.\"\"\"\n        self.result.is_success()\n        command_output = self.instance_commands[0].json_output\n\n        # Skip the test case if vxlan1 interface is not configured\n        vxlan_output = get_value(command_output, \"interfaces.Vxlan1\")\n        if not vxlan_output:\n            self.result.is_skipped(\"Vxlan1 interface is not configured.\")\n            return\n\n        src_intf = vxlan_output.get(\"srcIpIntf\")\n        port = vxlan_output.get(\"udpPort\")\n\n        # Check vxlan1 source interface and udp port\n        if src_intf != self.inputs.source_interface:\n            self.result.is_failure(f\"Source interface is not correct. Expected `{self.inputs.source_interface}` as source interface but found `{src_intf}` instead.\")\n        if port != self.inputs.udp_port:\n            self.result.is_failure(f\"UDP port is not correct. Expected `{self.inputs.udp_port}` as UDP port but found `{port}` instead.\")\n
"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlan1ConnSettings-attributes","title":"Inputs","text":"Name Type Description Default source_interface VxlanSrcIntf Source loopback interface of vxlan1 interface. - udp_port int UDP port used for vxlan1 interface. Field(ge=1024, le=65335)"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlan1Interface","title":"VerifyVxlan1Interface","text":"

Verifies if the Vxlan1 interface is configured and \u2018up/up\u2019.

Warning

The name of this test has been updated from \u2018VerifyVxlan\u2019 for better representation.

Expected Results
  • Success: The test will pass if the Vxlan1 interface is configured with line protocol status and interface status \u2018up\u2019.
  • Failure: The test will fail if the Vxlan1 interface line protocol status or interface status are not \u2018up\u2019.
  • Skipped: The test will be skipped if the Vxlan1 interface is not configured.
Examples
anta.tests.vxlan:\n  - VerifyVxlan1Interface:\n
Source code in anta/tests/vxlan.py
class VerifyVxlan1Interface(AntaTest):\n    \"\"\"Verifies if the Vxlan1 interface is configured and 'up/up'.\n\n    Warning\n    -------\n    The name of this test has been updated from 'VerifyVxlan' for better representation.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the Vxlan1 interface is configured with line protocol status and interface status 'up'.\n    * Failure: The test will fail if the Vxlan1 interface line protocol status or interface status are not 'up'.\n    * Skipped: The test will be skipped if the Vxlan1 interface is not configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.vxlan:\n      - VerifyVxlan1Interface:\n    ```\n    \"\"\"\n\n    name = \"VerifyVxlan1Interface\"\n    description = \"Verifies the Vxlan1 interface status.\"\n    categories: ClassVar[list[str]] = [\"vxlan\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces description\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyVxlan1Interface.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if \"Vxlan1\" not in command_output[\"interfaceDescriptions\"]:\n            self.result.is_skipped(\"Vxlan1 interface is not configured\")\n        elif (\n            command_output[\"interfaceDescriptions\"][\"Vxlan1\"][\"lineProtocolStatus\"] == \"up\"\n            and command_output[\"interfaceDescriptions\"][\"Vxlan1\"][\"interfaceStatus\"] == \"up\"\n        ):\n            self.result.is_success()\n        else:\n            self.result.is_failure(\n                f\"Vxlan1 interface is {command_output['interfaceDescriptions']['Vxlan1']['lineProtocolStatus']}\"\n                f\"/{command_output['interfaceDescriptions']['Vxlan1']['interfaceStatus']}\",\n            )\n
"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlanConfigSanity","title":"VerifyVxlanConfigSanity","text":"

Verifies that no issues are detected with the VXLAN configuration.

Expected Results
  • Success: The test will pass if no issues are detected with the VXLAN configuration.
  • Failure: The test will fail if issues are detected with the VXLAN configuration.
  • Skipped: The test will be skipped if VXLAN is not configured on the device.
Examples
anta.tests.vxlan:\n  - VerifyVxlanConfigSanity:\n
Source code in anta/tests/vxlan.py
class VerifyVxlanConfigSanity(AntaTest):\n    \"\"\"Verifies that no issues are detected with the VXLAN configuration.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if no issues are detected with the VXLAN configuration.\n    * Failure: The test will fail if issues are detected with the VXLAN configuration.\n    * Skipped: The test will be skipped if VXLAN is not configured on the device.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.vxlan:\n      - VerifyVxlanConfigSanity:\n    ```\n    \"\"\"\n\n    name = \"VerifyVxlanConfigSanity\"\n    description = \"Verifies there are no VXLAN config-sanity inconsistencies.\"\n    categories: ClassVar[list[str]] = [\"vxlan\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show vxlan config-sanity\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyVxlanConfigSanity.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if \"categories\" not in command_output or len(command_output[\"categories\"]) == 0:\n            self.result.is_skipped(\"VXLAN is not configured\")\n            return\n        failed_categories = {\n            category: content\n            for category, content in command_output[\"categories\"].items()\n            if category in [\"localVtep\", \"mlag\", \"pd\"] and content[\"allCheckPass\"] is not True\n        }\n        if len(failed_categories) > 0:\n            self.result.is_failure(f\"VXLAN config sanity check is not passing: {failed_categories}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlanVniBinding","title":"VerifyVxlanVniBinding","text":"

Verifies the VNI-VLAN bindings of the Vxlan1 interface.

Expected Results
  • Success: The test will pass if the VNI-VLAN bindings provided are properly configured.
  • Failure: The test will fail if any VNI lacks bindings or if any bindings are incorrect.
  • Skipped: The test will be skipped if the Vxlan1 interface is not configured.
Examples
anta.tests.vxlan:\n  - VerifyVxlanVniBinding:\n      bindings:\n        10010: 10\n        10020: 20\n
Source code in anta/tests/vxlan.py
class VerifyVxlanVniBinding(AntaTest):\n    \"\"\"Verifies the VNI-VLAN bindings of the Vxlan1 interface.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the VNI-VLAN bindings provided are properly configured.\n    * Failure: The test will fail if any VNI lacks bindings or if any bindings are incorrect.\n    * Skipped: The test will be skipped if the Vxlan1 interface is not configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.vxlan:\n      - VerifyVxlanVniBinding:\n          bindings:\n            10010: 10\n            10020: 20\n    ```\n    \"\"\"\n\n    name = \"VerifyVxlanVniBinding\"\n    description = \"Verifies the VNI-VLAN bindings of the Vxlan1 interface.\"\n    categories: ClassVar[list[str]] = [\"vxlan\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show vxlan vni\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyVxlanVniBinding test.\"\"\"\n\n        bindings: dict[Vni, Vlan]\n        \"\"\"VNI to VLAN bindings to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyVxlanVniBinding.\"\"\"\n        self.result.is_success()\n\n        no_binding = []\n        wrong_binding = []\n\n        if (vxlan1 := get_value(self.instance_commands[0].json_output, \"vxlanIntfs.Vxlan1\")) is None:\n            self.result.is_skipped(\"Vxlan1 interface is not configured\")\n            return\n\n        for vni, vlan in self.inputs.bindings.items():\n            str_vni = str(vni)\n            if str_vni in vxlan1[\"vniBindings\"]:\n                retrieved_vlan = vxlan1[\"vniBindings\"][str_vni][\"vlan\"]\n            elif str_vni in vxlan1[\"vniBindingsToVrf\"]:\n                retrieved_vlan = vxlan1[\"vniBindingsToVrf\"][str_vni][\"vlan\"]\n            else:\n                no_binding.append(str_vni)\n                retrieved_vlan = None\n\n            if retrieved_vlan and vlan != retrieved_vlan:\n                wrong_binding.append({str_vni: retrieved_vlan})\n\n        if no_binding:\n            self.result.is_failure(f\"The following VNI(s) have no binding: {no_binding}\")\n\n        if wrong_binding:\n            self.result.is_failure(f\"The following VNI(s) have the wrong VLAN binding: {wrong_binding}\")\n
"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlanVniBinding-attributes","title":"Inputs","text":"Name Type Description Default bindings dict[Vni, Vlan] VNI to VLAN bindings to verify. -"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlanVtep","title":"VerifyVxlanVtep","text":"

Verifies the VTEP peers of the Vxlan1 interface.

Expected Results
  • Success: The test will pass if all provided VTEP peers are identified and matching.
  • Failure: The test will fail if any VTEP peer is missing or there are unexpected VTEP peers.
  • Skipped: The test will be skipped if the Vxlan1 interface is not configured.
Examples
anta.tests.vxlan:\n  - VerifyVxlanVtep:\n      vteps:\n        - 10.1.1.5\n        - 10.1.1.6\n
Source code in anta/tests/vxlan.py
class VerifyVxlanVtep(AntaTest):\n    \"\"\"Verifies the VTEP peers of the Vxlan1 interface.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all provided VTEP peers are identified and matching.\n    * Failure: The test will fail if any VTEP peer is missing or there are unexpected VTEP peers.\n    * Skipped: The test will be skipped if the Vxlan1 interface is not configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.vxlan:\n      - VerifyVxlanVtep:\n          vteps:\n            - 10.1.1.5\n            - 10.1.1.6\n    ```\n    \"\"\"\n\n    name = \"VerifyVxlanVtep\"\n    description = \"Verifies the VTEP peers of the Vxlan1 interface\"\n    categories: ClassVar[list[str]] = [\"vxlan\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show vxlan vtep\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyVxlanVtep test.\"\"\"\n\n        vteps: list[IPv4Address]\n        \"\"\"List of VTEP peers to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyVxlanVtep.\"\"\"\n        self.result.is_success()\n\n        inputs_vteps = [str(input_vtep) for input_vtep in self.inputs.vteps]\n\n        if (vxlan1 := get_value(self.instance_commands[0].json_output, \"interfaces.Vxlan1\")) is None:\n            self.result.is_skipped(\"Vxlan1 interface is not configured\")\n            return\n\n        difference1 = set(inputs_vteps).difference(set(vxlan1[\"vteps\"]))\n        difference2 = set(vxlan1[\"vteps\"]).difference(set(inputs_vteps))\n\n        if difference1:\n            self.result.is_failure(f\"The following VTEP peer(s) are missing from the Vxlan1 interface: {sorted(difference1)}\")\n\n        if difference2:\n            self.result.is_failure(f\"Unexpected VTEP peer(s) on Vxlan1 interface: {sorted(difference2)}\")\n
"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlanVtep-attributes","title":"Inputs","text":"Name Type Description Default vteps list[IPv4Address] List of VTEP peers to verify. -"},{"location":"api/types/","title":"Input Types","text":""},{"location":"api/types/#anta.custom_types","title":"anta.custom_types","text":"

Module that provides predefined types for AntaTest.Input instances.

"},{"location":"api/types/#anta.custom_types.AAAAuthMethod","title":"AAAAuthMethod module-attribute","text":"
AAAAuthMethod = Annotated[str, AfterValidator(aaa_group_prefix)]\n
"},{"location":"api/types/#anta.custom_types.Afi","title":"Afi module-attribute","text":"
Afi = Literal['ipv4', 'ipv6', 'vpn-ipv4', 'vpn-ipv6', 'evpn', 'rt-membership', 'path-selection', 'link-state']\n
"},{"location":"api/types/#anta.custom_types.BfdInterval","title":"BfdInterval module-attribute","text":"
BfdInterval = Annotated[int, Field(ge=50, le=60000)]\n
"},{"location":"api/types/#anta.custom_types.BfdMultiplier","title":"BfdMultiplier module-attribute","text":"
BfdMultiplier = Annotated[int, Field(ge=3, le=50)]\n
"},{"location":"api/types/#anta.custom_types.EcdsaKeySize","title":"EcdsaKeySize module-attribute","text":"
EcdsaKeySize = Literal[256, 384, 512]\n
"},{"location":"api/types/#anta.custom_types.EncryptionAlgorithm","title":"EncryptionAlgorithm module-attribute","text":"
EncryptionAlgorithm = Literal['RSA', 'ECDSA']\n
"},{"location":"api/types/#anta.custom_types.ErrDisableInterval","title":"ErrDisableInterval module-attribute","text":"
ErrDisableInterval = Annotated[int, Field(ge=30, le=86400)]\n
"},{"location":"api/types/#anta.custom_types.ErrDisableReasons","title":"ErrDisableReasons module-attribute","text":"
ErrDisableReasons = Literal['acl', 'arp-inspection', 'bpduguard', 'dot1x-session-replace', 'hitless-reload-down', 'lacp-rate-limit', 'link-flap', 'no-internal-vlan', 'portchannelguard', 'portsec', 'tapagg', 'uplink-failure-detection']\n
"},{"location":"api/types/#anta.custom_types.EthernetInterface","title":"EthernetInterface module-attribute","text":"
EthernetInterface = Annotated[str, Field(pattern='^Ethernet[0-9]+(\\\\/[0-9]+)*$'), BeforeValidator(interface_autocomplete), BeforeValidator(interface_case_sensitivity)]\n
"},{"location":"api/types/#anta.custom_types.Hostname","title":"Hostname module-attribute","text":"
Hostname = Annotated[str, Field(pattern=REGEXP_TYPE_HOSTNAME)]\n
"},{"location":"api/types/#anta.custom_types.Interface","title":"Interface module-attribute","text":"
Interface = Annotated[str, Field(pattern=REGEXP_TYPE_EOS_INTERFACE), BeforeValidator(interface_autocomplete), BeforeValidator(interface_case_sensitivity)]\n
"},{"location":"api/types/#anta.custom_types.MlagPriority","title":"MlagPriority module-attribute","text":"
MlagPriority = Annotated[int, Field(ge=1, le=32767)]\n
"},{"location":"api/types/#anta.custom_types.MultiProtocolCaps","title":"MultiProtocolCaps module-attribute","text":"
MultiProtocolCaps = Annotated[str, BeforeValidator(bgp_multiprotocol_capabilities_abbreviations)]\n
"},{"location":"api/types/#anta.custom_types.Percent","title":"Percent module-attribute","text":"
Percent = Annotated[float, Field(ge=0.0, le=100.0)]\n
"},{"location":"api/types/#anta.custom_types.Port","title":"Port module-attribute","text":"
Port = Annotated[int, Field(ge=1, le=65535)]\n
"},{"location":"api/types/#anta.custom_types.PositiveInteger","title":"PositiveInteger module-attribute","text":"
PositiveInteger = Annotated[int, Field(ge=0)]\n
"},{"location":"api/types/#anta.custom_types.REGEXP_BGP_IPV4_MPLS_LABELS","title":"REGEXP_BGP_IPV4_MPLS_LABELS module-attribute","text":"
REGEXP_BGP_IPV4_MPLS_LABELS = '\\\\b(ipv4[\\\\s\\\\-]?mpls[\\\\s\\\\-]?label(s)?)\\\\b'\n

Match IPv4 MPLS Labels.

"},{"location":"api/types/#anta.custom_types.REGEXP_BGP_L2VPN_AFI","title":"REGEXP_BGP_L2VPN_AFI module-attribute","text":"
REGEXP_BGP_L2VPN_AFI = '\\\\b(l2[\\\\s\\\\-]?vpn[\\\\s\\\\-]?evpn)\\\\b'\n

Match L2VPN EVPN AFI.

"},{"location":"api/types/#anta.custom_types.REGEXP_EOS_BLACKLIST_CMDS","title":"REGEXP_EOS_BLACKLIST_CMDS module-attribute","text":"
REGEXP_EOS_BLACKLIST_CMDS = ['^reload.*', '^conf\\\\w*\\\\s*(terminal|session)*', '^wr\\\\w*\\\\s*\\\\w+']\n

List of regular expressions to blacklist from eos commands.

"},{"location":"api/types/#anta.custom_types.REGEXP_INTERFACE_ID","title":"REGEXP_INTERFACE_ID module-attribute","text":"
REGEXP_INTERFACE_ID = '\\\\d+(\\\\/\\\\d+)*(\\\\.\\\\d+)?'\n

Match Interface ID lilke 1/1.1.

"},{"location":"api/types/#anta.custom_types.REGEXP_PATH_MARKERS","title":"REGEXP_PATH_MARKERS module-attribute","text":"
REGEXP_PATH_MARKERS = '[\\\\\\\\\\\\/\\\\s]'\n

Match directory path from string.

"},{"location":"api/types/#anta.custom_types.REGEXP_TYPE_EOS_INTERFACE","title":"REGEXP_TYPE_EOS_INTERFACE module-attribute","text":"
REGEXP_TYPE_EOS_INTERFACE = '^(Dps|Ethernet|Fabric|Loopback|Management|Port-Channel|Tunnel|Vlan|Vxlan)[0-9]+(\\\\/[0-9]+)*(\\\\.[0-9]+)?$'\n

Match EOS interface types like Ethernet1/1, Vlan1, Loopback1, etc.

"},{"location":"api/types/#anta.custom_types.REGEXP_TYPE_HOSTNAME","title":"REGEXP_TYPE_HOSTNAME module-attribute","text":"
REGEXP_TYPE_HOSTNAME = '^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\\\-]*[a-zA-Z0-9])\\\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\\\-]*[A-Za-z0-9])$'\n

Match hostname like my-hostname, my-hostname-1, my-hostname-1-2.

"},{"location":"api/types/#anta.custom_types.REGEXP_TYPE_VXLAN_SRC_INTERFACE","title":"REGEXP_TYPE_VXLAN_SRC_INTERFACE module-attribute","text":"
REGEXP_TYPE_VXLAN_SRC_INTERFACE = '^(Loopback)([0-9]|[1-9][0-9]{1,2}|[1-7][0-9]{3}|8[01][0-9]{2}|819[01])$'\n

Match Vxlan source interface like Loopback10.

"},{"location":"api/types/#anta.custom_types.REGEX_BGP_IPV4_MPLS_VPN","title":"REGEX_BGP_IPV4_MPLS_VPN module-attribute","text":"
REGEX_BGP_IPV4_MPLS_VPN = '\\\\b(ipv4[\\\\s\\\\-]?mpls[\\\\s\\\\-]?vpn)\\\\b'\n

Match IPv4 MPLS VPN.

"},{"location":"api/types/#anta.custom_types.REGEX_BGP_IPV4_UNICAST","title":"REGEX_BGP_IPV4_UNICAST module-attribute","text":"
REGEX_BGP_IPV4_UNICAST = '\\\\b(ipv4[\\\\s\\\\-]?uni[\\\\s\\\\-]?cast)\\\\b'\n

Match IPv4 Unicast.

"},{"location":"api/types/#anta.custom_types.RegexString","title":"RegexString module-attribute","text":"
RegexString = Annotated[str, AfterValidator(validate_regex)]\n
"},{"location":"api/types/#anta.custom_types.Revision","title":"Revision module-attribute","text":"
Revision = Annotated[int, Field(ge=1, le=99)]\n
"},{"location":"api/types/#anta.custom_types.RsaKeySize","title":"RsaKeySize module-attribute","text":"
RsaKeySize = Literal[2048, 3072, 4096]\n
"},{"location":"api/types/#anta.custom_types.Safi","title":"Safi module-attribute","text":"
Safi = Literal['unicast', 'multicast', 'labeled-unicast', 'sr-te']\n
"},{"location":"api/types/#anta.custom_types.TestStatus","title":"TestStatus module-attribute","text":"
TestStatus = Literal['unset', 'success', 'failure', 'error', 'skipped']\n
"},{"location":"api/types/#anta.custom_types.Vlan","title":"Vlan module-attribute","text":"
Vlan = Annotated[int, Field(ge=0, le=4094)]\n
"},{"location":"api/types/#anta.custom_types.Vni","title":"Vni module-attribute","text":"
Vni = Annotated[int, Field(ge=1, le=16777215)]\n
"},{"location":"api/types/#anta.custom_types.VxlanSrcIntf","title":"VxlanSrcIntf module-attribute","text":"
VxlanSrcIntf = Annotated[str, Field(pattern=REGEXP_TYPE_VXLAN_SRC_INTERFACE), BeforeValidator(interface_autocomplete), BeforeValidator(interface_case_sensitivity)]\n
"},{"location":"api/types/#anta.custom_types.aaa_group_prefix","title":"aaa_group_prefix","text":"
aaa_group_prefix(v: str) -> str\n

Prefix the AAA method with \u2018group\u2019 if it is known.

Source code in anta/custom_types.py
def aaa_group_prefix(v: str) -> str:\n    \"\"\"Prefix the AAA method with 'group' if it is known.\"\"\"\n    built_in_methods = [\"local\", \"none\", \"logging\"]\n    return f\"group {v}\" if v not in built_in_methods and not v.startswith(\"group \") else v\n
"},{"location":"api/types/#anta.custom_types.bgp_multiprotocol_capabilities_abbreviations","title":"bgp_multiprotocol_capabilities_abbreviations","text":"
bgp_multiprotocol_capabilities_abbreviations(value: str) -> str\n

Abbreviations for different BGP multiprotocol capabilities.

Examples
- IPv4 Unicast\n- L2vpnEVPN\n- ipv4 MPLS Labels\n- ipv4Mplsvpn\n
Source code in anta/custom_types.py
def bgp_multiprotocol_capabilities_abbreviations(value: str) -> str:\n    \"\"\"Abbreviations for different BGP multiprotocol capabilities.\n\n    Examples\n    --------\n        - IPv4 Unicast\n        - L2vpnEVPN\n        - ipv4 MPLS Labels\n        - ipv4Mplsvpn\n\n    \"\"\"\n    patterns = {\n        REGEXP_BGP_L2VPN_AFI: \"l2VpnEvpn\",\n        REGEXP_BGP_IPV4_MPLS_LABELS: \"ipv4MplsLabels\",\n        REGEX_BGP_IPV4_MPLS_VPN: \"ipv4MplsVpn\",\n        REGEX_BGP_IPV4_UNICAST: \"ipv4Unicast\",\n    }\n\n    for pattern, replacement in patterns.items():\n        match = re.search(pattern, value, re.IGNORECASE)\n        if match:\n            return replacement\n\n    return value\n
"},{"location":"api/types/#anta.custom_types.interface_autocomplete","title":"interface_autocomplete","text":"
interface_autocomplete(v: str) -> str\n

Allow the user to only provide the beginning of an interface name.

Supported alias: - et, eth will be changed to Ethernet - po will be changed to Port-Channel - lo will be changed to Loopback

Source code in anta/custom_types.py
def interface_autocomplete(v: str) -> str:\n    \"\"\"Allow the user to only provide the beginning of an interface name.\n\n    Supported alias:\n         - `et`, `eth` will be changed to `Ethernet`\n         - `po` will be changed to `Port-Channel`\n    - `lo` will be changed to `Loopback`\n    \"\"\"\n    intf_id_re = re.compile(REGEXP_INTERFACE_ID)\n    m = intf_id_re.search(v)\n    if m is None:\n        msg = f\"Could not parse interface ID in interface '{v}'\"\n        raise ValueError(msg)\n    intf_id = m[0]\n\n    alias_map = {\"et\": \"Ethernet\", \"eth\": \"Ethernet\", \"po\": \"Port-Channel\", \"lo\": \"Loopback\"}\n\n    return next((f\"{full_name}{intf_id}\" for alias, full_name in alias_map.items() if v.lower().startswith(alias)), v)\n
"},{"location":"api/types/#anta.custom_types.interface_case_sensitivity","title":"interface_case_sensitivity","text":"
interface_case_sensitivity(v: str) -> str\n

Reformat interface name to match expected case sensitivity.

Examples
 - ethernet -> Ethernet\n - vlan -> Vlan\n - loopback -> Loopback\n
Source code in anta/custom_types.py
def interface_case_sensitivity(v: str) -> str:\n    \"\"\"Reformat interface name to match expected case sensitivity.\n\n    Examples\n    --------\n         - ethernet -> Ethernet\n         - vlan -> Vlan\n         - loopback -> Loopback\n\n    \"\"\"\n    if isinstance(v, str) and v != \"\" and not v[0].isupper():\n        return f\"{v[0].upper()}{v[1:]}\"\n    return v\n
"},{"location":"api/types/#anta.custom_types.validate_regex","title":"validate_regex","text":"
validate_regex(value: str) -> str\n

Validate that the input value is a valid regex format.

Source code in anta/custom_types.py
def validate_regex(value: str) -> str:\n    \"\"\"Validate that the input value is a valid regex format.\"\"\"\n    try:\n        re.compile(value)\n    except re.error as e:\n        msg = f\"Invalid regex: {e}\"\n        raise ValueError(msg) from e\n    return value\n
"},{"location":"cli/check/","title":"Check","text":""},{"location":"cli/check/#anta-check-commands","title":"ANTA check commands","text":"

The ANTA check command allow to execute some checks on the ANTA input files. Only checking the catalog is currently supported.

anta check --help\nUsage: anta check [OPTIONS] COMMAND [ARGS]...\n\n  Check commands for building ANTA\n\nOptions:\n  --help  Show this message and exit.\n\nCommands:\n  catalog  Check that the catalog is valid\n
"},{"location":"cli/check/#checking-the-catalog","title":"Checking the catalog","text":"
Usage: anta check catalog [OPTIONS]\n\n  Check that the catalog is valid.\n\nOptions:\n  -c, --catalog FILE            Path to the test catalog file  [env var:\n                                ANTA_CATALOG; required]\n  --catalog-format [yaml|json]  Format of the catalog file, either 'yaml' or\n                                'json'  [env var: ANTA_CATALOG_FORMAT]\n  --help                        Show this message and exit.\n
"},{"location":"cli/debug/","title":"Helpers","text":""},{"location":"cli/debug/#anta-debug-commands","title":"ANTA debug commands","text":"

The ANTA CLI includes a set of debugging tools, making it easier to build and test ANTA content. This functionality is accessed via the debug subcommand and offers the following options:

  • Executing a command on a device from your inventory and retrieving the result.
  • Running a templated command on a device from your inventory and retrieving the result.

These tools are especially helpful in building the tests, as they give a visual access to the output received from the eAPI. They also facilitate the extraction of output content for use in unit tests, as described in our contribution guide.

Warning

The debug tools require a device from your inventory. Thus, you MUST use a valid ANTA Inventory.

"},{"location":"cli/debug/#executing-an-eos-command","title":"Executing an EOS command","text":"

You can use the run-cmd entrypoint to run a command, which includes the following options:

"},{"location":"cli/debug/#command-overview","title":"Command overview","text":"
Usage: anta debug run-cmd [OPTIONS]\n\n  Run arbitrary command to an ANTA device.\n\nOptions:\n  -u, --username TEXT       Username to connect to EOS  [env var:\n                            ANTA_USERNAME; required]\n  -p, --password TEXT       Password to connect to EOS that must be provided.\n                            It can be prompted using '--prompt' option.  [env\n                            var: ANTA_PASSWORD]\n  --enable-password TEXT    Password to access EOS Privileged EXEC mode. It\n                            can be prompted using '--prompt' option. Requires\n                            '--enable' option.  [env var:\n                            ANTA_ENABLE_PASSWORD]\n  --enable                  Some commands may require EOS Privileged EXEC\n                            mode. This option tries to access this mode before\n                            sending a command to the device.  [env var:\n                            ANTA_ENABLE]\n  -P, --prompt              Prompt for passwords if they are not provided.\n                            [env var: ANTA_PROMPT]\n  --timeout FLOAT           Global API timeout. This value will be used for\n                            all devices.  [env var: ANTA_TIMEOUT; default:\n                            30.0]\n  --insecure                Disable SSH Host Key validation.  [env var:\n                            ANTA_INSECURE]\n  --disable-cache           Disable cache globally.  [env var:\n                            ANTA_DISABLE_CACHE]\n  -i, --inventory FILE      Path to the inventory YAML file.  [env var:\n                            ANTA_INVENTORY; required]\n  --tags TEXT               List of tags using comma as separator:\n                            tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  --ofmt [json|text]        EOS eAPI format to use. can be text or json\n  -v, --version [1|latest]  EOS eAPI version\n  -r, --revision INTEGER    eAPI command revision\n  -d, --device TEXT         Device from inventory to use  [required]\n  -c, --command TEXT        Command to run  [required]\n  --help                    Show this message and exit.\n

username, password, enable-password, enable, timeout and insecure values are the same for all devices

"},{"location":"cli/debug/#example","title":"Example","text":"

This example illustrates how to run the show interfaces description command with a JSON format (default):

anta debug run-cmd --command \"show interfaces description\" --device DC1-SPINE1\nRun command show interfaces description on DC1-SPINE1\n{\n    'interfaceDescriptions': {\n        'Ethernet1': {'lineProtocolStatus': 'up', 'description': 'P2P_LINK_TO_DC1-LEAF1A_Ethernet1', 'interfaceStatus': 'up'},\n        'Ethernet2': {'lineProtocolStatus': 'up', 'description': 'P2P_LINK_TO_DC1-LEAF1B_Ethernet1', 'interfaceStatus': 'up'},\n        'Ethernet3': {'lineProtocolStatus': 'up', 'description': 'P2P_LINK_TO_DC1-BL1_Ethernet1', 'interfaceStatus': 'up'},\n        'Ethernet4': {'lineProtocolStatus': 'up', 'description': 'P2P_LINK_TO_DC1-BL2_Ethernet1', 'interfaceStatus': 'up'},\n        'Loopback0': {'lineProtocolStatus': 'up', 'description': 'EVPN_Overlay_Peering', 'interfaceStatus': 'up'},\n        'Management0': {'lineProtocolStatus': 'up', 'description': 'oob_management', 'interfaceStatus': 'up'}\n    }\n}\n
"},{"location":"cli/debug/#executing-an-eos-command-using-templates","title":"Executing an EOS command using templates","text":"

The run-template entrypoint allows the user to provide an f-string templated command. It is followed by a list of arguments (key-value pairs) that build a dictionary used as template parameters.

"},{"location":"cli/debug/#command-overview_1","title":"Command overview","text":"
Usage: anta debug run-template [OPTIONS] PARAMS...\n\n  Run arbitrary templated command to an ANTA device.\n\n  Takes a list of arguments (keys followed by a value) to build a dictionary\n  used as template parameters.\n\n  Example: ------- anta debug run-template -d leaf1a -t 'show vlan {vlan_id}'\n  vlan_id 1\n\nOptions:\n  -u, --username TEXT       Username to connect to EOS  [env var:\n                            ANTA_USERNAME; required]\n  -p, --password TEXT       Password to connect to EOS that must be provided.\n                            It can be prompted using '--prompt' option.  [env\n                            var: ANTA_PASSWORD]\n  --enable-password TEXT    Password to access EOS Privileged EXEC mode. It\n                            can be prompted using '--prompt' option. Requires\n                            '--enable' option.  [env var:\n                            ANTA_ENABLE_PASSWORD]\n  --enable                  Some commands may require EOS Privileged EXEC\n                            mode. This option tries to access this mode before\n                            sending a command to the device.  [env var:\n                            ANTA_ENABLE]\n  -P, --prompt              Prompt for passwords if they are not provided.\n                            [env var: ANTA_PROMPT]\n  --timeout FLOAT           Global API timeout. This value will be used for\n                            all devices.  [env var: ANTA_TIMEOUT; default:\n                            30.0]\n  --insecure                Disable SSH Host Key validation.  [env var:\n                            ANTA_INSECURE]\n  --disable-cache           Disable cache globally.  [env var:\n                            ANTA_DISABLE_CACHE]\n  -i, --inventory FILE      Path to the inventory YAML file.  [env var:\n                            ANTA_INVENTORY; required]\n  --tags TEXT               List of tags using comma as separator:\n                            tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  --ofmt [json|text]        EOS eAPI format to use. can be text or json\n  -v, --version [1|latest]  EOS eAPI version\n  -r, --revision INTEGER    eAPI command revision\n  -d, --device TEXT         Device from inventory to use  [required]\n  -t, --template TEXT       Command template to run. E.g. 'show vlan\n                            {vlan_id}'  [required]\n  --help                    Show this message and exit.\n

username, password, enable-password, enable, timeout and insecure values are the same for all devices

"},{"location":"cli/debug/#example_1","title":"Example","text":"

This example uses the show vlan {vlan_id} command in a JSON format:

anta debug run-template --template \"show vlan {vlan_id}\" vlan_id 10 --device DC1-LEAF1A\nRun templated command 'show vlan {vlan_id}' with {'vlan_id': '10'} on DC1-LEAF1A\n{\n    'vlans': {\n        '10': {\n            'name': 'VRFPROD_VLAN10',\n            'dynamic': False,\n            'status': 'active',\n            'interfaces': {\n                'Cpu': {'privatePromoted': False, 'blocked': None},\n                'Port-Channel11': {'privatePromoted': False, 'blocked': None},\n                'Vxlan1': {'privatePromoted': False, 'blocked': None}\n            }\n        }\n    },\n    'sourceDetail': ''\n}\n

Warning

If multiple arguments of the same key are provided, only the last argument value will be kept in the template parameters.

"},{"location":"cli/debug/#example-of-multiple-arguments","title":"Example of multiple arguments","text":"
anta -log DEBUG debug run-template --template \"ping {dst} source {src}\" dst \"8.8.8.8\" src Loopback0 --device DC1-SPINE1 \u00a0 \u00a0\n> {'dst': '8.8.8.8', 'src': 'Loopback0'}\n\nanta -log DEBUG debug run-template --template \"ping {dst} source {src}\" dst \"8.8.8.8\" src Loopback0 dst \"1.1.1.1\" src Loopback1 --device DC1-SPINE1 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0\n> {'dst': '1.1.1.1', 'src': 'Loopback1'}\n# Notice how `src` and `dst` keep only the latest value\n
"},{"location":"cli/exec/","title":"Execute commands","text":""},{"location":"cli/exec/#executing-commands-on-devices","title":"Executing Commands on Devices","text":"

ANTA CLI provides a set of entrypoints to facilitate remote command execution on EOS devices.

"},{"location":"cli/exec/#exec-command-overview","title":"EXEC Command overview","text":"
anta exec --help\nUsage: anta exec [OPTIONS] COMMAND [ARGS]...\n\n  Execute commands to inventory devices\n\nOptions:\n  --help  Show this message and exit.\n\nCommands:\n  clear-counters        Clear counter statistics on EOS devices\n  collect-tech-support  Collect scheduled tech-support from EOS devices\n  snapshot              Collect commands output from devices in inventory\n
"},{"location":"cli/exec/#clear-interfaces-counters","title":"Clear interfaces counters","text":"

This command clears interface counters on EOS devices specified in your inventory.

"},{"location":"cli/exec/#command-overview","title":"Command overview","text":"
Usage: anta exec clear-counters [OPTIONS]\n\n  Clear counter statistics on EOS devices.\n\nOptions:\n  -u, --username TEXT     Username to connect to EOS  [env var: ANTA_USERNAME;\n                          required]\n  -p, --password TEXT     Password to connect to EOS that must be provided. It\n                          can be prompted using '--prompt' option.  [env var:\n                          ANTA_PASSWORD]\n  --enable-password TEXT  Password to access EOS Privileged EXEC mode. It can\n                          be prompted using '--prompt' option. Requires '--\n                          enable' option.  [env var: ANTA_ENABLE_PASSWORD]\n  --enable                Some commands may require EOS Privileged EXEC mode.\n                          This option tries to access this mode before sending\n                          a command to the device.  [env var: ANTA_ENABLE]\n  -P, --prompt            Prompt for passwords if they are not provided.  [env\n                          var: ANTA_PROMPT]\n  --timeout FLOAT         Global API timeout. This value will be used for all\n                          devices.  [env var: ANTA_TIMEOUT; default: 30.0]\n  --insecure              Disable SSH Host Key validation.  [env var:\n                          ANTA_INSECURE]\n  --disable-cache         Disable cache globally.  [env var:\n                          ANTA_DISABLE_CACHE]\n  -i, --inventory FILE    Path to the inventory YAML file.  [env var:\n                          ANTA_INVENTORY; required]\n  --tags TEXT             List of tags using comma as separator:\n                          tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  --help                  Show this message and exit.\n

username, password, enable-password, enable, timeout and insecure values are the same for all devices

"},{"location":"cli/exec/#example","title":"Example","text":"
anta exec clear-counters --tags SPINE\n[20:19:13] INFO     Connecting to devices...                                                                                                                         utils.py:43\n           INFO     Clearing counters on remote devices...                                                                                                           utils.py:46\n           INFO     Cleared counters on DC1-SPINE2 (cEOSLab)                                                                                                         utils.py:41\n           INFO     Cleared counters on DC2-SPINE1 (cEOSLab)                                                                                                         utils.py:41\n           INFO     Cleared counters on DC1-SPINE1 (cEOSLab)                                                                                                         utils.py:41\n           INFO     Cleared counters on DC2-SPINE2 (cEOSLab)\n
"},{"location":"cli/exec/#collect-a-set-of-commands","title":"Collect a set of commands","text":"

This command collects all the commands specified in a commands-list file, which can be in either json or text format.

"},{"location":"cli/exec/#command-overview_1","title":"Command overview","text":"
Usage: anta exec snapshot [OPTIONS]\n\n  Collect commands output from devices in inventory.\n\nOptions:\n  -u, --username TEXT       Username to connect to EOS  [env var:\n                            ANTA_USERNAME; required]\n  -p, --password TEXT       Password to connect to EOS that must be provided.\n                            It can be prompted using '--prompt' option.  [env\n                            var: ANTA_PASSWORD]\n  --enable-password TEXT    Password to access EOS Privileged EXEC mode. It\n                            can be prompted using '--prompt' option. Requires\n                            '--enable' option.  [env var:\n                            ANTA_ENABLE_PASSWORD]\n  --enable                  Some commands may require EOS Privileged EXEC\n                            mode. This option tries to access this mode before\n                            sending a command to the device.  [env var:\n                            ANTA_ENABLE]\n  -P, --prompt              Prompt for passwords if they are not provided.\n                            [env var: ANTA_PROMPT]\n  --timeout FLOAT           Global API timeout. This value will be used for\n                            all devices.  [env var: ANTA_TIMEOUT; default:\n                            30.0]\n  --insecure                Disable SSH Host Key validation.  [env var:\n                            ANTA_INSECURE]\n  --disable-cache           Disable cache globally.  [env var:\n                            ANTA_DISABLE_CACHE]\n  -i, --inventory FILE      Path to the inventory YAML file.  [env var:\n                            ANTA_INVENTORY; required]\n  --tags TEXT               List of tags using comma as separator:\n                            tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  -c, --commands-list FILE  File with list of commands to collect  [env var:\n                            ANTA_EXEC_SNAPSHOT_COMMANDS_LIST; required]\n  -o, --output DIRECTORY    Directory to save commands output.  [env var:\n                            ANTA_EXEC_SNAPSHOT_OUTPUT; default:\n                            anta_snapshot_2024-04-09_15_56_19]\n  --help                    Show this message and exit.\n

username, password, enable-password, enable, timeout and insecure values are the same for all devices

The commands-list file should follow this structure:

---\njson_format:\n  - show version\ntext_format:\n  - show bfd peers\n
"},{"location":"cli/exec/#example_1","title":"Example","text":"
anta exec snapshot --tags SPINE --commands-list ./commands.yaml --output ./\n[20:25:15] INFO     Connecting to devices...                                                                                                                         utils.py:78\n           INFO     Collecting commands from remote devices                                                                                                          utils.py:81\n           INFO     Collected command 'show version' from device DC2-SPINE1 (cEOSLab)                                                                                utils.py:76\n           INFO     Collected command 'show version' from device DC2-SPINE2 (cEOSLab)                                                                                utils.py:76\n           INFO     Collected command 'show version' from device DC1-SPINE1 (cEOSLab)                                                                                utils.py:76\n           INFO     Collected command 'show version' from device DC1-SPINE2 (cEOSLab)                                                                                utils.py:76\n[20:25:16] INFO     Collected command 'show bfd peers' from device DC2-SPINE2 (cEOSLab)                                                                              utils.py:76\n           INFO     Collected command 'show bfd peers' from device DC2-SPINE1 (cEOSLab)                                                                              utils.py:76\n           INFO     Collected command 'show bfd peers' from device DC1-SPINE1 (cEOSLab)                                                                              utils.py:76\n           INFO     Collected command 'show bfd peers' from device DC1-SPINE2 (cEOSLab)\n

The results of the executed commands will be stored in the output directory specified during command execution:

tree _2023-07-14_20_25_15\n_2023-07-14_20_25_15\n\u251c\u2500\u2500 DC1-SPINE1\n\u2502\u00a0\u00a0 \u251c\u2500\u2500 json\n\u2502\u00a0\u00a0 \u2502\u00a0\u00a0 \u2514\u2500\u2500 show version.json\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 text\n\u2502\u00a0\u00a0     \u2514\u2500\u2500 show bfd peers.log\n\u251c\u2500\u2500 DC1-SPINE2\n\u2502\u00a0\u00a0 \u251c\u2500\u2500 json\n\u2502\u00a0\u00a0 \u2502\u00a0\u00a0 \u2514\u2500\u2500 show version.json\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 text\n\u2502\u00a0\u00a0     \u2514\u2500\u2500 show bfd peers.log\n\u251c\u2500\u2500 DC2-SPINE1\n\u2502\u00a0\u00a0 \u251c\u2500\u2500 json\n\u2502\u00a0\u00a0 \u2502\u00a0\u00a0 \u2514\u2500\u2500 show version.json\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 text\n\u2502\u00a0\u00a0     \u2514\u2500\u2500 show bfd peers.log\n\u2514\u2500\u2500 DC2-SPINE2\n    \u251c\u2500\u2500 json\n    \u2502\u00a0\u00a0 \u2514\u2500\u2500 show version.json\n    \u2514\u2500\u2500 text\n        \u2514\u2500\u2500 show bfd peers.log\n\n12 directories, 8 files\n
"},{"location":"cli/exec/#get-scheduled-tech-support","title":"Get Scheduled tech-support","text":"

EOS offers a feature that automatically creates a tech-support archive every hour by default. These archives are stored under /mnt/flash/schedule/tech-support.

leaf1#show schedule summary\nMaximum concurrent jobs  1\nPrepend host name to logfile: Yes\nName                 At Time       Last        Interval       Timeout        Max        Max     Logfile Location                  Status\n                                   Time         (mins)        (mins)         Log        Logs\n                                                                            Files       Size\n----------------- ------------- ----------- -------------- ------------- ----------- ---------- --------------------------------- ------\ntech-support           now         08:37          60            30           100         -      flash:schedule/tech-support/      Success\n\n\nleaf1#bash ls /mnt/flash/schedule/tech-support\nleaf1_tech-support_2023-03-09.1337.log.gz  leaf1_tech-support_2023-03-10.0837.log.gz  leaf1_tech-support_2023-03-11.0337.log.gz\n

For Network Readiness for Use (NRFU) tests and to keep a comprehensive report of the system state before going live, ANTA provides a command-line interface that efficiently retrieves these files.

"},{"location":"cli/exec/#command-overview_2","title":"Command overview","text":"
Usage: anta exec collect-tech-support [OPTIONS]\n\n  Collect scheduled tech-support from EOS devices.\n\nOptions:\n  -u, --username TEXT     Username to connect to EOS  [env var: ANTA_USERNAME;\n                          required]\n  -p, --password TEXT     Password to connect to EOS that must be provided. It\n                          can be prompted using '--prompt' option.  [env var:\n                          ANTA_PASSWORD]\n  --enable-password TEXT  Password to access EOS Privileged EXEC mode. It can\n                          be prompted using '--prompt' option. Requires '--\n                          enable' option.  [env var: ANTA_ENABLE_PASSWORD]\n  --enable                Some commands may require EOS Privileged EXEC mode.\n                          This option tries to access this mode before sending\n                          a command to the device.  [env var: ANTA_ENABLE]\n  -P, --prompt            Prompt for passwords if they are not provided.  [env\n                          var: ANTA_PROMPT]\n  --timeout FLOAT         Global API timeout. This value will be used for all\n                          devices.  [env var: ANTA_TIMEOUT; default: 30.0]\n  --insecure              Disable SSH Host Key validation.  [env var:\n                          ANTA_INSECURE]\n  --disable-cache         Disable cache globally.  [env var:\n                          ANTA_DISABLE_CACHE]\n  -i, --inventory FILE    Path to the inventory YAML file.  [env var:\n                          ANTA_INVENTORY; required]\n  --tags TEXT             List of tags using comma as separator:\n                          tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  -o, --output PATH       Path for test catalog  [default: ./tech-support]\n  --latest INTEGER        Number of scheduled show-tech to retrieve\n  --configure             Ensure devices have 'aaa authorization exec default\n                          local' configured (required for SCP on EOS). THIS\n                          WILL CHANGE THE CONFIGURATION OF YOUR NETWORK.\n  --help                  Show this message and exit.\n

username, password, enable-password, enable, timeout and insecure values are the same for all devices

When executed, this command fetches tech-support files and downloads them locally into a device-specific subfolder within the designated folder. You can specify the output folder with the --output option.

ANTA uses SCP to download files from devices and will not trust unknown SSH hosts by default. Add the SSH public keys of your devices to your known_hosts file or use the anta --insecure option to ignore SSH host keys validation.

The configuration aaa authorization exec default must be present on devices to be able to use SCP. ANTA can automatically configure aaa authorization exec default local using the anta exec collect-tech-support --configure option. If you require specific AAA configuration for aaa authorization exec default, like aaa authorization exec default none or aaa authorization exec default group tacacs+, you will need to configure it manually.

The --latest option allows retrieval of a specific number of the most recent tech-support files.

Warning

By default all the tech-support files present on the devices are retrieved.

"},{"location":"cli/exec/#example_2","title":"Example","text":"
anta --insecure exec collect-tech-support\n[15:27:19] INFO     Connecting to devices...\nINFO     Copying '/mnt/flash/schedule/tech-support/spine1_tech-support_2023-06-09.1315.log.gz' from device spine1 to 'tech-support/spine1' locally\nINFO     Copying '/mnt/flash/schedule/tech-support/leaf3_tech-support_2023-06-09.1315.log.gz' from device leaf3 to 'tech-support/leaf3' locally\nINFO     Copying '/mnt/flash/schedule/tech-support/leaf1_tech-support_2023-06-09.1315.log.gz' from device leaf1 to 'tech-support/leaf1' locally\nINFO     Copying '/mnt/flash/schedule/tech-support/leaf2_tech-support_2023-06-09.1315.log.gz' from device leaf2 to 'tech-support/leaf2' locally\nINFO     Copying '/mnt/flash/schedule/tech-support/spine2_tech-support_2023-06-09.1315.log.gz' from device spine2 to 'tech-support/spine2' locally\nINFO     Copying '/mnt/flash/schedule/tech-support/leaf4_tech-support_2023-06-09.1315.log.gz' from device leaf4 to 'tech-support/leaf4' locally\nINFO     Collected 1 scheduled tech-support from leaf2\nINFO     Collected 1 scheduled tech-support from spine2\nINFO     Collected 1 scheduled tech-support from leaf3\nINFO     Collected 1 scheduled tech-support from spine1\nINFO     Collected 1 scheduled tech-support from leaf1\nINFO     Collected 1 scheduled tech-support from leaf4\n

The output folder structure is as follows:

tree tech-support/\ntech-support/\n\u251c\u2500\u2500 leaf1\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 leaf1_tech-support_2023-06-09.1315.log.gz\n\u251c\u2500\u2500 leaf2\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 leaf2_tech-support_2023-06-09.1315.log.gz\n\u251c\u2500\u2500 leaf3\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 leaf3_tech-support_2023-06-09.1315.log.gz\n\u251c\u2500\u2500 leaf4\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 leaf4_tech-support_2023-06-09.1315.log.gz\n\u251c\u2500\u2500 spine1\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 spine1_tech-support_2023-06-09.1315.log.gz\n\u2514\u2500\u2500 spine2\n    \u2514\u2500\u2500 spine2_tech-support_2023-06-09.1315.log.gz\n\n6 directories, 6 files\n

Each device has its own subdirectory containing the collected tech-support files.

"},{"location":"cli/get-inventory-information/","title":"Get Inventory Information","text":""},{"location":"cli/get-inventory-information/#retrieving-inventory-information","title":"Retrieving Inventory Information","text":"

The ANTA CLI offers multiple entrypoints to access data from your local inventory.

"},{"location":"cli/get-inventory-information/#inventory-used-of-examples","title":"Inventory used of examples","text":"

Let\u2019s consider the following inventory:

---\nanta_inventory:\n  hosts:\n    - host: 172.20.20.101\n      name: DC1-SPINE1\n      tags: [\"SPINE\", \"DC1\"]\n\n    - host: 172.20.20.102\n      name: DC1-SPINE2\n      tags: [\"SPINE\", \"DC1\"]\n\n    - host: 172.20.20.111\n      name: DC1-LEAF1A\n      tags: [\"LEAF\", \"DC1\"]\n\n    - host: 172.20.20.112\n      name: DC1-LEAF1B\n      tags: [\"LEAF\", \"DC1\"]\n\n    - host: 172.20.20.121\n      name: DC1-BL1\n      tags: [\"BL\", \"DC1\"]\n\n    - host: 172.20.20.122\n      name: DC1-BL2\n      tags: [\"BL\", \"DC1\"]\n\n    - host: 172.20.20.201\n      name: DC2-SPINE1\n      tags: [\"SPINE\", \"DC2\"]\n\n    - host: 172.20.20.202\n      name: DC2-SPINE2\n      tags: [\"SPINE\", \"DC2\"]\n\n    - host: 172.20.20.211\n      name: DC2-LEAF1A\n      tags: [\"LEAF\", \"DC2\"]\n\n    - host: 172.20.20.212\n      name: DC2-LEAF1B\n      tags: [\"LEAF\", \"DC2\"]\n\n    - host: 172.20.20.221\n      name: DC2-BL1\n      tags: [\"BL\", \"DC2\"]\n\n    - host: 172.20.20.222\n      name: DC2-BL2\n      tags: [\"BL\", \"DC2\"]\n
"},{"location":"cli/get-inventory-information/#obtaining-all-configured-tags","title":"Obtaining all configured tags","text":"

As most of ANTA\u2019s commands accommodate tag filtering, this particular command is useful for enumerating all tags configured in the inventory. Running the anta get tags command will return a list of all tags that have been configured in the inventory.

"},{"location":"cli/get-inventory-information/#command-overview","title":"Command overview","text":"
Usage: anta get tags [OPTIONS]\n\n  Get list of configured tags in user inventory.\n\nOptions:\n  -u, --username TEXT     Username to connect to EOS  [env var: ANTA_USERNAME;\n                          required]\n  -p, --password TEXT     Password to connect to EOS that must be provided. It\n                          can be prompted using '--prompt' option.  [env var:\n                          ANTA_PASSWORD]\n  --enable-password TEXT  Password to access EOS Privileged EXEC mode. It can\n                          be prompted using '--prompt' option. Requires '--\n                          enable' option.  [env var: ANTA_ENABLE_PASSWORD]\n  --enable                Some commands may require EOS Privileged EXEC mode.\n                          This option tries to access this mode before sending\n                          a command to the device.  [env var: ANTA_ENABLE]\n  -P, --prompt            Prompt for passwords if they are not provided.  [env\n                          var: ANTA_PROMPT]\n  --timeout FLOAT         Global API timeout. This value will be used for all\n                          devices.  [env var: ANTA_TIMEOUT; default: 30.0]\n  --insecure              Disable SSH Host Key validation.  [env var:\n                          ANTA_INSECURE]\n  --disable-cache         Disable cache globally.  [env var:\n                          ANTA_DISABLE_CACHE]\n  -i, --inventory FILE    Path to the inventory YAML file.  [env var:\n                          ANTA_INVENTORY; required]\n  --tags TEXT             List of tags using comma as separator:\n                          tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  --help                  Show this message and exit.\n
"},{"location":"cli/get-inventory-information/#example","title":"Example","text":"

To get the list of all configured tags in the inventory, run the following command:

anta get tags\nTags found:\n[\n  \"BL\",\n  \"DC1\",\n  \"DC2\",\n  \"LEAF\",\n  \"SPINE\"\n]\n\n* note that tag all has been added by anta\n

Note

Even if you haven\u2019t explicitly configured the all tag in the inventory, it is automatically added. This default tag allows to execute commands on all devices in the inventory when no tag is specified.

"},{"location":"cli/get-inventory-information/#list-devices-in-inventory","title":"List devices in inventory","text":"

This command will list all devices available in the inventory. Using the --tags option, you can filter this list to only include devices with specific tags. The --connected option allows to display only the devices where a connection has been established.

"},{"location":"cli/get-inventory-information/#command-overview_1","title":"Command overview","text":"
Usage: anta get inventory [OPTIONS]\n\n  Show inventory loaded in ANTA.\n\nOptions:\n  -u, --username TEXT            Username to connect to EOS  [env var:\n                                 ANTA_USERNAME; required]\n  -p, --password TEXT            Password to connect to EOS that must be\n                                 provided. It can be prompted using '--prompt'\n                                 option.  [env var: ANTA_PASSWORD]\n  --enable-password TEXT         Password to access EOS Privileged EXEC mode.\n                                 It can be prompted using '--prompt' option.\n                                 Requires '--enable' option.  [env var:\n                                 ANTA_ENABLE_PASSWORD]\n  --enable                       Some commands may require EOS Privileged EXEC\n                                 mode. This option tries to access this mode\n                                 before sending a command to the device.  [env\n                                 var: ANTA_ENABLE]\n  -P, --prompt                   Prompt for passwords if they are not\n                                 provided.  [env var: ANTA_PROMPT]\n  --timeout FLOAT                Global API timeout. This value will be used\n                                 for all devices.  [env var: ANTA_TIMEOUT;\n                                 default: 30.0]\n  --insecure                     Disable SSH Host Key validation.  [env var:\n                                 ANTA_INSECURE]\n  --disable-cache                Disable cache globally.  [env var:\n                                 ANTA_DISABLE_CACHE]\n  -i, --inventory FILE           Path to the inventory YAML file.  [env var:\n                                 ANTA_INVENTORY; required]\n  --tags TEXT                    List of tags using comma as separator:\n                                 tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  --connected / --not-connected  Display inventory after connection has been\n                                 created\n  --help                         Show this message and exit.\n

Tip

In its default mode, anta get inventory provides only information that doesn\u2019t rely on a device connection. If you are interested in obtaining connection-dependent details, like the hardware model, please use the --connected option.

"},{"location":"cli/get-inventory-information/#example_1","title":"Example","text":"

To retrieve a comprehensive list of all devices along with their details, execute the following command. It will provide all the data loaded into the ANTA inventory from your inventory file.

anta get inventory --tags SPINE\nCurrent inventory content is:\n{\n    'DC1-SPINE1': AsyncEOSDevice(\n        name='DC1-SPINE1',\n        tags=['SPINE', 'DC1'],\n        hw_model=None,\n        is_online=False,\n        established=False,\n        disable_cache=False,\n        host='172.20.20.101',\n        eapi_port=443,\n        username='arista',\n        enable=True,\n        enable_password='arista',\n        insecure=False\n    ),\n    'DC1-SPINE2': AsyncEOSDevice(\n        name='DC1-SPINE2',\n        tags=['SPINE', 'DC1'],\n        hw_model=None,\n        is_online=False,\n        established=False,\n        disable_cache=False,\n        host='172.20.20.102',\n        eapi_port=443,\n        username='arista',\n        enable=True,\n        insecure=False\n    ),\n    'DC2-SPINE1': AsyncEOSDevice(\n        name='DC2-SPINE1',\n        tags=['SPINE', 'DC2'],\n        hw_model=None,\n        is_online=False,\n        established=False,\n        disable_cache=False,\n        host='172.20.20.201',\n        eapi_port=443,\n        username='arista',\n        enable=True,\n        insecure=False\n    ),\n    'DC2-SPINE2': AsyncEOSDevice(\n        name='DC2-SPINE2',\n        tags=['SPINE', 'DC2'],\n        hw_model=None,\n        is_online=False,\n        established=False,\n        disable_cache=False,\n        host='172.20.20.202',\n        eapi_port=443,\n        username='arista',\n        enable=True,\n        insecure=False\n    )\n}\n
"},{"location":"cli/inv-from-ansible/","title":"Inventory from Ansible","text":""},{"location":"cli/inv-from-ansible/#create-an-inventory-from-ansible-inventory","title":"Create an Inventory from Ansible inventory","text":"

In large setups, it might be beneficial to construct your inventory based on your Ansible inventory. The from-ansible entrypoint of the get command enables the user to create an ANTA inventory from Ansible.

"},{"location":"cli/inv-from-ansible/#command-overview","title":"Command overview","text":"
$ anta get from-ansible --help\nUsage: anta get from-ansible [OPTIONS]\n\n  Build ANTA inventory from an ansible inventory YAML file.\n\n  NOTE: This command does not support inline vaulted variables. Make sure to\n  comment them out.\n\nOptions:\n  -o, --output FILE         Path to save inventory file  [env var:\n                            ANTA_INVENTORY; required]\n  --overwrite               Do not prompt when overriding current inventory\n                            [env var: ANTA_GET_FROM_ANSIBLE_OVERWRITE]\n  -g, --ansible-group TEXT  Ansible group to filter\n  --ansible-inventory FILE  Path to your ansible inventory file to read\n                            [required]\n  --help                    Show this message and exit.\n

Warning

anta get from-ansible does not support inline vaulted variables, comment them out to generate your inventory. If the vaulted variable is necessary to build the inventory (e.g. ansible_host), it needs to be unvaulted for from-ansible command to work.\u201d

The output is an inventory where the name of the container is added as a tag for each host:

anta_inventory:\n  hosts:\n  - host: 10.73.252.41\n    name: srv-pod01\n  - host: 10.73.252.42\n    name: srv-pod02\n  - host: 10.73.252.43\n    name: srv-pod03\n

Warning

The current implementation only considers devices directly attached to a specific Ansible group and does not support inheritance when using the --ansible-group option.

By default, if user does not provide --output file, anta will save output to configured anta inventory (anta --inventory). If the output file has content, anta will ask user to overwrite when running in interactive console. This mechanism can be controlled by triggers in case of CI usage: --overwrite to force anta to overwrite file. If not set, anta will exit

"},{"location":"cli/inv-from-ansible/#command-output","title":"Command output","text":"

host value is coming from the ansible_host key in your inventory while name is the name you defined for your host. Below is an ansible inventory example used to generate previous inventory:

---\ntooling:\n  children:\n    endpoints:\n      hosts:\n        srv-pod01:\n          ansible_httpapi_port: 9023\n          ansible_port: 9023\n          ansible_host: 10.73.252.41\n          type: endpoint\n        srv-pod02:\n          ansible_httpapi_port: 9024\n          ansible_port: 9024\n          ansible_host: 10.73.252.42\n          type: endpoint\n        srv-pod03:\n          ansible_httpapi_port: 9025\n          ansible_port: 9025\n          ansible_host: 10.73.252.43\n          type: endpoint\n
"},{"location":"cli/inv-from-cvp/","title":"Inventory from CVP","text":""},{"location":"cli/inv-from-cvp/#create-an-inventory-from-cloudvision","title":"Create an Inventory from CloudVision","text":"

In large setups, it might be beneficial to construct your inventory based on CloudVision. The from-cvp entrypoint of the get command enables the user to create an ANTA inventory from CloudVision.

Info

The current implementation only works with on-premises CloudVision instances, not with CloudVision as a Service (CVaaS).

"},{"location":"cli/inv-from-cvp/#command-overview","title":"Command overview","text":"
Usage: anta get from-cvp [OPTIONS]\n\n  Build ANTA inventory from CloudVision.\n\n  NOTE: Only username/password authentication is supported for on-premises CloudVision instances.\n  Token authentication for both on-premises and CloudVision as a Service (CVaaS) is not supported.\n\nOptions:\n  -o, --output FILE     Path to save inventory file  [env var: ANTA_INVENTORY;\n                        required]\n  --overwrite           Do not prompt when overriding current inventory  [env\n                        var: ANTA_GET_FROM_CVP_OVERWRITE]\n  -host, --host TEXT    CloudVision instance FQDN or IP  [required]\n  -u, --username TEXT   CloudVision username  [required]\n  -p, --password TEXT   CloudVision password  [required]\n  -c, --container TEXT  CloudVision container where devices are configured\n  --ignore-cert         By default connection to CV will use HTTPS\n                        certificate, set this flag to disable it  [env var:\n                        ANTA_GET_FROM_CVP_IGNORE_CERT]\n  --help                Show this message and exit.\n

The output is an inventory where the name of the container is added as a tag for each host:

anta_inventory:\n  hosts:\n  - host: 192.168.0.13\n    name: leaf2\n    tags:\n    - pod1\n  - host: 192.168.0.15\n    name: leaf4\n    tags:\n    - pod2\n

Warning

The current implementation only considers devices directly attached to a specific container when using the --cvp-container option.

"},{"location":"cli/inv-from-cvp/#creating-an-inventory-from-multiple-containers","title":"Creating an inventory from multiple containers","text":"

If you need to create an inventory from multiple containers, you can use a bash command and then manually concatenate files to create a single inventory file:

$ for container in pod01 pod02 spines; do anta get from-cvp -ip <cvp-ip> -u cvpadmin -p cvpadmin -c $container -d test-inventory; done\n\n[12:25:35] INFO     Getting auth token from cvp.as73.inetsix.net for user tom\n[12:25:36] INFO     Creating inventory folder /home/tom/Projects/arista/network-test-automation/test-inventory\n           WARNING  Using the new api_token parameter. This will override usage of the cvaas_token parameter if both are provided. This is because api_token and cvaas_token parameters\n                    are for the same use case and api_token is more generic\n           INFO     Connected to CVP cvp.as73.inetsix.net\n\n\n[12:25:37] INFO     Getting auth token from cvp.as73.inetsix.net for user tom\n[12:25:38] WARNING  Using the new api_token parameter. This will override usage of the cvaas_token parameter if both are provided. This is because api_token and cvaas_token parameters\n                    are for the same use case and api_token is more generic\n           INFO     Connected to CVP cvp.as73.inetsix.net\n\n\n[12:25:38] INFO     Getting auth token from cvp.as73.inetsix.net for user tom\n[12:25:39] WARNING  Using the new api_token parameter. This will override usage of the cvaas_token parameter if both are provided. This is because api_token and cvaas_token parameters\n                    are for the same use case and api_token is more generic\n           INFO     Connected to CVP cvp.as73.inetsix.net\n\n           INFO     Inventory file has been created in /home/tom/Projects/arista/network-test-automation/test-inventory/inventory-spines.yml\n
"},{"location":"cli/nrfu/","title":"NRFU","text":""},{"location":"cli/nrfu/#execute-network-readiness-for-use-nrfu-testing","title":"Execute Network Readiness For Use (NRFU) Testing","text":"

ANTA provides a set of commands for performing NRFU tests on devices. These commands are under the anta nrfu namespace and offer multiple output format options:

  • Text view
  • Table view
  • JSON view
  • Custom template view
"},{"location":"cli/nrfu/#nrfu-command-overview","title":"NRFU Command overview","text":"
Usage: anta nrfu [OPTIONS] COMMAND [ARGS]...\n\n  Run ANTA tests on selected inventory devices.\n\nOptions:\n  -u, --username TEXT             Username to connect to EOS  [env var:\n                                  ANTA_USERNAME; required]\n  -p, --password TEXT             Password to connect to EOS that must be\n                                  provided. It can be prompted using '--\n                                  prompt' option.  [env var: ANTA_PASSWORD]\n  --enable-password TEXT          Password to access EOS Privileged EXEC mode.\n                                  It can be prompted using '--prompt' option.\n                                  Requires '--enable' option.  [env var:\n                                  ANTA_ENABLE_PASSWORD]\n  --enable                        Some commands may require EOS Privileged\n                                  EXEC mode. This option tries to access this\n                                  mode before sending a command to the device.\n                                  [env var: ANTA_ENABLE]\n  -P, --prompt                    Prompt for passwords if they are not\n                                  provided.  [env var: ANTA_PROMPT]\n  --timeout FLOAT                 Global API timeout. This value will be used\n                                  for all devices.  [env var: ANTA_TIMEOUT;\n                                  default: 30.0]\n  --insecure                      Disable SSH Host Key validation.  [env var:\n                                  ANTA_INSECURE]\n  --disable-cache                 Disable cache globally.  [env var:\n                                  ANTA_DISABLE_CACHE]\n  -i, --inventory FILE            Path to the inventory YAML file.  [env var:\n                                  ANTA_INVENTORY; required]\n  --tags TEXT                     List of tags using comma as separator:\n                                  tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  -c, --catalog FILE              Path to the test catalog file  [env var:\n                                  ANTA_CATALOG; required]\n  --catalog-format [yaml|json]    Format of the catalog file, either 'yaml' or\n                                  'json'  [env var: ANTA_CATALOG_FORMAT]\n  -d, --device TEXT               Run tests on a specific device. Can be\n                                  provided multiple times.\n  -t, --test TEXT                 Run a specific test. Can be provided\n                                  multiple times.\n  --ignore-status                 Exit code will always be 0.  [env var:\n                                  ANTA_NRFU_IGNORE_STATUS]\n  --ignore-error                  Exit code will be 0 if all tests succeeded\n                                  or 1 if any test failed.  [env var:\n                                  ANTA_NRFU_IGNORE_ERROR]\n  --hide [success|failure|error|skipped]\n                                  Group result by test or device.\n  --dry-run                       Run anta nrfu command but stop before\n                                  starting to execute the tests. Considers all\n                                  devices as connected.  [env var:\n                                  ANTA_NRFU_DRY_RUN]\n  --help                          Show this message and exit.\n\nCommands:\n  json        ANTA command to check network state with JSON result.\n  table       ANTA command to check network states with table result.\n  text        ANTA command to check network states with text result.\n  tpl-report  ANTA command to check network state with templated report.\n

username, password, enable-password, enable, timeout and insecure values are the same for all devices

All commands under the anta nrfu namespace require a catalog yaml file specified with the --catalog option and a device inventory file specified with the --inventory option.

Info

Issuing the command anta nrfu will run anta nrfu table without any option.

"},{"location":"cli/nrfu/#tag-management","title":"Tag management","text":"

The --tags option can be used to target specific devices in your inventory and run only tests configured with this specific tags from your catalog. The default tag is set to all and is implicit. Expected behaviour is provided below:

Command Description none Run all tests on all devices according tag definition in your inventory and test catalog. And tests with no tag are executed on all devices --tags leaf Run all tests marked with leaf tag on all devices configured with leaf tag. All other tags are ignored --tags leaf,spine Run all tests marked with leaf tag on all devices configured with leaf tag.Run all tests marked with spine tag on all devices configured with spine tag. All other tags are ignored

Info

More examples available on this dedicated page.

"},{"location":"cli/nrfu/#device-and-test-filtering","title":"Device and test filtering","text":"

Options --device and --test can be used to target one or multiple devices and/or tests to run in your environment. The options can be repeated. Example: anta nrfu --device leaf1a --device leaf1b --test VerifyUptime --test VerifyReloadCause.

"},{"location":"cli/nrfu/#hide-results","title":"Hide results","text":"

Option --hide can be used to hide test results in the output based on their status. The option can be repeated. Example: anta nrfu --hide error --hide skipped.

"},{"location":"cli/nrfu/#performing-nrfu-with-text-rendering","title":"Performing NRFU with text rendering","text":"

The text subcommand provides a straightforward text report for each test executed on all devices in your inventory.

"},{"location":"cli/nrfu/#command-overview","title":"Command overview","text":"
Usage: anta nrfu text [OPTIONS]\n\n  ANTA command to check network states with text result.\n\nOptions:\n  --help  Show this message and exit.\n
"},{"location":"cli/nrfu/#example","title":"Example","text":"

anta nrfu --device DC1-LEAF1A text\n

"},{"location":"cli/nrfu/#performing-nrfu-with-table-rendering","title":"Performing NRFU with table rendering","text":"

The table command under the anta nrfu namespace offers a clear and organized table view of the test results, suitable for filtering. It also has its own set of options for better control over the output.

"},{"location":"cli/nrfu/#command-overview_1","title":"Command overview","text":"
Usage: anta nrfu table [OPTIONS]\n\n  ANTA command to check network states with table result.\n\nOptions:\n  --group-by [device|test]  Group result by test or device.\n  --help                    Show this message and exit.\n

The --group-by option show a summarized view of the test results per host or per test.

"},{"location":"cli/nrfu/#examples","title":"Examples","text":"

anta nrfu --tags LEAF table\n

For larger setups, you can also group the results by host or test to get a summarized view:

anta nrfu table --group-by device\n

anta nrfu table --group-by test\n

To get more specific information, it is possible to filter on a single device or a single test:

anta nrfu --device spine1 table\n

anta nrfu --test VerifyZeroTouch table\n

"},{"location":"cli/nrfu/#performing-nrfu-with-json-rendering","title":"Performing NRFU with JSON rendering","text":"

The JSON rendering command in NRFU testing is useful in generating a JSON output that can subsequently be passed on to another tool for reporting purposes.

"},{"location":"cli/nrfu/#command-overview_2","title":"Command overview","text":"
anta nrfu json --help\nUsage: anta nrfu json [OPTIONS]\n\n  ANTA command to check network state with JSON result.\n\nOptions:\n  -o, --output FILE  Path to save report as a file  [env var:\n                     ANTA_NRFU_JSON_OUTPUT]\n  --help             Show this message and exit.\n

The --output option allows you to save the JSON report as a file.

"},{"location":"cli/nrfu/#example_1","title":"Example","text":"

anta nrfu --tags LEAF json\n

"},{"location":"cli/nrfu/#performing-nrfu-with-custom-reports","title":"Performing NRFU with custom reports","text":"

ANTA offers a CLI option for creating custom reports. This leverages the Jinja2 template system, allowing you to tailor reports to your specific needs.

"},{"location":"cli/nrfu/#command-overview_3","title":"Command overview","text":"

anta nrfu tpl-report --help\nUsage: anta nrfu tpl-report [OPTIONS]\n\n  ANTA command to check network state with templated report\n\nOptions:\n  -tpl, --template FILE  Path to the template to use for the report  [env var:\n                         ANTA_NRFU_TPL_REPORT_TEMPLATE; required]\n  -o, --output FILE      Path to save report as a file  [env var:\n                         ANTA_NRFU_TPL_REPORT_OUTPUT]\n  --help                 Show this message and exit.\n
The --template option is used to specify the Jinja2 template file for generating the custom report.

The --output option allows you to choose the path where the final report will be saved.

"},{"location":"cli/nrfu/#example_2","title":"Example","text":"

anta nrfu --tags LEAF tpl-report --template ./custom_template.j2\n

The template ./custom_template.j2 is a simple Jinja2 template:

{% for d in data %}\n* {{ d.test }} is [green]{{ d.result | upper}}[/green] for {{ d.name }}\n{% endfor %}\n

The Jinja2 template has access to all TestResult elements and their values, as described in this documentation.

You can also save the report result to a file using the --output option:

anta nrfu --tags LEAF tpl-report --template ./custom_template.j2 --output nrfu-tpl-report.txt\n

The resulting output might look like this:

cat nrfu-tpl-report.txt\n* VerifyMlagStatus is [green]SUCCESS[/green] for DC1-LEAF1A\n* VerifyMlagInterfaces is [green]SUCCESS[/green] for DC1-LEAF1A\n* VerifyMlagConfigSanity is [green]SUCCESS[/green] for DC1-LEAF1A\n* VerifyMlagReloadDelay is [green]SUCCESS[/green] for DC1-LEAF1A\n
"},{"location":"cli/nrfu/#dry-run-mode","title":"Dry-run mode","text":"

It is possible to run anta nrfu --dry-run to execute ANTA up to the point where it should communicate with the network to execute the tests. When using --dry-run, all inventory devices are assumed to be online. This can be useful to check how many tests would be run using the catalog and inventory.

"},{"location":"cli/overview/","title":"Overview","text":""},{"location":"cli/overview/#overview-of-antas-command-line-interface-cli","title":"Overview of ANTA\u2019s Command-Line Interface (CLI)","text":"

ANTA provides a powerful Command-Line Interface (CLI) to perform a wide range of operations. This document provides a comprehensive overview of ANTA CLI usage and its commands.

ANTA can also be used as a Python library, allowing you to build your own tools based on it. Visit this page for more details.

To start using the ANTA CLI, open your terminal and type anta.

"},{"location":"cli/overview/#invoking-anta-cli","title":"Invoking ANTA CLI","text":"
$ anta --help\nUsage: anta [OPTIONS] COMMAND [ARGS]...\n\n  Arista Network Test Automation (ANTA) CLI.\n\nOptions:\n  --version                       Show the version and exit.\n  --log-file FILE                 Send the logs to a file. If logging level is\n                                  DEBUG, only INFO or higher will be sent to\n                                  stdout.  [env var: ANTA_LOG_FILE]\n  -l, --log-level [CRITICAL|ERROR|WARNING|INFO|DEBUG]\n                                  ANTA logging level  [env var:\n                                  ANTA_LOG_LEVEL; default: INFO]\n  --help                          Show this message and exit.\n\nCommands:\n  check  Commands to validate configuration files.\n  debug  Commands to execute EOS commands on remote devices.\n  exec   Commands to execute various scripts on EOS devices.\n  get    Commands to get information from or generate inventories.\n  nrfu   Run ANTA tests on selected inventory devices.\n
"},{"location":"cli/overview/#anta-environment-variables","title":"ANTA environment variables","text":"

Certain parameters are required and can be either passed to the ANTA CLI or set as an environment variable (ENV VAR).

To pass the parameters via the CLI:

anta nrfu -u admin -p arista123 -i inventory.yaml -c tests.yaml\n

To set them as environment variables:

export ANTA_USERNAME=admin\nexport ANTA_PASSWORD=arista123\nexport ANTA_INVENTORY=inventory.yml\nexport ANTA_INVENTORY=tests.yml\n

Then, run the CLI without options:

anta nrfu\n

Note

All environment variables may not be needed for every commands. Refer to <command> --help for the comprehensive environment variables names.

Below are the environment variables usable with the anta nrfu command:

Variable Name Purpose Required ANTA_USERNAME The username to use in the inventory to connect to devices. Yes ANTA_PASSWORD The password to use in the inventory to connect to devices. Yes ANTA_INVENTORY The path to the inventory file. Yes ANTA_CATALOG The path to the catalog file. Yes ANTA_PROMPT The value to pass to the prompt for password is password is not provided No ANTA_INSECURE Whether or not using insecure mode when connecting to the EOS devices HTTP API. No ANTA_DISABLE_CACHE A variable to disable caching for all ANTA tests (enabled by default). No ANTA_ENABLE Whether it is necessary to go to enable mode on devices. No ANTA_ENABLE_PASSWORD The optional enable password, when this variable is set, ANTA_ENABLE or --enable is required. No

Info

Caching can be disabled with the global parameter --disable-cache. For more details about how caching is implemented in ANTA, please refer to Caching in ANTA.

"},{"location":"cli/overview/#anta-exit-codes","title":"ANTA Exit Codes","text":"

ANTA CLI utilizes the following exit codes:

  • Exit code 0 - All tests passed successfully.
  • Exit code 1 - An internal error occurred while executing ANTA.
  • Exit code 2 - A usage error was raised.
  • Exit code 3 - Tests were run, but at least one test returned an error.
  • Exit code 4 - Tests were run, but at least one test returned a failure.

To ignore the test status, use anta nrfu --ignore-status, and the exit code will always be 0.

To ignore errors, use anta nrfu --ignore-error, and the exit code will be 0 if all tests succeeded or 1 if any test failed.

"},{"location":"cli/overview/#shell-completion","title":"Shell Completion","text":"

You can enable shell completion for the ANTA CLI:

ZSHBASH

If you use ZSH shell, add the following line in your ~/.zshrc:

eval \"$(_ANTA_COMPLETE=zsh_source anta)\" > /dev/null\n

With bash, add the following line in your ~/.bashrc:

eval \"$(_ANTA_COMPLETE=bash_source anta)\" > /dev/null\n
"},{"location":"cli/tag-management/","title":"Tag Management","text":""},{"location":"cli/tag-management/#tag-management","title":"Tag management","text":""},{"location":"cli/tag-management/#overview","title":"Overview","text":"

Some of the ANTA commands like anta nrfu command come with a --tags option.

For nrfu, this allows users to specify a set of tests, marked with a given tag, to be run on devices marked with the same tag. For instance, you can run tests dedicated to leaf devices on your leaf devices only and not on other devices.

Tags are string defined by the user and can be anything considered as a string by Python. A default one is present for all tests and devices.

The next table provides a short summary of the scope of tags using CLI

Command Description none Run all tests on all devices according tag definition in your inventory and test catalog. And tests with no tag are executed on all devices --tags leaf Run all tests marked with leaf tag on all devices configured with leaf tag. All other tags are ignored --tags leaf,spine Run all tests marked with leaf tag on all devices configured with leaf tag.Run all tests marked with spine tag on all devices configured with spine tag. All other tags are ignored"},{"location":"cli/tag-management/#inventory-and-catalog-for-tests","title":"Inventory and Catalog for tests","text":"

All commands in this page are based on the following inventory and test catalog.

InventoryTest Catalog
---\nanta_inventory:\n  hosts:\n  - host: 192.168.0.10\n    name: spine01\n    tags: ['fabric', 'spine']\n  - host: 192.168.0.11\n    name: spine02\n    tags: ['fabric', 'spine']\n  - host: 192.168.0.12\n    name: leaf01\n    tags: ['fabric', 'leaf']\n  - host: 192.168.0.13\n    name: leaf02\n    tags: ['fabric', 'leaf']\n  - host: 192.168.0.14\n    name: leaf03\n    tags: ['fabric', 'leaf']\n  - host: 192.168.0.15\n    name: leaf04\n    tags: ['fabric', 'leaf'\n
anta.tests.system:\n  - VerifyUptime:\n      minimum: 10\n      filters:\n        tags: ['fabric']\n  - VerifyReloadCause:\n      tags: ['leaf', spine']\n  - VerifyCoredump:\n  - VerifyAgentLogs:\n  - VerifyCPUUtilization:\n      filters:\n        tags: ['spine', 'leaf']\n  - VerifyMemoryUtilization:\n  - VerifyFileSystemUtilization:\n  - VerifyNTP:\n\nanta.tests.mlag:\n  - VerifyMlagStatus:\n\n\nanta.tests.interfaces:\n  - VerifyL3MTU:\n      mtu: 1500\n      filters:\n        tags: ['demo']\n
"},{"location":"cli/tag-management/#default-tags","title":"Default tags","text":"

By default, ANTA uses a default tag for both devices and tests. This default tag is all and it can be explicit if you want to make it visible in your inventory and also implicit since the framework injects this tag if it is not defined.

So this command will run all tests from your catalog on all devices. With a mapping for tags defined in your inventory and catalog. If no tags configured, then tests are executed against all devices.

$ anta nrfu -c .personal/catalog-class.yml table --group-by device\n\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Settings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 Running ANTA tests:                                  \u2502\n\u2502 - ANTA Inventory contains 6 devices (AsyncEOSDevice) \u2502\n\u2502 - Tests catalog contains 10 tests                    \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n\n\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\n\u2503 Device  \u2503 # of success \u2503 # of skipped \u2503 # of failure \u2503 # of errors \u2503 List of failed or error test cases \u2503\n\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\n\u2502 spine01 \u2502 5            \u2502 1            \u2502 1            \u2502 0           \u2502 ['VerifyCPUUtilization']           \u2502\n\u2502 spine02 \u2502 5            \u2502 1            \u2502 1            \u2502 0           \u2502 ['VerifyCPUUtilization']           \u2502\n\u2502 leaf01  \u2502 6            \u2502 0            \u2502 1            \u2502 0           \u2502 ['VerifyCPUUtilization']           \u2502\n\u2502 leaf02  \u2502 6            \u2502 0            \u2502 1            \u2502 0           \u2502 ['VerifyCPUUtilization']           \u2502\n\u2502 leaf03  \u2502 6            \u2502 0            \u2502 1            \u2502 0           \u2502 ['VerifyCPUUtilization']           \u2502\n\u2502 leaf04  \u2502 6            \u2502 0            \u2502 1            \u2502 0           \u2502 ['VerifyCPUUtilization']           \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n
"},{"location":"cli/tag-management/#use-a-single-tag-in-cli","title":"Use a single tag in CLI","text":"

The most used approach is to use a single tag in your CLI to filter tests & devices configured with this one.

In such scenario, ANTA will run tests marked with $tag only on devices marked with $tag. All other tests and devices will be ignored

$ anta nrfu -c .personal/catalog-class.yml --tags leaf text\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Settings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 Running ANTA tests:                                  \u2502\n\u2502 - ANTA Inventory contains 6 devices (AsyncEOSDevice) \u2502\n\u2502 - Tests catalog contains 10 tests                    \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n\nleaf01 :: VerifyUptime :: SUCCESS\nleaf01 :: VerifyReloadCause :: SUCCESS\nleaf01 :: VerifyCPUUtilization :: SUCCESS\nleaf02 :: VerifyUptime :: SUCCESS\nleaf02 :: VerifyReloadCause :: SUCCESS\nleaf02 :: VerifyCPUUtilization :: SUCCESS\nleaf03 :: VerifyUptime :: SUCCESS\nleaf03 :: VerifyReloadCause :: SUCCESS\nleaf03 :: VerifyCPUUtilization :: SUCCESS\nleaf04 :: VerifyUptime :: SUCCESS\nleaf04 :: VerifyReloadCause :: SUCCESS\nleaf04 :: VerifyCPUUtilization :: SUCCESS\n

In this case, only leaf devices defined in your inventory are used to run tests marked with leaf in your test catalog

"},{"location":"cli/tag-management/#use-multiple-tags-in-cli","title":"Use multiple tags in CLI","text":"

A more advanced usage of the tag feature is to list multiple tags in your CLI using --tags $tag1,$tag2 syntax.

In such scenario, all devices marked with $tag1 will be selected and ANTA will run tests with $tag1, then devices with $tag2 will be selected and will be tested with tests marked with $tag2

anta nrfu -c .personal/catalog-class.yml --tags leaf,fabric text\n\nspine01 :: VerifyUptime :: SUCCESS\nspine02 :: VerifyUptime :: SUCCESS\nleaf01 :: VerifyUptime :: SUCCESS\nleaf01 :: VerifyReloadCause :: SUCCESS\nleaf01 :: VerifyCPUUtilization :: SUCCESS\nleaf02 :: VerifyUptime :: SUCCESS\nleaf02 :: VerifyReloadCause :: SUCCESS\nleaf02 :: VerifyCPUUtilization :: SUCCESS\nleaf03 :: VerifyUptime :: SUCCESS\nleaf03 :: VerifyReloadCause :: SUCCESS\nleaf03 :: VerifyCPUUtilization :: SUCCESS\nleaf04 :: VerifyUptime :: SUCCESS\nleaf04 :: VerifyReloadCause :: SUCCESS\nleaf04 :: VerifyCPUUtilization :: SUCCESS\n
"}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Home","text":""},{"location":"#arista-network-test-automation-anta-framework","title":"Arista Network Test Automation (ANTA) Framework","text":"Code License GitHub PyPi

ANTA is Python framework that automates tests for Arista devices.

  • ANTA provides a set of tests to validate the state of your network
  • ANTA can be used to:
  • Automate NRFU (Network Ready For Use) test on a preproduction network
  • Automate tests on a live network (periodically or on demand)
  • ANTA can be used with:
  • As a Python library in your own application
  • The ANTA CLI

"},{"location":"#install-anta-library","title":"Install ANTA library","text":"

The library will NOT install the necessary dependencies for the CLI.

# Install ANTA as a library\npip install anta\n
"},{"location":"#install-anta-cli","title":"Install ANTA CLI","text":"

If you plan to use ANTA only as a CLI tool you can use pipx to install it. pipx is a tool to install and run python applications in isolated environments. Refer to pipx instructions to install on your system. pipx installs ANTA in an isolated python environment and makes it available globally.

This is not recommended if you plan to contribute to ANTA

# Install ANTA CLI with pipx\n$ pipx install anta[cli]\n\n# Run ANTA CLI\n$ anta --help\nUsage: anta [OPTIONS] COMMAND [ARGS]...\n\n  Arista Network Test Automation (ANTA) CLI\n\nOptions:\n  --version                       Show the version and exit.\n  --log-file FILE                 Send the logs to a file. If logging level is\n                                  DEBUG, only INFO or higher will be sent to\n                                  stdout.  [env var: ANTA_LOG_FILE]\n  -l, --log-level [CRITICAL|ERROR|WARNING|INFO|DEBUG]\n                                  ANTA logging level  [env var:\n                                  ANTA_LOG_LEVEL; default: INFO]\n  --help                          Show this message and exit.\n\nCommands:\n  check  Commands to validate configuration files\n  debug  Commands to execute EOS commands on remote devices\n  exec   Commands to execute various scripts on EOS devices\n  get    Commands to get information from or generate inventories\n  nrfu   Run ANTA tests on devices\n

You can also still choose to install it with directly with pip:

pip install anta[cli]\n
"},{"location":"#documentation","title":"Documentation","text":"

The documentation is published on ANTA package website.

"},{"location":"#contribution-guide","title":"Contribution guide","text":"

Contributions are welcome. Please refer to the contribution guide

"},{"location":"#credits","title":"Credits","text":"

Thank you to Jeremy Schulman for aio-eapi.

Thank you to Ang\u00e9lique Phillipps, Colin MacGiollaE\u00e1in, Khelil Sator, Matthieu Tache, Onur Gashi, Paul Lavelle, Guillaume Mulocher and Thomas Grimonet for their contributions and guidances.

"},{"location":"contribution/","title":"Contributions","text":""},{"location":"contribution/#how-to-contribute-to-anta","title":"How to contribute to ANTA","text":"

Contribution model is based on a fork-model. Don\u2019t push to aristanetworks/anta directly. Always do a branch in your forked repository and create a PR.

To help development, open your PR as soon as possible even in draft mode. It helps other to know on what you are working on and avoid duplicate PRs.

"},{"location":"contribution/#create-a-development-environment","title":"Create a development environment","text":"

Run the following commands to create an ANTA development environment:

# Clone repository\n$ git clone https://github.com/aristanetworks/anta.git\n$ cd anta\n\n# Install ANTA in editable mode and its development tools\n$ pip install -e .[dev]\n# To also install the CLI\n$ pip install -e .[dev,cli]\n\n# Verify installation\n$ pip list -e\nPackage Version Editable project location\n------- ------- -------------------------\nanta    1.0.0   /mnt/lab/projects/anta\n

Then, tox is configured with few environments to run CI locally:

$ tox list -d\ndefault environments:\nclean  -> Erase previous coverage reports\nlint   -> Check the code style\ntype   -> Check typing\npy38   -> Run pytest with py38\npy39   -> Run pytest with py39\npy310  -> Run pytest with py310\npy311  -> Run pytest with py311\nreport -> Generate coverage report\n
"},{"location":"contribution/#code-linting","title":"Code linting","text":"
tox -e lint\n[...]\nlint: commands[0]> black --check --diff --color .\nAll done! \u2728 \ud83c\udf70 \u2728\n104 files would be left unchanged.\nlint: commands[1]> isort --check --diff --color .\nSkipped 7 files\nlint: commands[2]> flake8 --max-line-length=165 --config=/dev/null anta\nlint: commands[3]> flake8 --max-line-length=165 --config=/dev/null tests\nlint: commands[4]> pylint anta\n\n--------------------------------------------------------------------\nYour code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)\n\n.pkg: _exit> python /Users/guillaumemulocher/.pyenv/versions/3.8.13/envs/anta/lib/python3.8/site-packages/pyproject_api/_backend.py True setuptools.build_meta\n  lint: OK (19.26=setup[5.83]+cmd[1.50,0.76,1.19,1.20,8.77] seconds)\n  congratulations :) (19.56 seconds)\n
"},{"location":"contribution/#code-typing","title":"Code Typing","text":"
tox -e type\n\n[...]\ntype: commands[0]> mypy --config-file=pyproject.toml anta\nSuccess: no issues found in 52 source files\n.pkg: _exit> python /Users/guillaumemulocher/.pyenv/versions/3.8.13/envs/anta/lib/python3.8/site-packages/pyproject_api/_backend.py True setuptools.build_meta\n  type: OK (46.66=setup[24.20]+cmd[22.46] seconds)\n  congratulations :) (47.01 seconds)\n

NOTE: Typing is configured quite strictly, do not hesitate to reach out if you have any questions, struggles, nightmares.

"},{"location":"contribution/#unit-tests","title":"Unit tests","text":"

To keep high quality code, we require to provide a Pytest for every tests implemented in ANTA.

All submodule should have its own pytest section under tests/units/anta_tests/<submodule-name>.py.

"},{"location":"contribution/#how-to-write-a-unit-test-for-an-antatest-subclass","title":"How to write a unit test for an AntaTest subclass","text":"

The Python modules in the tests/units/anta_tests folder define test parameters for AntaTest subclasses unit tests. A generic test function is written for all unit tests in tests.lib.anta module.

The pytest_generate_tests function definition in conftest.py is called during test collection.

The pytest_generate_tests function will parametrize the generic test function based on the DATA data structure defined in tests.units.anta_tests modules.

See https://docs.pytest.org/en/7.3.x/how-to/parametrize.html#basic-pytest-generate-tests-example

The DATA structure is a list of dictionaries used to parametrize the test. The list elements have the following keys:

  • name (str): Test name as displayed by Pytest.
  • test (AntaTest): An AntaTest subclass imported in the test module - e.g. VerifyUptime.
  • eos_data (list[dict]): List of data mocking EOS returned data to be passed to the test.
  • inputs (dict): Dictionary to instantiate the test inputs as defined in the class from test.
  • expected (dict): Expected test result structure, a dictionary containing a key result containing one of the allowed status (Literal['success', 'failure', 'unset', 'skipped', 'error']) and optionally a key messages which is a list(str) and each message is expected to be a substring of one of the actual messages in the TestResult object.

In order for your unit tests to be correctly collected, you need to import the generic test function even if not used in the Python module.

Test example for anta.tests.system.VerifyUptime AntaTest.

# Import the generic test function\nfrom tests.lib.anta import test  # noqa: F401\n\n# Import your AntaTest\nfrom anta.tests.system import VerifyUptime\n\n# Define test parameters\nDATA: list[dict[str, Any]] = [\n   {\n        # Arbitrary test name\n        \"name\": \"success\",\n        # Must be an AntaTest definition\n        \"test\": VerifyUptime,\n        # Data returned by EOS on which the AntaTest is tested\n        \"eos_data\": [{\"upTime\": 1186689.15, \"loadAvg\": [0.13, 0.12, 0.09], \"users\": 1, \"currentTime\": 1683186659.139859}],\n        # Dictionary to instantiate VerifyUptime.Input\n        \"inputs\": {\"minimum\": 666},\n        # Expected test result\n        \"expected\": {\"result\": \"success\"},\n    },\n    {\n        \"name\": \"failure\",\n        \"test\": VerifyUptime,\n        \"eos_data\": [{\"upTime\": 665.15, \"loadAvg\": [0.13, 0.12, 0.09], \"users\": 1, \"currentTime\": 1683186659.139859}],\n        \"inputs\": {\"minimum\": 666},\n        # If the test returns messages, it needs to be expected otherwise test will fail.\n        # NB: expected messages only needs to be included in messages returned by the test. Exact match is not required.\n        \"expected\": {\"result\": \"failure\", \"messages\": [\"Device uptime is 665.15 seconds\"]},\n    },\n]\n
"},{"location":"contribution/#git-pre-commit-hook","title":"Git Pre-commit hook","text":"
pip install pre-commit\npre-commit install\n

When running a commit or a pre-commit check:

\u276f echo \"import foobaz\" > test.py && git add test.py\n\u276f pre-commit\npylint...................................................................Failed\n- hook id: pylint\n- exit code: 22\n\n************* Module test\ntest.py:1:0: C0114: Missing module docstring (missing-module-docstring)\ntest.py:1:0: E0401: Unable to import 'foobaz' (import-error)\ntest.py:1:0: W0611: Unused import foobaz (unused-import)\n

NOTE: It could happen that pre-commit and tox disagree on something, in that case please open an issue on Github so we can take a look.. It is most probably wrong configuration on our side.

"},{"location":"contribution/#configure-mypypath","title":"Configure MYPYPATH","text":"

In some cases, mypy can complain about not having MYPYPATH configured in your shell. It is especially the case when you update both an anta test and its unit test. So you can configure this environment variable with:

# Option 1: use local folder\nexport MYPYPATH=.\n\n# Option 2: use absolute path\nexport MYPYPATH=/path/to/your/local/anta/repository\n
"},{"location":"contribution/#documentation","title":"Documentation","text":"

mkdocs is used to generate the documentation. A PR should always update the documentation to avoid documentation debt.

"},{"location":"contribution/#install-documentation-requirements","title":"Install documentation requirements","text":"

Run pip to install the documentation requirements from the root of the repo:

pip install -e .[doc]\n
"},{"location":"contribution/#testing-documentation","title":"Testing documentation","text":"

You can then check locally the documentation using the following command from the root of the repo:

mkdocs serve\n

By default, mkdocs listens to http://127.0.0.1:8000/, if you need to expose the documentation to another IP or port (for instance all IPs on port 8080), use the following command:

mkdocs serve --dev-addr=0.0.0.0:8080\n
"},{"location":"contribution/#build-class-diagram","title":"Build class diagram","text":"

To build class diagram to use in API documentation, you can use pyreverse part of pylint with graphviz installed for jpeg generation.

pyreverse anta --colorized -a1 -s1 -o jpeg -m true -k --output-directory docs/imgs/uml/ -c <FQDN anta class>\n

Image will be generated under docs/imgs/uml/ and can be inserted in your documentation.

"},{"location":"contribution/#checking-links","title":"Checking links","text":"

Writing documentation is crucial but managing links can be cumbersome. To be sure there is no dead links, you can use muffet with the following command:

muffet -c 2 --color=always http://127.0.0.1:8000 -e fonts.gstatic.com -b 8192\n
"},{"location":"contribution/#continuous-integration","title":"Continuous Integration","text":"

GitHub actions is used to test git pushes and pull requests. The workflows are defined in this directory. We can view the results here.

"},{"location":"faq/","title":"FAQ","text":""},{"location":"faq/#frequently-asked-questions-faq","title":"Frequently Asked Questions (FAQ)","text":""},{"location":"faq/#a-local-os-error-occurred-while-connecting-to-a-device","title":"A local OS error occurred while connecting to a device","text":"A local OS error occurred while connecting to a device

When running ANTA, you can receive A local OS error occurred while connecting to <device> errors. The underlying OSError exception can have various reasons: [Errno 24] Too many open files or [Errno 16] Device or resource busy.

This usually means that the operating system refused to open a new file descriptor (or socket) for the ANTA process. This might be due to the hard limit for open file descriptors currently set for the ANTA process.

At startup, ANTA sets the soft limit of its process to the hard limit up to 16384. This is because the soft limit is usually 1024 and the hard limit is usually higher (depends on the system). If the hard limit of the ANTA process is still lower than the number of selected tests in ANTA, the ANTA process may request to the operating system too many file descriptors and get an error, a WARNING is displayed at startup if this is the case.

"},{"location":"faq/#solution","title":"Solution","text":"

One solution could be to raise the hard limit for the user starting the ANTA process. You can get the current hard limit for a user using the command ulimit -n -H while logged in. Create the file /etc/security/limits.d/10-anta.conf with the following content:

<user>  hard    nofile  <value>\n
The user is the one with which the ANTA process is started. The value is the new hard limit. The maximum value depends on the system. A hard limit of 16384 should be sufficient for ANTA to run in most high scale scenarios. After creating this file, log out the current session and log in again.

"},{"location":"faq/#timeout-error-in-the-logs","title":"Timeout error in the logs","text":"Timeout error in the logs

When running ANTA, you can receive <Foo>Timeout errors in the logs (could be ReadTimeout, WriteTimeout, ConnectTimeout or PoolTimeout). More details on the timeouts of the underlying library are available here: https://www.python-httpx.org/advanced/timeouts.

This might be due to the time the host on which ANTA is run takes to reach the target devices (for instance if going through firewalls, NATs, \u2026) or when a lot of tests are being run at the same time on a device (eAPI has a queue mechanism to avoid exhausting EOS resources because of a high number of simultaneous eAPI requests).

"},{"location":"faq/#solution_1","title":"Solution","text":"

Use the timeout option. As an example for the nrfu command:

anta nrfu --enable --username username --password arista --inventory inventory.yml -c nrfu.yml --timeout 50 text\n

The previous command set a couple of options for ANTA NRFU, one them being the timeout command, by default, when running ANTA from CLI, it is set to 30s. The timeout is increased to 50s to allow ANTA to wait for API calls a little longer.

"},{"location":"faq/#importerror-related-to-urllib3","title":"ImportError related to urllib3","text":"ImportError related to urllib3 when running ANTA

When running the anta --help command, some users might encounter the following error:

ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0.2k-fips  26 Jan 2017'. See: https://github.com/urllib3/urllib3/issues/2168\n

This error arises due to a compatibility issue between urllib3 v2.0 and older versions of OpenSSL.

"},{"location":"faq/#solution_2","title":"Solution","text":"
  1. Workaround: Downgrade urllib3

    If you need a quick fix, you can temporarily downgrade the urllib3 package:

    pip3 uninstall urllib3\n\npip3 install urllib3==1.26.15\n
  2. Recommended: Upgrade System or Libraries:

    As per the [urllib3 v2 migration guide](https://urllib3.readthedocs.io/en/latest/v2-migration-guide.html), the root cause of this error is an incompatibility with older OpenSSL versions. For example, users on RHEL7 might consider upgrading to RHEL8, which supports the required OpenSSL version.\n
"},{"location":"faq/#attributeerror-module-lib-has-no-attribute-openssl_add_all_algorithms","title":"AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'","text":"AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms' when running ANTA

When running the anta commands after installation, some users might encounter the following error:

AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'\n

The error is a result of incompatibility between cryptography and pyopenssl when installing asyncssh which is a requirement of ANTA.

"},{"location":"faq/#solution_3","title":"Solution","text":"
  1. Upgrade pyopenssl

    pip install -U pyopenssl>22.0\n
"},{"location":"faq/#__nscfconstantstring-initialize-error-on-osx","title":"__NSCFConstantString initialize error on OSX","text":"__NSCFConstantString initialize error on OSX

This error occurs because of added security to restrict multithreading in macOS High Sierra and later versions of macOS. https://www.wefearchange.org/2018/11/forkmacos.rst.html

"},{"location":"faq/#solution_4","title":"Solution","text":"
  1. Set the following environment variable

    export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES\n
"},{"location":"faq/#still-facing-issues","title":"Still facing issues?","text":"

If you\u2019ve tried the above solutions and continue to experience problems, please follow the troubleshooting instructions and report the issue in our GitHub repository.

"},{"location":"getting-started/","title":"Getting Started","text":""},{"location":"getting-started/#getting-started","title":"Getting Started","text":"

This section shows how to use ANTA with basic configuration. All examples are based on Arista Test Drive (ATD) topology you can access by reaching out to your preferred SE.

"},{"location":"getting-started/#installation","title":"Installation","text":"

The easiest way to install ANTA package is to run Python (>=3.9) and its pip package to install:

pip install anta[cli]\n

For more details about how to install package, please see the requirements and installation section.

"},{"location":"getting-started/#configure-arista-eos-devices","title":"Configure Arista EOS devices","text":"

For ANTA to be able to connect to your target devices, you need to configure your management interface

vrf instance MGMT\n!\ninterface Management0\n   description oob_management\n   vrf MGMT\n   ip address 192.168.0.10/24\n!\n

Then, configure access to eAPI:

!\nmanagement api http-commands\n   protocol https port 443\n   no shutdown\n   vrf MGMT\n      no shutdown\n   !\n!\n
"},{"location":"getting-started/#create-your-inventory","title":"Create your inventory","text":"

ANTA uses an inventory to list the target devices for the tests. You can create a file manually with this format:

anta_inventory:\n  hosts:\n  - host: 192.168.0.10\n    name: spine01\n    tags: ['fabric', 'spine']\n  - host: 192.168.0.11\n    name: spine02\n    tags: ['fabric', 'spine']\n  - host: 192.168.0.12\n    name: leaf01\n    tags: ['fabric', 'leaf']\n  - host: 192.168.0.13\n    name: leaf02\n    tags: ['fabric', 'leaf']\n  - host: 192.168.0.14\n    name: leaf03\n    tags: ['fabric', 'leaf']\n  - host: 192.168.0.15\n    name: leaf04\n    tags: ['fabric', 'leaf']\n

You can read more details about how to build your inventory here

"},{"location":"getting-started/#test-catalog","title":"Test Catalog","text":"

To test your network, ANTA relies on a test catalog to list all the tests to run against your inventory. A test catalog references python functions into a yaml file.

The structure to follow is like:

<anta_tests_submodule>:\n  - <anta_tests_submodule function name>:\n      <test function option>:\n        <test function option value>\n

You can read more details about how to build your catalog here

Here is an example for basic tests:

# Load anta.tests.software\nanta.tests.software:\n  - VerifyEOSVersion: # Verifies the device is running one of the allowed EOS version.\n      versions: # List of allowed EOS versions.\n        - 4.25.4M\n        - 4.26.1F\n        - '4.28.3M-28837868.4283M (engineering build)'\n  - VerifyTerminAttrVersion:\n      versions:\n        - v1.22.1\n\nanta.tests.system:\n  - VerifyUptime: # Verifies the device uptime is higher than a value.\n      minimum: 1\n  - VerifyNTP:\n  - VerifySyslog:\n\nanta.tests.mlag:\n  - VerifyMlagStatus:\n  - VerifyMlagInterfaces:\n  - VerifyMlagConfigSanity:\n\nanta.tests.configuration:\n  - VerifyZeroTouch: # Verifies ZeroTouch is disabled.\n  - VerifyRunningConfigDiffs:\n
"},{"location":"getting-started/#test-your-network","title":"Test your network","text":""},{"location":"getting-started/#cli","title":"CLI","text":"

ANTA comes with a generic CLI entrypoint to run tests in your network. It requires an inventory file as well as a test catalog.

This entrypoint has multiple options to manage test coverage and reporting.

Usage: anta [OPTIONS] COMMAND [ARGS]...\n\n  Arista Network Test Automation (ANTA) CLI.\n\nOptions:\n  --version                       Show the version and exit.\n  --log-file FILE                 Send the logs to a file. If logging level is\n                                  DEBUG, only INFO or higher will be sent to\n                                  stdout.  [env var: ANTA_LOG_FILE]\n  -l, --log-level [CRITICAL|ERROR|WARNING|INFO|DEBUG]\n                                  ANTA logging level  [env var:\n                                  ANTA_LOG_LEVEL; default: INFO]\n  --help                          Show this message and exit.\n\nCommands:\n  check  Commands to validate configuration files.\n  debug  Commands to execute EOS commands on remote devices.\n  exec   Commands to execute various scripts on EOS devices.\n  get    Commands to get information from or generate inventories.\n  nrfu   Run ANTA tests on selected inventory devices.\n
Usage: anta nrfu [OPTIONS] COMMAND [ARGS]...\n\n  Run ANTA tests on selected inventory devices.\n\nOptions:\n  -u, --username TEXT             Username to connect to EOS  [env var:\n                                  ANTA_USERNAME; required]\n  -p, --password TEXT             Password to connect to EOS that must be\n                                  provided. It can be prompted using '--\n                                  prompt' option.  [env var: ANTA_PASSWORD]\n  --enable-password TEXT          Password to access EOS Privileged EXEC mode.\n                                  It can be prompted using '--prompt' option.\n                                  Requires '--enable' option.  [env var:\n                                  ANTA_ENABLE_PASSWORD]\n  --enable                        Some commands may require EOS Privileged\n                                  EXEC mode. This option tries to access this\n                                  mode before sending a command to the device.\n                                  [env var: ANTA_ENABLE]\n  -P, --prompt                    Prompt for passwords if they are not\n                                  provided.  [env var: ANTA_PROMPT]\n  --timeout FLOAT                 Global API timeout. This value will be used\n                                  for all devices.  [env var: ANTA_TIMEOUT;\n                                  default: 30.0]\n  --insecure                      Disable SSH Host Key validation.  [env var:\n                                  ANTA_INSECURE]\n  --disable-cache                 Disable cache globally.  [env var:\n                                  ANTA_DISABLE_CACHE]\n  -i, --inventory FILE            Path to the inventory YAML file.  [env var:\n                                  ANTA_INVENTORY; required]\n  --tags TEXT                     List of tags using comma as separator:\n                                  tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  -c, --catalog FILE              Path to the test catalog file  [env var:\n                                  ANTA_CATALOG; required]\n  --catalog-format [yaml|json]    Format of the catalog file, either 'yaml' or\n                                  'json'  [env var: ANTA_CATALOG_FORMAT]\n  -d, --device TEXT               Run tests on a specific device. Can be\n                                  provided multiple times.\n  -t, --test TEXT                 Run a specific test. Can be provided\n                                  multiple times.\n  --ignore-status                 Exit code will always be 0.  [env var:\n                                  ANTA_NRFU_IGNORE_STATUS]\n  --ignore-error                  Exit code will be 0 if all tests succeeded\n                                  or 1 if any test failed.  [env var:\n                                  ANTA_NRFU_IGNORE_ERROR]\n  --hide [success|failure|error|skipped]\n                                  Hide result by type: success / failure /\n                                  error / skipped'.\n  --dry-run                       Run anta nrfu command but stop before\n                                  starting to execute the tests. Considers all\n                                  devices as connected.  [env var:\n                                  ANTA_NRFU_DRY_RUN]\n  --help                          Show this message and exit.\n\nCommands:\n  json        ANTA command to check network state with JSON result.\n  table       ANTA command to check network states with table result.\n  text        ANTA command to check network states with text result.\n  tpl-report  ANTA command to check network state with templated report.\n

To run the NRFU, you need to select an output format amongst [\u201cjson\u201d, \u201ctable\u201d, \u201ctext\u201d, \u201ctpl-report\u201d]. For a first usage, table is recommended. By default all test results for all devices are rendered but it can be changed to a report per test case or per host

"},{"location":"getting-started/#default-report-using-table","title":"Default report using table","text":"
anta nrfu \\\n    --username tom \\\n    --password arista123 \\\n    --enable \\\n    --enable-password t \\\n    --inventory .personal/inventory_atd.yml \\\n    --catalog .personal/tests-bases.yml \\\n    table --tags leaf\n\n\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Settings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 Running ANTA tests:                                  \u2502\n\u2502 - ANTA Inventory contains 6 devices (AsyncEOSDevice) \u2502\n\u2502 - Tests catalog contains 10 tests                    \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n[10:17:24] INFO     Running ANTA tests...                                                                                                           runner.py:75\n  \u2022 Running NRFU Tests...100% \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501 40/40 \u2022 0:00:02 \u2022 0:00:00\n\n                                                                       All tests results\n\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\n\u2503 Device IP \u2503 Test Name                \u2503 Test Status \u2503 Message(s)       \u2503 Test description                                                     \u2503 Test category \u2503\n\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\n\u2502 leaf01    \u2502 VerifyEOSVersion         \u2502 success     \u2502                  \u2502 Verifies the device is running one of the allowed EOS version.       \u2502 software      \u2502\n\u2502 leaf01    \u2502 VerifyTerminAttrVersion  \u2502 success     \u2502                  \u2502 Verifies the device is running one of the allowed TerminAttr         \u2502 software      \u2502\n\u2502           \u2502                          \u2502             \u2502                  \u2502 version.                                                             \u2502               \u2502\n\u2502 leaf01    \u2502 VerifyUptime             \u2502 success     \u2502                  \u2502 Verifies the device uptime is higher than a value.                   \u2502 system        \u2502\n\u2502 leaf01    \u2502 VerifyNTP                \u2502 success     \u2502                  \u2502 Verifies NTP is synchronised.                                        \u2502 system        \u2502\n\u2502 leaf01    \u2502 VerifySyslog             \u2502 success     \u2502                  \u2502 Verifies the device had no syslog message with a severity of warning \u2502 system        \u2502\n\u2502           \u2502                          \u2502             \u2502                  \u2502 (or a more severe message) during the last 7 days.                   \u2502               \u2502\n\u2502 leaf01    \u2502 VerifyMlagStatus         \u2502 skipped     \u2502 MLAG is disabled \u2502 This test verifies the health status of the MLAG configuration.      \u2502 mlag          \u2502\n\u2502 leaf01    \u2502 VerifyMlagInterfaces     \u2502 skipped     \u2502 MLAG is disabled \u2502 This test verifies there are no inactive or active-partial MLAG      \u2502 mlag          \u2502\n[...]\n\u2502 leaf04    \u2502 VerifyMlagConfigSanity   \u2502 skipped     \u2502 MLAG is disabled \u2502 This test verifies there are no MLAG config-sanity inconsistencies.  \u2502 mlag          \u2502\n\u2502 leaf04    \u2502 VerifyZeroTouch          \u2502 success     \u2502                  \u2502 Verifies ZeroTouch is disabled.                                      \u2502 configuration \u2502\n\u2502 leaf04    \u2502 VerifyRunningConfigDiffs \u2502 success     \u2502                  \u2502                                                                      \u2502 configuration \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n
"},{"location":"getting-started/#report-in-text-mode","title":"Report in text mode","text":"
$ anta nrfu \\\n    --username tom \\\n    --password arista123 \\\n    --enable \\\n    --enable-password t \\\n    --inventory .personal/inventory_atd.yml \\\n    --catalog .personal/tests-bases.yml \\\n    text --tags leaf\n\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Settings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 Running ANTA tests:                                  \u2502\n\u2502 - ANTA Inventory contains 6 devices (AsyncEOSDevice) \u2502\n\u2502 - Tests catalog contains 10 tests                    \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n[10:20:47] INFO     Running ANTA tests...                                                                                                           runner.py:75\n  \u2022 Running NRFU Tests...100% \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501 40/40 \u2022 0:00:01 \u2022 0:00:00\nleaf01 :: VerifyEOSVersion :: SUCCESS\nleaf01 :: VerifyTerminAttrVersion :: SUCCESS\nleaf01 :: VerifyUptime :: SUCCESS\nleaf01 :: VerifyNTP :: SUCCESS\nleaf01 :: VerifySyslog :: SUCCESS\nleaf01 :: VerifyMlagStatus :: SKIPPED (MLAG is disabled)\nleaf01 :: VerifyMlagInterfaces :: SKIPPED (MLAG is disabled)\nleaf01 :: VerifyMlagConfigSanity :: SKIPPED (MLAG is disabled)\n[...]\n
"},{"location":"getting-started/#report-in-json-format","title":"Report in JSON format","text":"
$ anta nrfu \\\n    --username tom \\\n    --password arista123 \\\n    --enable \\\n    --enable-password t \\\n    --inventory .personal/inventory_atd.yml \\\n    --catalog .personal/tests-bases.yml \\\n    json --tags leaf\n\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Settings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 Running ANTA tests:                                  \u2502\n\u2502 - ANTA Inventory contains 6 devices (AsyncEOSDevice) \u2502\n\u2502 - Tests catalog contains 10 tests                    \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n[10:21:51] INFO     Running ANTA tests...                                                                                                           runner.py:75\n  \u2022 Running NRFU Tests...100% \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501 40/40 \u2022 0:00:02 \u2022 0:00:00\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 JSON results of all tests                                                                                                                                    \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n[\n  {\n    \"name\": \"leaf01\",\n    \"test\": \"VerifyEOSVersion\",\n    \"categories\": [\n      \"software\"\n    ],\n    \"description\": \"Verifies the device is running one of the allowed EOS version.\",\n    \"result\": \"success\",\n    \"messages\": [],\n    \"custom_field\": \"None\",\n  },\n  {\n    \"name\": \"leaf01\",\n    \"test\": \"VerifyTerminAttrVersion\",\n    \"categories\": [\n      \"software\"\n    ],\n    \"description\": \"Verifies the device is running one of the allowed TerminAttr version.\",\n    \"result\": \"success\",\n    \"messages\": [],\n    \"custom_field\": \"None\",\n  },\n[...]\n]\n

You can find more information under the usage section of the website

"},{"location":"getting-started/#basic-usage-in-a-python-script","title":"Basic usage in a Python script","text":"
# Copyright (c) 2023-2024 Arista Networks, Inc.\n# Use of this source code is governed by the Apache License 2.0\n# that can be found in the LICENSE file.\n\"\"\"Example script for ANTA.\n\nusage:\n\npython anta_runner.py\n\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nimport logging\nimport sys\nfrom pathlib import Path\n\nfrom anta.catalog import AntaCatalog\nfrom anta.cli.nrfu.utils import anta_progress_bar\nfrom anta.inventory import AntaInventory\nfrom anta.logger import Log, setup_logging\nfrom anta.models import AntaTest\nfrom anta.result_manager import ResultManager\nfrom anta.runner import main as anta_runner\n\n# setup logging\nsetup_logging(Log.INFO, Path(\"/tmp/anta.log\"))\nLOGGER = logging.getLogger()\nSCRIPT_LOG_PREFIX = \"[bold magenta][ANTA RUNNER SCRIPT][/] \"  # For convenience purpose - there are nicer way to do this.\n\n\n# NOTE: The inventory and catalog files are not delivered with this script\nUSERNAME = \"admin\"\nPASSWORD = \"admin\"\nCATALOG_PATH = Path(\"/tmp/anta_catalog.yml\")\nINVENTORY_PATH = Path(\"/tmp/anta_inventory.yml\")\n\n# Load catalog file\ntry:\n    catalog = AntaCatalog.parse(CATALOG_PATH)\nexcept Exception:\n    LOGGER.exception(\"%s Catalog failed to load!\", SCRIPT_LOG_PREFIX)\n    sys.exit(1)\nLOGGER.info(\"%s Catalog loaded!\", SCRIPT_LOG_PREFIX)\n\n# Load inventory\ntry:\n    inventory = AntaInventory.parse(INVENTORY_PATH, username=USERNAME, password=PASSWORD)\nexcept Exception:\n    LOGGER.exception(\"%s Inventory failed to load!\", SCRIPT_LOG_PREFIX)\n    sys.exit(1)\nLOGGER.info(\"%s Inventory loaded!\", SCRIPT_LOG_PREFIX)\n\n# Create result manager object\nmanager = ResultManager()\n\n# Launch ANTA\nLOGGER.info(\"%s  Starting ANTA runner...\", SCRIPT_LOG_PREFIX)\nwith anta_progress_bar() as AntaTest.progress:\n    # Set dry_run to True to avoid connecting to the devices\n    asyncio.run(anta_runner(manager, inventory, catalog, dry_run=False))\n\nLOGGER.info(\"%s ANTA run completed!\", SCRIPT_LOG_PREFIX)\n\n# Manipulate the test result object\nfor test_result in manager.results:\n    LOGGER.info(\"%s %s:%s:%s\", SCRIPT_LOG_PREFIX, test_result.name, test_result.test, test_result.result)\n
"},{"location":"requirements-and-installation/","title":"Installation","text":""},{"location":"requirements-and-installation/#anta-requirements","title":"ANTA Requirements","text":""},{"location":"requirements-and-installation/#python-version","title":"Python version","text":"

Python 3 (>=3.9) is required:

python --version\nPython 3.11.8\n
"},{"location":"requirements-and-installation/#install-anta-package","title":"Install ANTA package","text":"

This installation will deploy tests collection, scripts and all their Python requirements.

The ANTA package and the cli require some packages that are not part of the Python standard library. They are indicated in the pyproject.toml file, under dependencies.

"},{"location":"requirements-and-installation/#install-library-from-pypi-server","title":"Install library from Pypi server","text":"
pip install anta\n

Warning

  • This command alone will not install the ANTA CLI requirements.
"},{"location":"requirements-and-installation/#install-anta-cli-as-an-application-with-pipx","title":"Install ANTA CLI as an application with pipx","text":"

pipx is a tool to install and run python applications in isolated environments. If you plan to use ANTA only as a CLI tool you can use pipx to install it. pipx installs ANTA in an isolated python environment and makes it available globally.

pipx install anta[cli]\n

Info

Please take the time to read through the installation instructions of pipx before getting started.

"},{"location":"requirements-and-installation/#install-cli-from-pypi-server","title":"Install CLI from Pypi server","text":"

Alternatively, pip install with cli extra is enough to install the ANTA CLI.

pip install anta[cli]\n
"},{"location":"requirements-and-installation/#install-anta-from-github","title":"Install ANTA from github","text":"
pip install git+https://github.com/aristanetworks/anta.git\npip install git+https://github.com/aristanetworks/anta.git#egg=anta[cli]\n\n# You can even specify the branch, tag or commit:\npip install git+https://github.com/aristanetworks/anta.git@<cool-feature-branch>\npip install git+https://github.com/aristanetworks/anta.git@<cool-feature-branch>#egg=anta[cli]\n\npip install git+https://github.com/aristanetworks/anta.git@<cool-tag>\npip install git+https://github.com/aristanetworks/anta.git@<cool-tag>#egg=anta[cli]\n\npip install git+https://github.com/aristanetworks/anta.git@<more-or-less-cool-hash>\npip install git+https://github.com/aristanetworks/anta.git@<more-or-less-cool-hash>#egg=anta[cli]\n
"},{"location":"requirements-and-installation/#check-installation","title":"Check installation","text":"

After installing ANTA, verify the installation with the following commands:

# Check ANTA has been installed in your python path\npip list | grep anta\n\n# Check scripts are in your $PATH\n# Path may differ but it means CLI is in your path\nwhich anta\n/home/tom/.pyenv/shims/anta\n

Warning

Before running the anta --version command, please be aware that some users have reported issues related to the urllib3 package. If you encounter an error at this step, please refer to our FAQ page for guidance on resolving it.

# Check ANTA version\nanta --version\nanta, version v1.0.0\n
"},{"location":"requirements-and-installation/#eos-requirements","title":"EOS Requirements","text":"

To get ANTA working, the targeted Arista EOS devices must have eAPI enabled. They need to use the following configuration (assuming you connect to the device using Management interface in MGMT VRF):

configure\n!\nvrf instance MGMT\n!\ninterface Management1\n   description oob_management\n   vrf MGMT\n   ip address 10.73.1.105/24\n!\nend\n

Enable eAPI on the MGMT vrf:

configure\n!\nmanagement api http-commands\n   protocol https port 443\n   no shutdown\n   vrf MGMT\n      no shutdown\n!\nend\n

Now the switch accepts on port 443 in the MGMT VRF HTTPS requests containing a list of CLI commands.

Run these EOS commands to verify:

show management http-server\nshow management api http-commands\n
"},{"location":"troubleshooting/","title":"Troubleshooting","text":""},{"location":"troubleshooting/#troubleshooting-anta","title":"Troubleshooting ANTA","text":"

A couple of things to check when hitting an issue with ANTA:

flowchart LR\n    A>Hitting an issue with ANTA] --> B{Is my issue <br >listed in the FAQ?}\n    B -- Yes --> C{Does the FAQ solution<br />works for me?}\n    C -- Yes --> V(((Victory)))\n    B -->|No| E{Is my problem<br />mentioned in one<br />of the open issues?}\n    C -->|No| E\n    E -- Yes --> F{Has the issue been<br />fixed in a newer<br />release or in main?}\n    F -- Yes --> U[Upgrade]\n    E -- No ---> H((Follow the steps below<br />and open a Github issue))\n    U --> I{Did it fix<br /> your problem}\n    I -- Yes --> V\n    I -- No --> H\n    F -- No ----> G((Add a comment on the <br />issue indicating you<br >are hitting this and<br />describing your setup<br /> and adding your logs.))\n\n    click B \"../faq\" \"FAQ\"\n    click E \"https://github.com/aristanetworks/anta/issues\"\n    click H \"https://github.com/aristanetworks/anta/issues\"\n    style A stroke:#f00,stroke-width:2px
"},{"location":"troubleshooting/#capturing-logs","title":"Capturing logs","text":"

To help document the issue in Github, it is important to capture some logs so the developers can understand what is affecting your system. No logs mean that the first question asked on the issue will probably be \u201cCan you share some logs please?\u201d.

ANTA provides very verbose logs when using the DEBUG level. When using DEBUG log level with a log file, the DEBUG logging level is not sent to stdout, but only to the file.

Danger

On real deployments, do not use DEBUG logging level without setting a log file at the same time.

To save the logs to a file called anta.log, use the following flags:

# Where ANTA_COMMAND is one of nrfu, debug, get, exec, check\nanta -l DEBUG \u2013log-file anta.log <ANTA_COMMAND>\n

See anta --help for more information. These have to precede the nrfu cmd.

Tip

Remember that in ANTA, each level of command has its own options and they can only be set at this level. so the -l and --log-file MUST be between anta and the ANTA_COMMAND. similarly, all the nrfu options MUST be set between the nrfu and the ANTA_NRFU_SUBCOMMAND (json, text, table or tpl-report).

As an example, for the nrfu command, it would look like:

anta -l DEBUG --log-file anta.log nrfu --enable --username username --password arista --inventory inventory.yml -c nrfu.yml text\n
"},{"location":"troubleshooting/#anta_debug-environment-variable","title":"ANTA_DEBUG environment variable","text":"Warning

Do not use this if you do not know why. This produces a lot of logs and can create confusion if you do not know what to look for.

The environment variable ANTA_DEBUG=true enable ANTA Debug Mode.

This flag is used by various functions in ANTA: when set to true, the function will display or log more information. In particular, when an Exception occurs in the code and this variable is set, the logging function used by ANTA is different to also produce the Python traceback for debugging. This typically needs to be done when opening a GitHub issue and an Exception is seen at runtime.

Example:

ANTA_DEBUG=true anta -l DEBUG --log-file anta.log nrfu --enable --username username --password arista --inventory inventory.yml -c nrfu.yml text\n
"},{"location":"troubleshooting/#troubleshooting-on-eos","title":"Troubleshooting on EOS","text":"

ANTA is using a specific ID in eAPI requests towards EOS. This allows for easier eAPI requests debugging on the device using EOS configuration trace CapiApp setting UwsgiRequestContext/4,CapiUwsgiServer/4 to set up CapiApp agent logs.

Then, you can view agent logs using:

bash tail -f /var/log/agents/CapiApp-*\n\n2024-05-15 15:32:54.056166  1429 UwsgiRequestContext  4 request content b'{\"jsonrpc\": \"2.0\", \"method\": \"runCmds\", \"params\": {\"version\": \"latest\", \"cmds\": [{\"cmd\": \"show ip route vrf default 10.255.0.3\", \"revision\": 4}], \"format\": \"json\", \"autoComplete\": false, \"expandAliases\": false}, \"id\": \"ANTA-VerifyRoutingTableEntry-132366530677328\"}'\n

"},{"location":"usage-inventory-catalog/","title":"Inventory & Tests catalog","text":""},{"location":"usage-inventory-catalog/#inventory-and-catalog","title":"Inventory and Catalog","text":"

The ANTA framework needs 2 important inputs from the user to run: a device inventory and a test catalog.

Both inputs can be defined in a file or programmatically.

"},{"location":"usage-inventory-catalog/#device-inventory","title":"Device Inventory","text":"

A device inventory is an instance of the AntaInventory class.

"},{"location":"usage-inventory-catalog/#device-inventory-file","title":"Device Inventory File","text":"

The ANTA device inventory can easily be defined as a YAML file. The file must comply with the following structure:

anta_inventory:\n  hosts:\n    - host: < ip address value >\n      port: < TCP port for eAPI. Default is 443 (Optional)>\n      name: < name to display in report. Default is host:port (Optional) >\n      tags: < list of tags to use to filter inventory during tests >\n      disable_cache: < Disable cache per hosts. Default is False. >\n  networks:\n    - network: < network using CIDR notation >\n      tags: < list of tags to use to filter inventory during tests >\n      disable_cache: < Disable cache per network. Default is False. >\n  ranges:\n    - start: < first ip address value of the range >\n      end: < last ip address value of the range >\n      tags: < list of tags to use to filter inventory during tests >\n      disable_cache: < Disable cache per range. Default is False. >\n

The inventory file must start with the anta_inventory key then define one or multiple methods:

  • hosts: define each device individually
  • networks: scan a network for devices accessible via eAPI
  • ranges: scan a range for devices accessible via eAPI

A full description of the inventory model is available in API documentation

Info

Caching can be disabled per device, network or range by setting the disable_cache key to True in the inventory file. For more details about how caching is implemented in ANTA, please refer to Caching in ANTA.

"},{"location":"usage-inventory-catalog/#example","title":"Example","text":"
---\nanta_inventory:\n  hosts:\n  - host: 192.168.0.10\n    name: spine01\n    tags: ['fabric', 'spine']\n  - host: 192.168.0.11\n    name: spine02\n    tags: ['fabric', 'spine']\n  networks:\n  - network: '192.168.110.0/24'\n    tags: ['fabric', 'leaf']\n  ranges:\n  - start: 10.0.0.9\n    end: 10.0.0.11\n    tags: ['fabric', 'l2leaf']\n
"},{"location":"usage-inventory-catalog/#test-catalog","title":"Test Catalog","text":"

A test catalog is an instance of the AntaCatalog class.

"},{"location":"usage-inventory-catalog/#test-catalog-file","title":"Test Catalog File","text":"

In addition to the inventory file, you also have to define a catalog of tests to execute against your devices. This catalog list all your tests, their inputs and their tags.

A valid test catalog file must have the following structure in either YAML or JSON:

---\n<Python module>:\n    - <AntaTest subclass>:\n        <AntaTest.Input compliant dictionary>\n

{\n  \"<Python module>\": [\n    {\n      \"<AntaTest subclass>\": <AntaTest.Input compliant dictionary>\n    }\n  ]\n}\n
"},{"location":"usage-inventory-catalog/#example_1","title":"Example","text":"
---\nanta.tests.connectivity:\n  - VerifyReachability:\n      hosts:\n        - source: Management0\n          destination: 1.1.1.1\n          vrf: MGMT\n        - source: Management0\n          destination: 8.8.8.8\n          vrf: MGMT\n      filters:\n        tags: ['leaf']\n      result_overwrite:\n        categories:\n          - \"Overwritten category 1\"\n        description: \"Test with overwritten description\"\n        custom_field: \"Test run by John Doe\"\n

or equivalent in JSON:

{\n  \"anta.tests.connectivity\": [\n    {\n      \"VerifyReachability\": {\n        \"result_overwrite\": {\n          \"description\": \"Test with overwritten description\",\n          \"categories\": [\n            \"Overwritten category 1\"\n          ],\n          \"custom_field\": \"Test run by John Doe\"\n        },\n        \"filters\": {\n          \"tags\": [\n            \"leaf\"\n          ]\n        },\n        \"hosts\": [\n          {\n            \"destination\": \"1.1.1.1\",\n            \"source\": \"Management0\",\n            \"vrf\": \"MGMT\"\n          },\n          {\n            \"destination\": \"8.8.8.8\",\n            \"source\": \"Management0\",\n            \"vrf\": \"MGMT\"\n          }\n        ]\n      }\n    }\n  ]\n}\n

It is also possible to nest Python module definition:

anta.tests:\n  connectivity:\n    - VerifyReachability:\n        hosts:\n          - source: Management0\n            destination: 1.1.1.1\n            vrf: MGMT\n          - source: Management0\n            destination: 8.8.8.8\n            vrf: MGMT\n        filters:\n          tags: ['leaf']\n        result_overwrite:\n          categories:\n            - \"Overwritten category 1\"\n          description: \"Test with overwritten description\"\n          custom_field: \"Test run by John Doe\"\n

This test catalog example is maintained with all the tests defined in the anta.tests Python module.

"},{"location":"usage-inventory-catalog/#test-tags","title":"Test tags","text":"

All tests can be defined with a list of user defined tags. These tags will be mapped with device tags: when at least one tag is defined for a test, this test will only be executed on devices with the same tag. If a test is defined in the catalog without any tags, the test will be executed on all devices.

anta.tests.system:\n  - VerifyUptime:\n      minimum: 10\n      filters:\n        tags: ['demo', 'leaf']\n  - VerifyReloadCause:\n  - VerifyCoredump:\n  - VerifyAgentLogs:\n  - VerifyCPUUtilization:\n      filters:\n        tags: ['leaf']\n

Info

When using the CLI, you can filter the NRFU execution using tags. Refer to this section of the CLI documentation.

"},{"location":"usage-inventory-catalog/#tests-available-in-anta","title":"Tests available in ANTA","text":"

All tests available as part of the ANTA framework are defined under the anta.tests Python module and are categorised per family (Python submodule). The complete list of the tests and their respective inputs is available at the tests section of this website.

To run test to verify the EOS software version, you can do:

anta.tests.software:\n  - VerifyEOSVersion:\n

It will load the test VerifyEOSVersion located in anta.tests.software. But since this test has mandatory inputs, we need to provide them as a dictionary in the YAML or JSON file:

anta.tests.software:\n  - VerifyEOSVersion:\n      # List of allowed EOS versions.\n      versions:\n        - 4.25.4M\n        - 4.26.1F\n
{\n  \"anta.tests.software\": [\n    {\n      \"VerifyEOSVersion\": {\n        \"versions\": [\n          \"4.25.4M\",\n          \"4.31.1F\"\n        ]\n      }\n    }\n  ]\n}\n

The following example is a very minimal test catalog:

---\n# Load anta.tests.software\nanta.tests.software:\n  # Verifies the device is running one of the allowed EOS version.\n  - VerifyEOSVersion:\n      # List of allowed EOS versions.\n      versions:\n        - 4.25.4M\n        - 4.26.1F\n\n# Load anta.tests.system\nanta.tests.system:\n  # Verifies the device uptime is higher than a value.\n  - VerifyUptime:\n      minimum: 1\n\n# Load anta.tests.configuration\nanta.tests.configuration:\n  # Verifies ZeroTouch is disabled.\n  - VerifyZeroTouch:\n  - VerifyRunningConfigDiffs:\n
"},{"location":"usage-inventory-catalog/#catalog-with-custom-tests","title":"Catalog with custom tests","text":"

In case you want to leverage your own tests collection, use your own Python package in the test catalog. So for instance, if my custom tests are defined in the custom.tests.system Python module, the test catalog will be:

custom.tests.system:\n  - VerifyPlatform:\n    type: ['cEOS-LAB']\n

How to create custom tests

To create your custom tests, you should refer to this documentation

"},{"location":"usage-inventory-catalog/#customize-test-description-and-categories","title":"Customize test description and categories","text":"

It might be interesting to use your own categories and customized test description to build a better report for your environment. ANTA comes with a handy feature to define your own categories and description in the report.

In your test catalog, use result_overwrite dictionary with categories and description to just overwrite this values in your report:

anta.tests.configuration:\n  - VerifyZeroTouch: # Verifies ZeroTouch is disabled.\n      result_overwrite:\n        categories: ['demo', 'pr296']\n        description: A custom test\n  - VerifyRunningConfigDiffs:\nanta.tests.interfaces:\n  - VerifyInterfaceUtilization:\n

Once you run anta nrfu table, you will see following output:

\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\n\u2503 Device IP \u2503 Test Name                  \u2503 Test Status \u2503 Message(s) \u2503 Test description                              \u2503 Test category \u2503\n\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\n\u2502 spine01   \u2502 VerifyZeroTouch            \u2502 success     \u2502            \u2502 A custom test                                 \u2502 demo, pr296   \u2502\n\u2502 spine01   \u2502 VerifyRunningConfigDiffs   \u2502 success     \u2502            \u2502                                               \u2502 configuration \u2502\n\u2502 spine01   \u2502 VerifyInterfaceUtilization \u2502 success     \u2502            \u2502 Verifies interfaces utilization is below 75%. \u2502 interfaces    \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n
"},{"location":"usage-inventory-catalog/#example-script-to-merge-catalogs","title":"Example script to merge catalogs","text":"

The following script reads all the files in intended/test_catalogs/ with names <device_name>-catalog.yml and merge them together inside one big catalog anta-catalog.yml.

#!/usr/bin/env python\nfrom anta.catalog import AntaCatalog\n\nfrom pathlib import Path\nfrom anta.models import AntaTest\n\n\nCATALOG_SUFFIX = '-catalog.yml'\nCATALOG_DIR = 'intended/test_catalogs/'\n\nif __name__ == \"__main__\":\n    catalog = AntaCatalog()\n    for file in Path(CATALOG_DIR).glob('*'+CATALOG_SUFFIX):\n        c = AntaCatalog.parse(file)\n        device = str(file).removesuffix(CATALOG_SUFFIX).removeprefix(CATALOG_DIR)\n        print(f\"Merging test catalog for device {device}\")\n        # Apply filters to all tests for this device\n        for test in c.tests:\n            test.inputs.filters = AntaTest.Input.Filters(tags=[device])\n        catalog = catalog.merge(c)\n    with open(Path('anta-catalog.yml'), \"w\") as f:\n        f.write(catalog.dump().yaml())\n
"},{"location":"advanced_usages/as-python-lib/","title":"ANTA as a Python Library","text":"

ANTA is a Python library that can be used in user applications. This section describes how you can leverage ANTA Python modules to help you create your own NRFU solution.

Tip

If you are unfamiliar with asyncio, refer to the Python documentation relevant to your Python version - https://docs.python.org/3/library/asyncio.html

"},{"location":"advanced_usages/as-python-lib/#antadevice-abstract-class","title":"AntaDevice Abstract Class","text":"

A device is represented in ANTA as a instance of a subclass of the AntaDevice abstract class. There are few abstract methods that needs to be implemented by child classes:

  • The collect() coroutine is in charge of collecting outputs of AntaCommand instances.
  • The refresh() coroutine is in charge of updating attributes of the AntaDevice instance. These attributes are used by AntaInventory to filter out unreachable devices or by AntaTest to skip devices based on their hardware models.

The copy() coroutine is used to copy files to and from the device. It does not need to be implemented if tests are not using it.

"},{"location":"advanced_usages/as-python-lib/#asynceosdevice-class","title":"AsyncEOSDevice Class","text":"

The AsyncEOSDevice class is an implementation of AntaDevice for Arista EOS. It uses the aio-eapi eAPI client and the AsyncSSH library.

  • The collect() coroutine collects AntaCommand outputs using eAPI.
  • The refresh() coroutine tries to open a TCP connection on the eAPI port and update the is_online attribute accordingly. If the TCP connection succeeds, it sends a show version command to gather the hardware model of the device and updates the established and hw_model attributes.
  • The copy() coroutine copies files to and from the device using the SCP protocol.
"},{"location":"advanced_usages/as-python-lib/#antainventory-class","title":"AntaInventory Class","text":"

The AntaInventory class is a subclass of the standard Python type dict. The keys of this dictionary are the device names, the values are AntaDevice instances.

AntaInventory provides methods to interact with the ANTA inventory:

  • The add_device() method adds an AntaDevice instance to the inventory. Adding an entry to AntaInventory with a key different from the device name is not allowed.
  • The get_inventory() returns a new AntaInventory instance with filtered out devices based on the method inputs.
  • The connect_inventory() coroutine will execute the refresh() coroutines of all the devices in the inventory.
  • The parse() static method creates an AntaInventory instance from a YAML file and returns it. The devices are AsyncEOSDevice instances.

To parse a YAML inventory file and print the devices connection status:

\"\"\"\nExample\n\"\"\"\nimport asyncio\n\nfrom anta.inventory import AntaInventory\n\n\nasync def main(inv: AntaInventory) -> None:\n    \"\"\"\n    Take an AntaInventory and:\n    1. try to connect to every device in the inventory\n    2. print a message for every device connection status\n    \"\"\"\n    await inv.connect_inventory()\n\n    for device in inv.values():\n        if device.established:\n            print(f\"Device {device.name} is online\")\n        else:\n            print(f\"Could not connect to device {device.name}\")\n\nif __name__ == \"__main__\":\n    # Create the AntaInventory instance\n    inventory = AntaInventory.parse(\n        filename=\"inv.yml\",\n        username=\"arista\",\n        password=\"@rista123\",\n    )\n\n    # Run the main coroutine\n    res = asyncio.run(main(inventory))\n
How to create your inventory file

Please visit this dedicated section for how to use inventory and catalog files.

To run an EOS commands list on the reachable devices from the inventory:

\"\"\"\nExample\n\"\"\"\n# This is needed to run the script for python < 3.10 for typing annotations\nfrom __future__ import annotations\n\nimport asyncio\nfrom pprint import pprint\n\nfrom anta.inventory import AntaInventory\nfrom anta.models import AntaCommand\n\n\nasync def main(inv: AntaInventory, commands: list[str]) -> dict[str, list[AntaCommand]]:\n    \"\"\"\n    Take an AntaInventory and a list of commands as string and:\n    1. try to connect to every device in the inventory\n    2. collect the results of the commands from each device\n\n    Returns:\n      a dictionary where key is the device name and the value is the list of AntaCommand ran towards the device\n    \"\"\"\n    await inv.connect_inventory()\n\n    # Make a list of coroutine to run commands towards each connected device\n    coros = []\n    # dict to keep track of the commands per device\n    result_dict = {}\n    for name, device in inv.get_inventory(established_only=True).items():\n        anta_commands = [AntaCommand(command=command, ofmt=\"json\") for command in commands]\n        result_dict[name] = anta_commands\n        coros.append(device.collect_commands(anta_commands))\n\n    # Run the coroutines\n    await asyncio.gather(*coros)\n\n    return result_dict\n\n\nif __name__ == \"__main__\":\n    # Create the AntaInventory instance\n    inventory = AntaInventory.parse(\n        filename=\"inv.yml\",\n        username=\"arista\",\n        password=\"@rista123\",\n    )\n\n    # Create a list of commands with json output\n    commands = [\"show version\", \"show ip bgp summary\"]\n\n    # Run the main asyncio  entry point\n    res = asyncio.run(main(inventory, commands))\n\n    pprint(res)\n

"},{"location":"advanced_usages/as-python-lib/#use-tests-from-anta","title":"Use tests from ANTA","text":"

All the test classes inherit from the same abstract Base Class AntaTest. The Class definition indicates which commands are required for the test and the user should focus only on writing the test function with optional keywords argument. The instance of the class upon creation instantiates a TestResult object that can be accessed later on to check the status of the test ([unset, skipped, success, failure, error]).

"},{"location":"advanced_usages/as-python-lib/#test-structure","title":"Test structure","text":"

All tests are built on a class named AntaTest which provides a complete toolset for a test:

  • Object creation
  • Test definition
  • TestResult definition
  • Abstracted method to collect data

This approach means each time you create a test it will be based on this AntaTest class. Besides that, you will have to provide some elements:

  • name: Name of the test
  • description: A human readable description of your test
  • categories: a list of categories to sort test.
  • commands: a list of command to run. This list must be a list of AntaCommand which is described in the next part of this document.

Here is an example of a hardware test related to device temperature:

from __future__ import annotations\n\nimport logging\nfrom typing import Any, Dict, List, Optional, cast\n\nfrom anta.models import AntaTest, AntaCommand\n\n\nclass VerifyTemperature(AntaTest):\n    \"\"\"\n    Verifies device temparture is currently OK.\n    \"\"\"\n\n    # The test name\n    name = \"VerifyTemperature\"\n    # A small description of the test, usually the first line of the class docstring\n    description = \"Verifies device temparture is currently OK\"\n    # The category of the test, usually the module name\n    categories = [\"hardware\"]\n    # The command(s) used for the test. Could be a template instead\n    commands = [AntaCommand(command=\"show system environment temperature\", ofmt=\"json\")]\n\n    # Decorator\n    @AntaTest.anta_test\n    # abstract method that must be defined by the child Test class\n    def test(self) -> None:\n        \"\"\"Run VerifyTemperature validation\"\"\"\n        command_output = cast(Dict[str, Dict[Any, Any]], self.instance_commands[0].output)\n        temperature_status = command_output[\"systemStatus\"] if \"systemStatus\" in command_output.keys() else \"\"\n        if temperature_status == \"temperatureOk\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device temperature is not OK, systemStatus: {temperature_status }\")\n

When you run the test, object will automatically call its anta.models.AntaTest.collect() method to get device output for each command if no pre-collected data was given to the test. This method does a loop to call anta.inventory.models.InventoryDevice.collect() methods which is in charge of managing device connection and how to get data.

run test offline

You can also pass eos data directly to your test if you want to validate data collected in a different workflow. An example is provided below just for information:

test = VerifyTemperature(device, eos_data=test_data[\"eos_data\"])\nasyncio.run(test.test())\n

The test function is always the same and must be defined with the @AntaTest.anta_test decorator. This function takes at least one argument which is a anta.inventory.models.InventoryDevice object. In some cases a test would rely on some additional inputs from the user, for instance the number of expected peers or some expected numbers. All parameters must come with a default value and the test function should validate the parameters values (at this stage this is the only place where validation can be done but there are future plans to make this better).

class VerifyTemperature(AntaTest):\n    ...\n    @AntaTest.anta_test\n    def test(self) -> None:\n        pass\n\nclass VerifyTransceiversManufacturers(AntaTest):\n    ...\n    @AntaTest.anta_test\n    def test(self, manufacturers: Optional[List[str]] = None) -> None:\n        # validate the manufactures parameter\n        pass\n

The test itself does not return any value, but the result is directly available from your AntaTest object and exposes a anta.result_manager.models.TestResult object with result, name of the test and optional messages:

  • name (str): Device name where the test has run.
  • test (str): Test name runs on the device.
  • categories (List[str]): List of categories the TestResult belongs to, by default the AntaTest categories.
  • description (str): TestResult description, by default the AntaTest description.
  • results (str): Result of the test. Can be one of [\u201cunset\u201d, \u201csuccess\u201d, \u201cfailure\u201d, \u201cerror\u201d, \u201cskipped\u201d].
  • message (str, optional): Message to report after the test if any.
  • custom_field (str, optional): Custom field to store a string for flexibility in integrating with ANTA
from anta.tests.hardware import VerifyTemperature\n\ntest = VerifyTemperature(device, eos_data=test_data[\"eos_data\"])\nasyncio.run(test.test())\nassert test.result.result == \"success\"\n
"},{"location":"advanced_usages/as-python-lib/#classes-for-commands","title":"Classes for commands","text":"

To make it easier to get data, ANTA defines 2 different classes to manage commands to send to devices:

"},{"location":"advanced_usages/as-python-lib/#antacommand-class","title":"AntaCommand Class","text":"

Represent a command with following information:

  • Command to run
  • Output format expected
  • eAPI version
  • Output of the command

Usage example:

from anta.models import AntaCommand\n\ncmd1 = AntaCommand(command=\"show zerotouch\")\ncmd2 = AntaCommand(command=\"show running-config diffs\", ofmt=\"text\")\n

Command revision and version

  • Most of EOS commands return a JSON structure according to a model (some commands may not be modeled hence the necessity to use text outformat sometimes.
  • The model can change across time (adding feature, \u2026 ) and when the model is changed in a non backward-compatible way, the revision number is bumped. The initial model starts with revision 1.
  • A revision applies to a particular CLI command whereas a version is global to an eAPI call. The version is internally translated to a specific revision for each CLI command in the RPC call. The currently supported version values are 1 and latest.
  • A revision takes precedence over a version (e.g. if a command is run with version=\u201dlatest\u201d and revision=1, the first revision of the model is returned)
  • By default, eAPI returns the first revision of each model to ensure that when upgrading, integrations with existing tools are not broken. This is done by using by default version=1 in eAPI calls.

By default, ANTA uses version=\"latest\" in AntaCommand, but when developing tests, the revision MUST be provided when the outformat of the command is json. As explained earlier, this is to ensure that the eAPI always returns the same output model and that the test remains always valid from the day it was created. For some commands, you may also want to run them with a different revision or version.

For instance, the VerifyBFDPeersHealth test leverages the first revision of show bfd peers:

# revision 1 as later revision introduce additional nesting for type\ncommands = [AntaCommand(command=\"show bfd peers\", revision=1)]\n
"},{"location":"advanced_usages/as-python-lib/#antatemplate-class","title":"AntaTemplate Class","text":"

Because some command can require more dynamic than just a command with no parameter provided by user, ANTA supports command template: you define a template in your test class and user provide parameters when creating test object.

class RunArbitraryTemplateCommand(AntaTest):\n    \"\"\"\n    Run an EOS command and return result\n    Based on AntaTest to build relevant output for pytest\n    \"\"\"\n\n    name = \"Run aributrary EOS command\"\n    description = \"To be used only with anta debug commands\"\n    template = AntaTemplate(template=\"show interfaces {ifd}\")\n    categories = [\"debug\"]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        errdisabled_interfaces = [interface for interface, value in response[\"interfaceStatuses\"].items() if value[\"linkStatus\"] == \"errdisabled\"]\n        ...\n\n\nparams = [{\"ifd\": \"Ethernet2\"}, {\"ifd\": \"Ethernet49/1\"}]\nrun_command1 = RunArbitraryTemplateCommand(device_anta, params)\n

In this example, test waits for interfaces to check from user setup and will only check for interfaces in params

"},{"location":"advanced_usages/caching/","title":"Caching in ANTA","text":"

ANTA is a streamlined Python framework designed for efficient interaction with network devices. This section outlines how ANTA incorporates caching mechanisms to collect command outputs from network devices.

"},{"location":"advanced_usages/caching/#configuration","title":"Configuration","text":"

By default, ANTA utilizes aiocache\u2019s memory cache backend, also called SimpleMemoryCache. This library aims for simplicity and supports asynchronous operations to go along with Python asyncio used in ANTA.

The _init_cache() method of the AntaDevice abstract class initializes the cache. Child classes can override this method to tweak the cache configuration:

def _init_cache(self) -> None:\n    \"\"\"\n    Initialize cache for the device, can be overridden by subclasses to manipulate how it works\n    \"\"\"\n    self.cache = Cache(cache_class=Cache.MEMORY, ttl=60, namespace=self.name, plugins=[HitMissRatioPlugin()])\n    self.cache_locks = defaultdict(asyncio.Lock)\n

The cache is also configured with aiocache\u2019s HitMissRatioPlugin plugin to calculate the ratio of hits the cache has and give useful statistics for logging purposes in ANTA.

"},{"location":"advanced_usages/caching/#cache-key-design","title":"Cache key design","text":"

The cache is initialized per AntaDevice and uses the following cache key design:

<device_name>:<uid>

The uid is an attribute of AntaCommand, which is a unique identifier generated from the command, version, revision and output format.

Each UID has its own asyncio lock. This design allows coroutines that need to access the cache for different UIDs to do so concurrently. The locks are managed by the self.cache_locks dictionary.

"},{"location":"advanced_usages/caching/#mechanisms","title":"Mechanisms","text":"

By default, once the cache is initialized, it is used in the collect() method of AntaDevice. The collect() method prioritizes retrieving the output of the command from the cache. If the output is not in the cache, the private _collect() method will retrieve and then store it for future access.

"},{"location":"advanced_usages/caching/#how-to-disable-caching","title":"How to disable caching","text":"

Caching is enabled by default in ANTA following the previous configuration and mechanisms.

There might be scenarios where caching is not wanted. You can disable caching in multiple ways in ANTA:

  1. Caching can be disabled globally, for ALL commands on ALL devices, using the --disable-cache global flag when invoking anta at the CLI:
    anta --disable-cache --username arista --password arista nrfu table\n
  2. Caching can be disabled per device, network or range by setting the disable_cache key to True when defining the ANTA Inventory file:

    anta_inventory:\n  hosts:\n  - host: 172.20.20.101\n    name: DC1-SPINE1\n    tags: [\"SPINE\", \"DC1\"]\n    disable_cache: True  # Set this key to True\n  - host: 172.20.20.102\n    name: DC1-SPINE2\n    tags: [\"SPINE\", \"DC1\"]\n    disable_cache: False # Optional since it's the default\n\n  networks:\n  - network: \"172.21.21.0/24\"\n    disable_cache: True\n\n  ranges:\n  - start: 172.22.22.10\n    end: 172.22.22.19\n    disable_cache: True\n
    This approach effectively disables caching for ALL commands sent to devices targeted by the disable_cache key.

  3. For tests developers, caching can be disabled for a specific AntaCommand or AntaTemplate by setting the use_cache attribute to False. That means the command output will always be collected on the device and therefore, never use caching.

"},{"location":"advanced_usages/caching/#disable-caching-in-a-child-class-of-antadevice","title":"Disable caching in a child class of AntaDevice","text":"

Since caching is implemented at the AntaDevice abstract class level, all subclasses will inherit that default behavior. As a result, if you need to disable caching in any custom implementation of AntaDevice outside of the ANTA framework, you must initialize AntaDevice with disable_cache set to True:

class AnsibleEOSDevice(AntaDevice):\n  \"\"\"\n  Implementation of an AntaDevice using Ansible HttpApi plugin for EOS.\n  \"\"\"\n  def __init__(self, name: str, connection: ConnectionBase, tags: set = None) -> None:\n      super().__init__(name, tags, disable_cache=True)\n
"},{"location":"advanced_usages/custom-tests/","title":"Developing ANTA tests","text":"

This documentation applies for both creating tests in ANTA or creating your own test package.

ANTA is not only a Python library with a CLI and a collection of built-in tests, it is also a framework you can extend by building your own tests.

"},{"location":"advanced_usages/custom-tests/#generic-approach","title":"Generic approach","text":"

A test is a Python class where a test function is defined and will be run by the framework.

ANTA provides an abstract class AntaTest. This class does the heavy lifting and provide the logic to define, collect and test data. The code below is an example of a simple test in ANTA, which is an AntaTest subclass:

from anta.models import AntaTest, AntaCommand\nfrom anta.decorators import skip_on_platforms\n\n\nclass VerifyTemperature(AntaTest):\n    \"\"\"Verifies if the device temperature is within acceptable limits.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device temperature is currently OK: 'temperatureOk'.\n    * Failure: The test will fail if the device temperature is NOT OK.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyTemperature:\n    ```\n    \"\"\"\n\n    name = \"VerifyTemperature\"\n    description = \"Verifies the device temperature.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system environment temperature\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTemperature.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        temperature_status = command_output.get(\"systemStatus\", \"\")\n        if temperature_status == \"temperatureOk\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device temperature exceeds acceptable limits. Current system status: '{temperature_status}'\")\n

AntaTest also provide more advanced capabilities like AntaCommand templating using the AntaTemplate class or test inputs definition and validation using AntaTest.Input pydantic model. This will be discussed in the sections below.

"},{"location":"advanced_usages/custom-tests/#antatest-structure","title":"AntaTest structure","text":"

Full AntaTest API documentation is available in the API documentation section

"},{"location":"advanced_usages/custom-tests/#class-attributes","title":"Class Attributes","text":"
  • name (str): Name of the test. Used during reporting.
  • description (str): A human readable description of your test.
  • categories (list[str]): A list of categories in which the test belongs.
  • commands ([list[AntaCommand | AntaTemplate]]): A list of command to collect from devices. This list must be a list of AntaCommand or AntaTemplate instances. Rendering AntaTemplate instances will be discussed later.

Info

All these class attributes are mandatory. If any attribute is missing, a NotImplementedError exception will be raised during class instantiation.

"},{"location":"advanced_usages/custom-tests/#instance-attributes","title":"Instance Attributes","text":"

Info

You can access an instance attribute in your code using the self reference. E.g. you can access the test input values using self.inputs.

Attributes:

Name Type Description device AntaDevice instance on which this test is run

inputs: AntaTest.Input instance carrying the test inputs instance_commands: List of AntaCommand instances of this test result: TestResult instance representing the result of this test logger: Python logger for this test instance

Logger object

ANTA already provides comprehensive logging at every steps of a test execution. The AntaTest class also provides a logger attribute that is a Python logger specific to the test instance. See Python documentation for more information.

AntaDevice object

Even if device is not a private attribute, you should not need to access this object in your code.

"},{"location":"advanced_usages/custom-tests/#test-inputs","title":"Test Inputs","text":"

AntaTest.Input is a pydantic model that allow test developers to define their test inputs. pydantic provides out of the box error handling for test input validation based on the type hints defined by the test developer.

The base definition of AntaTest.Input provides common test inputs for all AntaTest instances:

"},{"location":"advanced_usages/custom-tests/#input-model","title":"Input model","text":"

Full Input model documentation is available in API documentation section

Attributes:

Name Type Description result_overwrite Define fields to overwrite in the TestResult object"},{"location":"advanced_usages/custom-tests/#resultoverwrite-model","title":"ResultOverwrite model","text":"

Full ResultOverwrite model documentation is available in API documentation section

Attributes:

Name Type Description description overwrite TestResult.description

categories: overwrite TestResult.categories custom_field: a free string that will be included in the TestResult object

Note

The pydantic model is configured using the extra=forbid that will fail input validation if extra fields are provided.

"},{"location":"advanced_usages/custom-tests/#methods","title":"Methods","text":"
  • test(self) -> None: This is an abstract method that must be implemented. It contains the test logic that can access the collected command outputs using the instance_commands instance attribute, access the test inputs using the inputs instance attribute and must set the result instance attribute accordingly. It must be implemented using the AntaTest.anta_test decorator that provides logging and will collect commands before executing the test() method.
  • render(self, template: AntaTemplate) -> list[AntaCommand]: This method only needs to be implemented if AntaTemplate instances are present in the commands class attribute. It will be called for every AntaTemplate occurrence and must return a list of AntaCommand using the AntaTemplate.render() method. It can access test inputs using the inputs instance attribute.
"},{"location":"advanced_usages/custom-tests/#test-execution","title":"Test execution","text":"

Below is a high level description of the test execution flow in ANTA:

  1. ANTA will parse the test catalog to get the list of AntaTest subclasses to instantiate and their associated input values. We consider a single AntaTest subclass in the following steps.

  2. ANTA will instantiate the AntaTest subclass and a single device will be provided to the test instance. The Input model defined in the class will also be instantiated at this moment. If any ValidationError is raised, the test execution will be stopped.

  3. If there is any AntaTemplate instance in the commands class attribute, render() will be called for every occurrence. At this moment, the instance_commands attribute has been initialized. If any rendering error occurs, the test execution will be stopped.

  4. The AntaTest.anta_test decorator will collect the commands from the device and update the instance_commands attribute with the outputs. If any collection error occurs, the test execution will be stopped.

  5. The test() method is executed.

"},{"location":"advanced_usages/custom-tests/#writing-an-antatest-subclass","title":"Writing an AntaTest subclass","text":"

In this section, we will go into all the details of writing an AntaTest subclass.

"},{"location":"advanced_usages/custom-tests/#class-definition","title":"Class definition","text":"

Import anta.models.AntaTest and define your own class. Define the mandatory class attributes using anta.models.AntaCommand, anta.models.AntaTemplate or both.

Info

Caching can be disabled per AntaCommand or AntaTemplate by setting the use_cache argument to False. For more details about how caching is implemented in ANTA, please refer to Caching in ANTA.

from anta.models import AntaTest, AntaCommand, AntaTemplate\n\n\nclass <YourTestName>(AntaTest):\n    \"\"\"\n    <a docstring description of your test>\n    \"\"\"\n\n    name = \"YourTestName\"                                           # should be your class name\n    description = \"<test description in human reading format>\"\n    categories = [\"<arbitrary category>\", \"<another arbitrary category>\"]\n    commands = [\n        AntaCommand(\n            command=\"<EOS command to run>\",\n            ofmt=\"<command format output>\",\n            version=\"<eAPI version to use>\",\n            revision=\"<revision to use for the command>\",           # revision has precedence over version\n            use_cache=\"<Use cache for the command>\",\n        ),\n        AntaTemplate(\n            template=\"<Python f-string to render an EOS command>\",\n            ofmt=\"<command format output>\",\n            version=\"<eAPI version to use>\",\n            revision=\"<revision to use for the command>\",           # revision has precedence over version\n            use_cache=\"<Use cache for the command>\",\n        )\n    ]\n
"},{"location":"advanced_usages/custom-tests/#inputs-definition","title":"Inputs definition","text":"

If the user needs to provide inputs for your test, you need to define a pydantic model that defines the schema of the test inputs:

class <YourTestName>(AntaTest):\n    \"\"\"Verifies ...\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if ...\n    * Failure: The test will fail if ...\n\n    Examples\n    --------\n    ```yaml\n    your.module.path:\n      - YourTestName:\n        field_name: example_field_value\n    ```\n    \"\"\"\n    ...\n    class Input(AntaTest.Input):\n        \"\"\"Inputs for my awesome test.\"\"\"\n        <input field name>: <input field type>\n        \"\"\"<input field docstring>\"\"\"\n

To define an input field type, refer to the pydantic documentation about types. You can also leverage anta.custom_types that provides reusable types defined in ANTA tests.

Regarding required, optional and nullable fields, refer to this documentation on how to define them.

Note

All the pydantic features are supported. For instance you can define validators for complex input validation.

"},{"location":"advanced_usages/custom-tests/#template-rendering","title":"Template rendering","text":"

Define the render() method if you have AntaTemplate instances in your commands class attribute:

class <YourTestName>(AntaTest):\n    ...\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        return [template.render(<template param>=input_value) for input_value in self.inputs.<input_field>]\n

You can access test inputs and render as many AntaCommand as desired.

"},{"location":"advanced_usages/custom-tests/#test-definition","title":"Test definition","text":"

Implement the test() method with your test logic:

class <YourTestName>(AntaTest):\n    ...\n    @AntaTest.anta_test\n    def test(self) -> None:\n        pass\n

The logic usually includes the following different stages: 1. Parse the command outputs using the self.instance_commands instance attribute. 2. If needed, access the test inputs using the self.inputs instance attribute and write your conditional logic. 3. Set the result instance attribute to reflect the test result by either calling self.result.is_success() or self.result.is_failure(\"<FAILURE REASON>\"). Sometimes, setting the test result to skipped using self.result.is_skipped(\"<SKIPPED REASON>\") can make sense (e.g. testing the OSPF neighbor states but no neighbor was found). However, you should not need to catch any exception and set the test result to error since the error handling is done by the framework, see below.

The example below is based on the VerifyTemperature test.

class VerifyTemperature(AntaTest):\n    ...\n    @AntaTest.anta_test\n    def test(self) -> None:\n        # Grab output of the collected command\n        command_output = self.instance_commands[0].json_output\n\n        # Do your test: In this example we check a specific field of the JSON output from EOS\n        temperature_status = command_output[\"systemStatus\"] if \"systemStatus\" in command_output.keys() else \"\"\n        if temperature_status == \"temperatureOk\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device temperature exceeds acceptable limits. Current system status: '{temperature_status}'\")\n

As you can see there is no error handling to do in your code. Everything is packaged in the AntaTest.anta_tests decorator and below is a simple example of error captured when trying to access a dictionary with an incorrect key:

class VerifyTemperature(AntaTest):\n    ...\n    @AntaTest.anta_test\n    def test(self) -> None:\n        # Grab output of the collected command\n        command_output = self.instance_commands[0].json_output\n\n        # Access the dictionary with an incorrect key\n        command_output['incorrectKey']\n
ERROR    Exception raised for test VerifyTemperature (on device 192.168.0.10) - KeyError ('incorrectKey')\n

Get stack trace for debugging

If you want to access to the full exception stack, you can run ANTA in debug mode by setting the ANTA_DEBUG environment variable to true. Example:

$ ANTA_DEBUG=true anta nrfu --catalog test_custom.yml text\n

"},{"location":"advanced_usages/custom-tests/#test-decorators","title":"Test decorators","text":"

In addition to the required AntaTest.anta_tests decorator, ANTA offers a set of optional decorators for further test customization:

  • anta.decorators.deprecated_test: Use this to log a message of WARNING severity when a test is deprecated.
  • anta.decorators.skip_on_platforms: Use this to skip tests for functionalities that are not supported on specific platforms.
from anta.decorators import skip_on_platforms\n\nclass VerifyTemperature(AntaTest):\n    ...\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        pass\n
"},{"location":"advanced_usages/custom-tests/#access-your-custom-tests-in-the-test-catalog","title":"Access your custom tests in the test catalog","text":"

This section is required only if you are not merging your development into ANTA. Otherwise, just follow contribution guide.

For that, you need to create your own Python package as described in this hitchhiker\u2019s guide to package Python code. We assume it is well known and we won\u2019t focus on this aspect. Thus, your package must be impartable by ANTA hence available in the module search path sys.path (you can use PYTHONPATH for example).

It is very similar to what is documented in catalog section but you have to use your own package name.2

Let say the custom Python package is anta_custom and the test is defined in anta_custom.dc_project Python module, the test catalog would look like:

anta_custom.dc_project:\n  - VerifyFeatureX:\n      minimum: 1\n
And now you can run your NRFU tests with the CLI:

anta nrfu text --catalog test_custom.yml\nspine01 :: verify_dynamic_vlan :: FAILURE (Device has 0 configured, we expect at least 1)\nspine02 :: verify_dynamic_vlan :: FAILURE (Device has 0 configured, we expect at least 1)\nleaf01 :: verify_dynamic_vlan :: SUCCESS\nleaf02 :: verify_dynamic_vlan :: SUCCESS\nleaf03 :: verify_dynamic_vlan :: SUCCESS\nleaf04 :: verify_dynamic_vlan :: SUCCESS\n
"},{"location":"api/catalog/","title":"Test Catalog","text":""},{"location":"api/catalog/#anta.catalog.AntaCatalog","title":"AntaCatalog","text":"
AntaCatalog(tests: list[AntaTestDefinition] | None = None, filename: str | Path | None = None)\n

Class representing an ANTA Catalog.

It can be instantiated using its constructor or one of the static methods: parse(), from_list() or from_dict()

Source code in anta/catalog.py
def __init__(\n    self,\n    tests: list[AntaTestDefinition] | None = None,\n    filename: str | Path | None = None,\n) -> None:\n    \"\"\"Instantiate an AntaCatalog instance.\n\n    Parameters\n    ----------\n        tests: A list of AntaTestDefinition instances.\n        filename: The path from which the catalog is loaded.\n\n    \"\"\"\n    self._tests: list[AntaTestDefinition] = []\n    if tests is not None:\n        self._tests = tests\n    self._filename: Path | None = None\n    if filename is not None:\n        if isinstance(filename, Path):\n            self._filename = filename\n        else:\n            self._filename = Path(filename)\n\n    # Default indexes for faster access\n    self.tag_to_tests: defaultdict[str | None, set[AntaTestDefinition]] = defaultdict(set)\n    self.tests_without_tags: set[AntaTestDefinition] = set()\n    self.indexes_built: bool = False\n    self.final_tests_count: int = 0\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.filename","title":"filename property","text":"
filename: Path | None\n

Path of the file used to create this AntaCatalog instance.

"},{"location":"api/catalog/#anta.catalog.AntaCatalog.tests","title":"tests property writable","text":"
tests: list[AntaTestDefinition]\n

List of AntaTestDefinition in this catalog.

"},{"location":"api/catalog/#anta.catalog.AntaCatalog.build_indexes","title":"build_indexes","text":"
build_indexes(filtered_tests: set[str] | None = None) -> None\n

Indexes tests by their tags for quick access during filtering operations.

If a filtered_tests set is provided, only the tests in this set will be indexed.

This method populates two attributes: - tag_to_tests: A dictionary mapping each tag to a set of tests that contain it. - tests_without_tags: A set of tests that do not have any tags.

Once the indexes are built, the indexes_built attribute is set to True.

Source code in anta/catalog.py
def build_indexes(self, filtered_tests: set[str] | None = None) -> None:\n    \"\"\"Indexes tests by their tags for quick access during filtering operations.\n\n    If a `filtered_tests` set is provided, only the tests in this set will be indexed.\n\n    This method populates two attributes:\n    - tag_to_tests: A dictionary mapping each tag to a set of tests that contain it.\n    - tests_without_tags: A set of tests that do not have any tags.\n\n    Once the indexes are built, the `indexes_built` attribute is set to True.\n    \"\"\"\n    for test in self.tests:\n        # Skip tests that are not in the specified filtered_tests set\n        if filtered_tests and test.test.name not in filtered_tests:\n            continue\n\n        # Indexing by tag\n        if test.inputs.filters and (test_tags := test.inputs.filters.tags):\n            for tag in test_tags:\n                self.tag_to_tests[tag].add(test)\n        else:\n            self.tests_without_tags.add(test)\n\n    self.tag_to_tests[None] = self.tests_without_tags\n    self.indexes_built = True\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.dump","title":"dump","text":"
dump() -> AntaCatalogFile\n

Return an AntaCatalogFile instance from this AntaCatalog instance.

Returns:

Type Description An AntaCatalogFile instance containing tests of this AntaCatalog instance. Source code in anta/catalog.py
def dump(self) -> AntaCatalogFile:\n    \"\"\"Return an AntaCatalogFile instance from this AntaCatalog instance.\n\n    Returns\n    -------\n        An AntaCatalogFile instance containing tests of this AntaCatalog instance.\n    \"\"\"\n    root: dict[ImportString[Any], list[AntaTestDefinition]] = {}\n    for test in self.tests:\n        # Cannot use AntaTest.module property as the class is not instantiated\n        root.setdefault(test.test.__module__, []).append(test)\n    return AntaCatalogFile(root=root)\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.from_dict","title":"from_dict staticmethod","text":"
from_dict(data: RawCatalogInput, filename: str | Path | None = None) -> AntaCatalog\n

Create an AntaCatalog instance from a dictionary data structure.

See RawCatalogInput type alias for details. It is the data structure returned by yaml.load() function of a valid YAML Test Catalog file.

Source code in anta/catalog.py
@staticmethod\ndef from_dict(data: RawCatalogInput, filename: str | Path | None = None) -> AntaCatalog:\n    \"\"\"Create an AntaCatalog instance from a dictionary data structure.\n\n    See RawCatalogInput type alias for details.\n    It is the data structure returned by `yaml.load()` function of a valid\n    YAML Test Catalog file.\n\n    Parameters\n    ----------\n        data: Python dictionary used to instantiate the AntaCatalog instance\n        filename: value to be set as AntaCatalog instance attribute\n\n    \"\"\"\n    tests: list[AntaTestDefinition] = []\n    if data is None:\n        logger.warning(\"Catalog input data is empty\")\n        return AntaCatalog(filename=filename)\n\n    if not isinstance(data, dict):\n        msg = f\"Wrong input type for catalog data{f' (from {filename})' if filename is not None else ''}, must be a dict, got {type(data).__name__}\"\n        raise TypeError(msg)\n\n    try:\n        catalog_data = AntaCatalogFile(data)  # type: ignore[arg-type]\n    except ValidationError as e:\n        anta_log_exception(\n            e,\n            f\"Test catalog is invalid!{f' (from {filename})' if filename is not None else ''}\",\n            logger,\n        )\n        raise\n    for t in catalog_data.root.values():\n        tests.extend(t)\n    return AntaCatalog(tests, filename=filename)\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.from_list","title":"from_list staticmethod","text":"
from_list(data: ListAntaTestTuples) -> AntaCatalog\n

Create an AntaCatalog instance from a list data structure.

See ListAntaTestTuples type alias for details.

Source code in anta/catalog.py
@staticmethod\ndef from_list(data: ListAntaTestTuples) -> AntaCatalog:\n    \"\"\"Create an AntaCatalog instance from a list data structure.\n\n    See ListAntaTestTuples type alias for details.\n\n    Parameters\n    ----------\n        data: Python list used to instantiate the AntaCatalog instance\n\n    \"\"\"\n    tests: list[AntaTestDefinition] = []\n    try:\n        tests.extend(AntaTestDefinition(test=test, inputs=inputs) for test, inputs in data)\n    except ValidationError as e:\n        anta_log_exception(e, \"Test catalog is invalid!\", logger)\n        raise\n    return AntaCatalog(tests)\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.get_tests_by_tags","title":"get_tests_by_tags","text":"
get_tests_by_tags(tags: set[str], *, strict: bool = False) -> set[AntaTestDefinition]\n

Return all tests that match a given set of tags, according to the specified strictness.

Returns:

Type Description set[AntaTestDefinition]: A set of tests that match the given tags.

Raises:

Type Description ValueError: If the indexes have not been built prior to method call. Source code in anta/catalog.py
def get_tests_by_tags(self, tags: set[str], *, strict: bool = False) -> set[AntaTestDefinition]:\n    \"\"\"Return all tests that match a given set of tags, according to the specified strictness.\n\n    Parameters\n    ----------\n        tags: The tags to filter tests by. If empty, return all tests without tags.\n        strict: If True, returns only tests that contain all specified tags (intersection).\n                If False, returns tests that contain any of the specified tags (union).\n\n    Returns\n    -------\n        set[AntaTestDefinition]: A set of tests that match the given tags.\n\n    Raises\n    ------\n        ValueError: If the indexes have not been built prior to method call.\n    \"\"\"\n    if not self.indexes_built:\n        msg = \"Indexes have not been built yet. Call build_indexes() first.\"\n        raise ValueError(msg)\n    if not tags:\n        return self.tag_to_tests[None]\n\n    filtered_sets = [self.tag_to_tests[tag] for tag in tags if tag in self.tag_to_tests]\n    if not filtered_sets:\n        return set()\n\n    if strict:\n        return set.intersection(*filtered_sets)\n    return set.union(*filtered_sets)\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.merge","title":"merge","text":"
merge(catalog: AntaCatalog) -> AntaCatalog\n

Merge two AntaCatalog instances.

Returns:

Type Description A new AntaCatalog instance containing the tests of the two instances. Source code in anta/catalog.py
def merge(self, catalog: AntaCatalog) -> AntaCatalog:\n    \"\"\"Merge two AntaCatalog instances.\n\n    Parameters\n    ----------\n        catalog: AntaCatalog instance to merge to this instance.\n\n    Returns\n    -------\n        A new AntaCatalog instance containing the tests of the two instances.\n    \"\"\"\n    return AntaCatalog(tests=self.tests + catalog.tests)\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalog.parse","title":"parse staticmethod","text":"
parse(filename: str | Path, file_format: Literal['yaml', 'json'] = 'yaml') -> AntaCatalog\n

Create an AntaCatalog instance from a test catalog file.

Source code in anta/catalog.py
@staticmethod\ndef parse(filename: str | Path, file_format: Literal[\"yaml\", \"json\"] = \"yaml\") -> AntaCatalog:\n    \"\"\"Create an AntaCatalog instance from a test catalog file.\n\n    Parameters\n    ----------\n        filename: Path to test catalog YAML or JSON fil\n        file_format: Format of the file, either 'yaml' or 'json'\n\n    \"\"\"\n    if file_format not in [\"yaml\", \"json\"]:\n        message = f\"'{file_format}' is not a valid format for an AntaCatalog file. Only 'yaml' and 'json' are supported.\"\n        raise ValueError(message)\n\n    try:\n        file: Path = filename if isinstance(filename, Path) else Path(filename)\n        with file.open(encoding=\"UTF-8\") as f:\n            data = safe_load(f) if file_format == \"yaml\" else json_load(f)\n    except (TypeError, YAMLError, OSError, ValueError) as e:\n        message = f\"Unable to parse ANTA Test Catalog file '{filename}'\"\n        anta_log_exception(e, message, logger)\n        raise\n\n    return AntaCatalog.from_dict(data, filename=filename)\n
"},{"location":"api/catalog/#anta.catalog.AntaTestDefinition","title":"AntaTestDefinition","text":"
AntaTestDefinition(**data: type[AntaTest] | AntaTest.Input | dict[str, Any] | None)\n

Bases: BaseModel

Define a test with its associated inputs.

test: An AntaTest concrete subclass inputs: The associated AntaTest.Input subclass instance

https://docs.pydantic.dev/2.0/usage/validators/#using-validation-context-with-basemodel-initialization.

Source code in anta/catalog.py
def __init__(self, **data: type[AntaTest] | AntaTest.Input | dict[str, Any] | None) -> None:\n    \"\"\"Inject test in the context to allow to instantiate Input in the BeforeValidator.\n\n    https://docs.pydantic.dev/2.0/usage/validators/#using-validation-context-with-basemodel-initialization.\n    \"\"\"\n    self.__pydantic_validator__.validate_python(\n        data,\n        self_instance=self,\n        context={\"test\": data[\"test\"]},\n    )\n    super(BaseModel, self).__init__()\n
"},{"location":"api/catalog/#anta.catalog.AntaTestDefinition.check_inputs","title":"check_inputs","text":"
check_inputs() -> AntaTestDefinition\n

Check the inputs field typing.

The inputs class attribute needs to be an instance of the AntaTest.Input subclass defined in the class test.

Source code in anta/catalog.py
@model_validator(mode=\"after\")\ndef check_inputs(self) -> AntaTestDefinition:\n    \"\"\"Check the `inputs` field typing.\n\n    The `inputs` class attribute needs to be an instance of the AntaTest.Input subclass defined in the class `test`.\n    \"\"\"\n    if not isinstance(self.inputs, self.test.Input):\n        msg = f\"Test input has type {self.inputs.__class__.__qualname__} but expected type {self.test.Input.__qualname__}\"\n        raise ValueError(msg)  # noqa: TRY004 pydantic catches ValueError or AssertionError, no TypeError\n    return self\n
"},{"location":"api/catalog/#anta.catalog.AntaTestDefinition.instantiate_inputs","title":"instantiate_inputs classmethod","text":"
instantiate_inputs(data: AntaTest.Input | dict[str, Any] | None, info: ValidationInfo) -> AntaTest.Input\n

Ensure the test inputs can be instantiated and thus are valid.

If the test has no inputs, allow the user to omit providing the inputs field. If the test has inputs, allow the user to provide a valid dictionary of the input fields. This model validator will instantiate an Input class from the test class field.

Source code in anta/catalog.py
@field_validator(\"inputs\", mode=\"before\")\n@classmethod\ndef instantiate_inputs(\n    cls: type[AntaTestDefinition],\n    data: AntaTest.Input | dict[str, Any] | None,\n    info: ValidationInfo,\n) -> AntaTest.Input:\n    \"\"\"Ensure the test inputs can be instantiated and thus are valid.\n\n    If the test has no inputs, allow the user to omit providing the `inputs` field.\n    If the test has inputs, allow the user to provide a valid dictionary of the input fields.\n    This model validator will instantiate an Input class from the `test` class field.\n    \"\"\"\n    if info.context is None:\n        msg = \"Could not validate inputs as no test class could be identified\"\n        raise ValueError(msg)\n    # Pydantic guarantees at this stage that test_class is a subclass of AntaTest because of the ordering\n    # of fields in the class definition - so no need to check for this\n    test_class = info.context[\"test\"]\n    if not (isclass(test_class) and issubclass(test_class, AntaTest)):\n        msg = f\"Could not validate inputs as no test class {test_class} is not a subclass of AntaTest\"\n        raise ValueError(msg)\n\n    if isinstance(data, AntaTest.Input):\n        return data\n    try:\n        if data is None:\n            return test_class.Input()\n        if isinstance(data, dict):\n            return test_class.Input(**data)\n    except ValidationError as e:\n        inputs_msg = str(e).replace(\"\\n\", \"\\n\\t\")\n        err_type = \"wrong_test_inputs\"\n        raise PydanticCustomError(\n            err_type,\n            f\"{test_class.name} test inputs are not valid: {inputs_msg}\\n\",\n            {\"errors\": e.errors()},\n        ) from e\n    msg = f\"Could not instantiate inputs as type {type(data).__name__} is not valid\"\n    raise ValueError(msg)\n
"},{"location":"api/catalog/#anta.catalog.AntaTestDefinition.serialize_model","title":"serialize_model","text":"
serialize_model() -> dict[str, AntaTest.Input]\n

Serialize the AntaTestDefinition model.

The dictionary representing the model will be look like:

<AntaTest subclass name>:\n        <AntaTest.Input compliant dictionary>\n

Returns:

Type Description A dictionary representing the model. Source code in anta/catalog.py
@model_serializer()\ndef serialize_model(self) -> dict[str, AntaTest.Input]:\n    \"\"\"Serialize the AntaTestDefinition model.\n\n    The dictionary representing the model will be look like:\n    ```\n    <AntaTest subclass name>:\n            <AntaTest.Input compliant dictionary>\n    ```\n\n    Returns\n    -------\n        A dictionary representing the model.\n    \"\"\"\n    return {self.test.__name__: self.inputs}\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalogFile","title":"AntaCatalogFile","text":"

Bases: RootModel[dict[ImportString[Any], list[AntaTestDefinition]]]

Represents an ANTA Test Catalog File.

Example:
A valid test catalog file must have the following structure:\n```\n<Python module>:\n    - <AntaTest subclass>:\n        <AntaTest.Input compliant dictionary>\n```\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalogFile.check_tests","title":"check_tests classmethod","text":"
check_tests(data: Any) -> Any\n

Allow the user to provide a Python data structure that only has string values.

This validator will try to flatten and import Python modules, check if the tests classes are actually defined in their respective Python module and instantiate Input instances with provided value to validate test inputs.

Source code in anta/catalog.py
@model_validator(mode=\"before\")\n@classmethod\ndef check_tests(cls: type[AntaCatalogFile], data: Any) -> Any:  # noqa: ANN401\n    \"\"\"Allow the user to provide a Python data structure that only has string values.\n\n    This validator will try to flatten and import Python modules, check if the tests classes\n    are actually defined in their respective Python module and instantiate Input instances\n    with provided value to validate test inputs.\n    \"\"\"\n    if isinstance(data, dict):\n        if not data:\n            return data\n        typed_data: dict[ModuleType, list[Any]] = AntaCatalogFile.flatten_modules(data)\n        for module, tests in typed_data.items():\n            test_definitions: list[AntaTestDefinition] = []\n            for test_definition in tests:\n                if isinstance(test_definition, AntaTestDefinition):\n                    test_definitions.append(test_definition)\n                    continue\n                if not isinstance(test_definition, dict):\n                    msg = f\"Syntax error when parsing: {test_definition}\\nIt must be a dictionary. Check the test catalog.\"\n                    raise ValueError(msg)  # noqa: TRY004 pydantic catches ValueError or AssertionError, no TypeError\n                if len(test_definition) != 1:\n                    msg = (\n                        f\"Syntax error when parsing: {test_definition}\\n\"\n                        \"It must be a dictionary with a single entry. Check the indentation in the test catalog.\"\n                    )\n                    raise ValueError(msg)\n                for test_name, test_inputs in test_definition.copy().items():\n                    test: type[AntaTest] | None = getattr(module, test_name, None)\n                    if test is None:\n                        msg = (\n                            f\"{test_name} is not defined in Python module {module.__name__}\"\n                            f\"{f' (from {module.__file__})' if module.__file__ is not None else ''}\"\n                        )\n                        raise ValueError(msg)\n                    test_definitions.append(AntaTestDefinition(test=test, inputs=test_inputs))\n            typed_data[module] = test_definitions\n        return typed_data\n    return data\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalogFile.flatten_modules","title":"flatten_modules staticmethod","text":"
flatten_modules(data: dict[str, Any], package: str | None = None) -> dict[ModuleType, list[Any]]\n

Allow the user to provide a data structure with nested Python modules.

Example:
```\nanta.tests.routing:\n  generic:\n    - <AntaTestDefinition>\n  bgp:\n    - <AntaTestDefinition>\n```\n`anta.tests.routing.generic` and `anta.tests.routing.bgp` are importable Python modules.\n
Source code in anta/catalog.py
@staticmethod\ndef flatten_modules(data: dict[str, Any], package: str | None = None) -> dict[ModuleType, list[Any]]:\n    \"\"\"Allow the user to provide a data structure with nested Python modules.\n\n    Example:\n    -------\n        ```\n        anta.tests.routing:\n          generic:\n            - <AntaTestDefinition>\n          bgp:\n            - <AntaTestDefinition>\n        ```\n        `anta.tests.routing.generic` and `anta.tests.routing.bgp` are importable Python modules.\n\n    \"\"\"\n    modules: dict[ModuleType, list[Any]] = {}\n    for module_name, tests in data.items():\n        if package and not module_name.startswith(\".\"):\n            # PLW2901 - we redefine the loop variable on purpose here.\n            module_name = f\".{module_name}\"  # noqa: PLW2901\n        try:\n            module: ModuleType = importlib.import_module(name=module_name, package=package)\n        except Exception as e:  # pylint: disable=broad-exception-caught\n            # A test module is potentially user-defined code.\n            # We need to catch everything if we want to have meaningful logs\n            module_str = f\"{module_name[1:] if module_name.startswith('.') else module_name}{f' from package {package}' if package else ''}\"\n            message = f\"Module named {module_str} cannot be imported. Verify that the module exists and there is no Python syntax issues.\"\n            anta_log_exception(e, message, logger)\n            raise ValueError(message) from e\n        if isinstance(tests, dict):\n            # This is an inner Python module\n            modules.update(AntaCatalogFile.flatten_modules(data=tests, package=module.__name__))\n        elif isinstance(tests, list):\n            # This is a list of AntaTestDefinition\n            modules[module] = tests\n        else:\n            msg = f\"Syntax error when parsing: {tests}\\nIt must be a list of ANTA tests. Check the test catalog.\"\n            raise ValueError(msg)  # noqa: TRY004 pydantic catches ValueError or AssertionError, no TypeError\n    return modules\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalogFile.to_json","title":"to_json","text":"
to_json() -> str\n

Return a JSON representation string of this model.

Returns:

Type Description The JSON representation string of this model. Source code in anta/catalog.py
def to_json(self) -> str:\n    \"\"\"Return a JSON representation string of this model.\n\n    Returns\n    -------\n        The JSON representation string of this model.\n    \"\"\"\n    return self.model_dump_json(serialize_as_any=True, exclude_unset=True, indent=2)\n
"},{"location":"api/catalog/#anta.catalog.AntaCatalogFile.yaml","title":"yaml","text":"
yaml() -> str\n

Return a YAML representation string of this model.

Returns:

Type Description The YAML representation string of this model. Source code in anta/catalog.py
def yaml(self) -> str:\n    \"\"\"Return a YAML representation string of this model.\n\n    Returns\n    -------\n        The YAML representation string of this model.\n    \"\"\"\n    # TODO: Pydantic and YAML serialization/deserialization is not supported natively.\n    # This could be improved.\n    # https://github.com/pydantic/pydantic/issues/1043\n    # Explore if this worth using this: https://github.com/NowanIlfideme/pydantic-yaml\n    return safe_dump(safe_load(self.model_dump_json(serialize_as_any=True, exclude_unset=True)), indent=2, width=math.inf)\n
"},{"location":"api/device/","title":"Device","text":""},{"location":"api/device/#antadevice-base-class","title":"AntaDevice base class","text":""},{"location":"api/device/#uml-representation","title":"UML representation","text":""},{"location":"api/device/#anta.device.AntaDevice","title":"AntaDevice","text":"
AntaDevice(name: str, tags: set[str] | None = None, *, disable_cache: bool = False)\n

Bases: ABC

Abstract class representing a device in ANTA.

An implementation of this class must override the abstract coroutines _collect() and refresh().

Attributes:

Name Type Description name Device name

is_online: True if the device IP is reachable and a port can be open. established: True if remote command execution succeeds. hw_model: Hardware model of the device. tags: Tags for this device. cache: In-memory cache from aiocache library for this device (None if cache is disabled). cache_locks: Dictionary mapping keys to asyncio locks to guarantee exclusive access to the cache if not disabled.

Source code in anta/device.py
def __init__(self, name: str, tags: set[str] | None = None, *, disable_cache: bool = False) -> None:\n    \"\"\"Initialize an AntaDevice.\n\n    Parameters\n    ----------\n        name: Device name.\n        tags: Tags for this device.\n        disable_cache: Disable caching for all commands for this device.\n\n    \"\"\"\n    self.name: str = name\n    self.hw_model: str | None = None\n    self.tags: set[str] = tags if tags is not None else set()\n    # A device always has its own name as tag\n    self.tags.add(self.name)\n    self.is_online: bool = False\n    self.established: bool = False\n    self.cache: Cache | None = None\n    self.cache_locks: defaultdict[str, asyncio.Lock] | None = None\n\n    # Initialize cache if not disabled\n    if not disable_cache:\n        self._init_cache()\n
"},{"location":"api/device/#anta.device.AntaDevice.cache_statistics","title":"cache_statistics property","text":"
cache_statistics: dict[str, Any] | None\n

Returns the device cache statistics for logging purposes.

"},{"location":"api/device/#anta.device.AntaDevice.__hash__","title":"__hash__","text":"
__hash__() -> int\n

Implement hashing for AntaDevice objects.

Source code in anta/device.py
def __hash__(self) -> int:\n    \"\"\"Implement hashing for AntaDevice objects.\"\"\"\n    return hash(self._keys)\n
"},{"location":"api/device/#anta.device.AntaDevice.collect","title":"collect async","text":"
collect(command: AntaCommand, *, collection_id: str | None = None) -> None\n

Collect the output for a specified command.

When caching is activated on both the device and the command, this method prioritizes retrieving the output from the cache. In cases where the output isn\u2019t cached yet, it will be freshly collected and then stored in the cache for future access. The method employs asynchronous locks based on the command\u2019s UID to guarantee exclusive access to the cache.

When caching is NOT enabled, either at the device or command level, the method directly collects the output via the private _collect method without interacting with the cache.

Source code in anta/device.py
async def collect(self, command: AntaCommand, *, collection_id: str | None = None) -> None:\n    \"\"\"Collect the output for a specified command.\n\n    When caching is activated on both the device and the command,\n    this method prioritizes retrieving the output from the cache. In cases where the output isn't cached yet,\n    it will be freshly collected and then stored in the cache for future access.\n    The method employs asynchronous locks based on the command's UID to guarantee exclusive access to the cache.\n\n    When caching is NOT enabled, either at the device or command level, the method directly collects the output\n    via the private `_collect` method without interacting with the cache.\n\n    Parameters\n    ----------\n        command: The command to collect.\n        collection_id: An identifier used to build the eAPI request ID.\n    \"\"\"\n    # Need to ignore pylint no-member as Cache is a proxy class and pylint is not smart enough\n    # https://github.com/pylint-dev/pylint/issues/7258\n    if self.cache is not None and self.cache_locks is not None and command.use_cache:\n        async with self.cache_locks[command.uid]:\n            cached_output = await self.cache.get(command.uid)  # pylint: disable=no-member\n\n            if cached_output is not None:\n                logger.debug(\"Cache hit for %s on %s\", command.command, self.name)\n                command.output = cached_output\n            else:\n                await self._collect(command=command, collection_id=collection_id)\n                await self.cache.set(command.uid, command.output)  # pylint: disable=no-member\n    else:\n        await self._collect(command=command, collection_id=collection_id)\n
"},{"location":"api/device/#anta.device.AntaDevice.collect_commands","title":"collect_commands async","text":"
collect_commands(commands: list[AntaCommand], *, collection_id: str | None = None) -> None\n

Collect multiple commands.

Source code in anta/device.py
async def collect_commands(self, commands: list[AntaCommand], *, collection_id: str | None = None) -> None:\n    \"\"\"Collect multiple commands.\n\n    Parameters\n    ----------\n        commands: The commands to collect.\n        collection_id: An identifier used to build the eAPI request ID.\n    \"\"\"\n    await asyncio.gather(*(self.collect(command=command, collection_id=collection_id) for command in commands))\n
"},{"location":"api/device/#anta.device.AntaDevice.copy","title":"copy async","text":"
copy(sources: list[Path], destination: Path, direction: Literal['to', 'from'] = 'from') -> None\n

Copy files to and from the device, usually through SCP.

It is not mandatory to implement this for a valid AntaDevice subclass.

Source code in anta/device.py
async def copy(self, sources: list[Path], destination: Path, direction: Literal[\"to\", \"from\"] = \"from\") -> None:\n    \"\"\"Copy files to and from the device, usually through SCP.\n\n    It is not mandatory to implement this for a valid AntaDevice subclass.\n\n    Parameters\n    ----------\n        sources: List of files to copy to or from the device.\n        destination: Local or remote destination when copying the files. Can be a folder.\n        direction: Defines if this coroutine copies files to or from the device.\n\n    \"\"\"\n    _ = (sources, destination, direction)\n    msg = f\"copy() method has not been implemented in {self.__class__.__name__} definition\"\n    raise NotImplementedError(msg)\n
"},{"location":"api/device/#anta.device.AntaDevice.refresh","title":"refresh abstractmethod async","text":"
refresh() -> None\n

Update attributes of an AntaDevice instance.

This coroutine must update the following attributes of AntaDevice: - is_online: When the device IP is reachable and a port can be open - established: When a command execution succeeds - hw_model: The hardware model of the device

Source code in anta/device.py
@abstractmethod\nasync def refresh(self) -> None:\n    \"\"\"Update attributes of an AntaDevice instance.\n\n    This coroutine must update the following attributes of AntaDevice:\n        - `is_online`: When the device IP is reachable and a port can be open\n        - `established`: When a command execution succeeds\n        - `hw_model`: The hardware model of the device\n    \"\"\"\n
"},{"location":"api/device/#async-eos-device-class","title":"Async EOS device class","text":""},{"location":"api/device/#uml-representation_1","title":"UML representation","text":""},{"location":"api/device/#anta.device.AsyncEOSDevice","title":"AsyncEOSDevice","text":"
AsyncEOSDevice(host: str, username: str, password: str, name: str | None = None, enable_password: str | None = None, port: int | None = None, ssh_port: int | None = 22, tags: set[str] | None = None, timeout: float | None = None, proto: Literal['http', 'https'] = 'https', *, enable: bool = False, insecure: bool = False, disable_cache: bool = False)\n

Bases: AntaDevice

Implementation of AntaDevice for EOS using aio-eapi.

Attributes:

Name Type Description name Device name

is_online: True if the device IP is reachable and a port can be open established: True if remote command execution succeeds hw_model: Hardware model of the device tags: Tags for this device

Source code in anta/device.py
def __init__(\n    self,\n    host: str,\n    username: str,\n    password: str,\n    name: str | None = None,\n    enable_password: str | None = None,\n    port: int | None = None,\n    ssh_port: int | None = 22,\n    tags: set[str] | None = None,\n    timeout: float | None = None,\n    proto: Literal[\"http\", \"https\"] = \"https\",\n    *,\n    enable: bool = False,\n    insecure: bool = False,\n    disable_cache: bool = False,\n) -> None:\n    \"\"\"Instantiate an AsyncEOSDevice.\n\n    Parameters\n    ----------\n        host: Device FQDN or IP.\n        username: Username to connect to eAPI and SSH.\n        password: Password to connect to eAPI and SSH.\n        name: Device name.\n        enable: Collect commands using privileged mode.\n        enable_password: Password used to gain privileged access on EOS.\n        port: eAPI port. Defaults to 80 is proto is 'http' or 443 if proto is 'https'.\n        ssh_port: SSH port.\n        tags: Tags for this device.\n        timeout: Timeout value in seconds for outgoing API calls.\n        insecure: Disable SSH Host Key validation.\n        proto: eAPI protocol. Value can be 'http' or 'https'.\n        disable_cache: Disable caching for all commands for this device.\n\n    \"\"\"\n    if host is None:\n        message = \"'host' is required to create an AsyncEOSDevice\"\n        logger.error(message)\n        raise ValueError(message)\n    if name is None:\n        name = f\"{host}{f':{port}' if port else ''}\"\n    super().__init__(name, tags, disable_cache=disable_cache)\n    if username is None:\n        message = f\"'username' is required to instantiate device '{self.name}'\"\n        logger.error(message)\n        raise ValueError(message)\n    if password is None:\n        message = f\"'password' is required to instantiate device '{self.name}'\"\n        logger.error(message)\n        raise ValueError(message)\n    self.enable = enable\n    self._enable_password = enable_password\n    self._session: asynceapi.Device = asynceapi.Device(host=host, port=port, username=username, password=password, proto=proto, timeout=timeout)\n    ssh_params: dict[str, Any] = {}\n    if insecure:\n        ssh_params[\"known_hosts\"] = None\n    self._ssh_opts: SSHClientConnectionOptions = SSHClientConnectionOptions(\n        host=host, port=ssh_port, username=username, password=password, client_keys=CLIENT_KEYS, **ssh_params\n    )\n
"},{"location":"api/device/#anta.device.AsyncEOSDevice.copy","title":"copy async","text":"
copy(sources: list[Path], destination: Path, direction: Literal['to', 'from'] = 'from') -> None\n

Copy files to and from the device using asyncssh.scp().

Source code in anta/device.py
async def copy(self, sources: list[Path], destination: Path, direction: Literal[\"to\", \"from\"] = \"from\") -> None:\n    \"\"\"Copy files to and from the device using asyncssh.scp().\n\n    Parameters\n    ----------\n        sources: List of files to copy to or from the device.\n        destination: Local or remote destination when copying the files. Can be a folder.\n        direction: Defines if this coroutine copies files to or from the device.\n\n    \"\"\"\n    async with asyncssh.connect(\n        host=self._ssh_opts.host,\n        port=self._ssh_opts.port,\n        tunnel=self._ssh_opts.tunnel,\n        family=self._ssh_opts.family,\n        local_addr=self._ssh_opts.local_addr,\n        options=self._ssh_opts,\n    ) as conn:\n        src: list[tuple[SSHClientConnection, Path]] | list[Path]\n        dst: tuple[SSHClientConnection, Path] | Path\n        if direction == \"from\":\n            src = [(conn, file) for file in sources]\n            dst = destination\n            for file in sources:\n                message = f\"Copying '{file}' from device {self.name} to '{destination}' locally\"\n                logger.info(message)\n\n        elif direction == \"to\":\n            src = sources\n            dst = conn, destination\n            for file in src:\n                message = f\"Copying '{file}' to device {self.name} to '{destination}' remotely\"\n                logger.info(message)\n\n        else:\n            logger.critical(\"'direction' argument to copy() function is invalid: %s\", direction)\n\n            return\n        await asyncssh.scp(src, dst)\n
"},{"location":"api/device/#anta.device.AsyncEOSDevice.refresh","title":"refresh async","text":"
refresh() -> None\n

Update attributes of an AsyncEOSDevice instance.

This coroutine must update the following attributes of AsyncEOSDevice: - is_online: When a device IP is reachable and a port can be open - established: When a command execution succeeds - hw_model: The hardware model of the device

Source code in anta/device.py
async def refresh(self) -> None:\n    \"\"\"Update attributes of an AsyncEOSDevice instance.\n\n    This coroutine must update the following attributes of AsyncEOSDevice:\n    - is_online: When a device IP is reachable and a port can be open\n    - established: When a command execution succeeds\n    - hw_model: The hardware model of the device\n    \"\"\"\n    logger.debug(\"Refreshing device %s\", self.name)\n    self.is_online = await self._session.check_connection()\n    if self.is_online:\n        show_version = AntaCommand(command=\"show version\")\n        await self._collect(show_version)\n        if not show_version.collected:\n            logger.warning(\"Cannot get hardware information from device %s\", self.name)\n        else:\n            self.hw_model = show_version.json_output.get(\"modelName\", None)\n            if self.hw_model is None:\n                logger.critical(\"Cannot parse 'show version' returned by device %s\", self.name)\n    else:\n        logger.warning(\"Could not connect to device %s: cannot open eAPI port\", self.name)\n\n    self.established = bool(self.is_online and self.hw_model)\n
"},{"location":"api/inventory/","title":"Inventory module","text":""},{"location":"api/inventory/#anta.inventory.AntaInventory","title":"AntaInventory","text":"

Bases: dict[str, AntaDevice]

Inventory abstraction for ANTA framework.

"},{"location":"api/inventory/#anta.inventory.AntaInventory.devices","title":"devices property","text":"
devices: list[AntaDevice]\n

List of AntaDevice in this inventory.

"},{"location":"api/inventory/#anta.inventory.AntaInventory.__setitem__","title":"__setitem__","text":"
__setitem__(key: str, value: AntaDevice) -> None\n

Set a device in the inventory.

Source code in anta/inventory/__init__.py
def __setitem__(self, key: str, value: AntaDevice) -> None:\n    \"\"\"Set a device in the inventory.\"\"\"\n    if key != value.name:\n        msg = f\"The key must be the device name for device '{value.name}'. Use AntaInventory.add_device().\"\n        raise RuntimeError(msg)\n    return super().__setitem__(key, value)\n
"},{"location":"api/inventory/#anta.inventory.AntaInventory.add_device","title":"add_device","text":"
add_device(device: AntaDevice) -> None\n

Add a device to final inventory.

Source code in anta/inventory/__init__.py
def add_device(self, device: AntaDevice) -> None:\n    \"\"\"Add a device to final inventory.\n\n    Parameters\n    ----------\n        device: Device object to be added\n\n    \"\"\"\n    self[device.name] = device\n
"},{"location":"api/inventory/#anta.inventory.AntaInventory.connect_inventory","title":"connect_inventory async","text":"
connect_inventory() -> None\n

Run refresh() coroutines for all AntaDevice objects in this inventory.

Source code in anta/inventory/__init__.py
async def connect_inventory(self) -> None:\n    \"\"\"Run `refresh()` coroutines for all AntaDevice objects in this inventory.\"\"\"\n    logger.debug(\"Refreshing devices...\")\n    results = await asyncio.gather(\n        *(device.refresh() for device in self.values()),\n        return_exceptions=True,\n    )\n    for r in results:\n        if isinstance(r, Exception):\n            message = \"Error when refreshing inventory\"\n            anta_log_exception(r, message, logger)\n
"},{"location":"api/inventory/#anta.inventory.AntaInventory.get_inventory","title":"get_inventory","text":"
get_inventory(*, established_only: bool = False, tags: set[str] | None = None, devices: set[str] | None = None) -> AntaInventory\n

Return a filtered inventory.

Returns:

Type Description An inventory with filtered AntaDevice objects. Source code in anta/inventory/__init__.py
def get_inventory(self, *, established_only: bool = False, tags: set[str] | None = None, devices: set[str] | None = None) -> AntaInventory:\n    \"\"\"Return a filtered inventory.\n\n    Parameters\n    ----------\n        established_only: Whether or not to include only established devices.\n        tags: Tags to filter devices.\n        devices: Names to filter devices.\n\n    Returns\n    -------\n        An inventory with filtered AntaDevice objects.\n    \"\"\"\n\n    def _filter_devices(device: AntaDevice) -> bool:\n        \"\"\"Select the devices based on the inputs `tags`, `devices` and `established_only`.\"\"\"\n        if tags is not None and all(tag not in tags for tag in device.tags):\n            return False\n        if devices is None or device.name in devices:\n            return bool(not established_only or device.established)\n        return False\n\n    filtered_devices: list[AntaDevice] = list(filter(_filter_devices, self.values()))\n    result = AntaInventory()\n    for device in filtered_devices:\n        result.add_device(device)\n    return result\n
"},{"location":"api/inventory/#anta.inventory.AntaInventory.parse","title":"parse staticmethod","text":"
parse(filename: str | Path, username: str, password: str, enable_password: str | None = None, timeout: float | None = None, *, enable: bool = False, insecure: bool = False, disable_cache: bool = False) -> AntaInventory\n

Create an AntaInventory instance from an inventory file.

The inventory devices are AsyncEOSDevice instances.

Raises:

Type Description InventoryRootKeyError: Root key of inventory is missing.

InventoryIncorrectSchemaError: Inventory file is not following AntaInventory Schema.

Source code in anta/inventory/__init__.py
@staticmethod\ndef parse(\n    filename: str | Path,\n    username: str,\n    password: str,\n    enable_password: str | None = None,\n    timeout: float | None = None,\n    *,\n    enable: bool = False,\n    insecure: bool = False,\n    disable_cache: bool = False,\n) -> AntaInventory:\n    \"\"\"Create an AntaInventory instance from an inventory file.\n\n    The inventory devices are AsyncEOSDevice instances.\n\n    Parameters\n    ----------\n        filename: Path to device inventory YAML file.\n        username: Username to use to connect to devices.\n        password: Password to use to connect to devices.\n        enable_password: Enable password to use if required.\n        timeout: Timeout value in seconds for outgoing API calls.\n        enable: Whether or not the commands need to be run in enable mode towards the devices.\n        insecure: Disable SSH Host Key validation.\n        disable_cache: Disable cache globally.\n\n    Raises\n    ------\n        InventoryRootKeyError: Root key of inventory is missing.\n        InventoryIncorrectSchemaError: Inventory file is not following AntaInventory Schema.\n\n    \"\"\"\n    inventory = AntaInventory()\n    kwargs: dict[str, Any] = {\n        \"username\": username,\n        \"password\": password,\n        \"enable\": enable,\n        \"enable_password\": enable_password,\n        \"timeout\": timeout,\n        \"insecure\": insecure,\n        \"disable_cache\": disable_cache,\n    }\n    if username is None:\n        message = \"'username' is required to create an AntaInventory\"\n        logger.error(message)\n        raise ValueError(message)\n    if password is None:\n        message = \"'password' is required to create an AntaInventory\"\n        logger.error(message)\n        raise ValueError(message)\n\n    try:\n        filename = Path(filename)\n        with filename.open(encoding=\"UTF-8\") as file:\n            data = safe_load(file)\n    except (TypeError, YAMLError, OSError) as e:\n        message = f\"Unable to parse ANTA Device Inventory file '{filename}'\"\n        anta_log_exception(e, message, logger)\n        raise\n\n    if AntaInventory.INVENTORY_ROOT_KEY not in data:\n        exc = InventoryRootKeyError(f\"Inventory root key ({AntaInventory.INVENTORY_ROOT_KEY}) is not defined in your inventory\")\n        anta_log_exception(exc, f\"Device inventory is invalid! (from {filename})\", logger)\n        raise exc\n\n    try:\n        inventory_input = AntaInventoryInput(**data[AntaInventory.INVENTORY_ROOT_KEY])\n    except ValidationError as e:\n        anta_log_exception(e, f\"Device inventory is invalid! (from {filename})\", logger)\n        raise\n\n    # Read data from input\n    AntaInventory._parse_hosts(inventory_input, inventory, **kwargs)\n    AntaInventory._parse_networks(inventory_input, inventory, **kwargs)\n    AntaInventory._parse_ranges(inventory_input, inventory, **kwargs)\n\n    return inventory\n
"},{"location":"api/inventory/#anta.inventory.exceptions","title":"exceptions","text":"

Manage Exception in Inventory module.

"},{"location":"api/inventory/#anta.inventory.exceptions.InventoryIncorrectSchemaError","title":"InventoryIncorrectSchemaError","text":"

Bases: Exception

Error when user data does not follow ANTA schema.

"},{"location":"api/inventory/#anta.inventory.exceptions.InventoryRootKeyError","title":"InventoryRootKeyError","text":"

Bases: Exception

Error raised when inventory root key is not found.

"},{"location":"api/inventory.models.input/","title":"Inventory models","text":""},{"location":"api/inventory.models.input/#anta.inventory.models.AntaInventoryInput","title":"AntaInventoryInput","text":"

Bases: BaseModel

Device inventory input model.

"},{"location":"api/inventory.models.input/#anta.inventory.models.AntaInventoryInput.yaml","title":"yaml","text":"
yaml() -> str\n

Return a YAML representation string of this model.

Returns:

Type Description The YAML representation string of this model. Source code in anta/inventory/models.py
def yaml(self) -> str:\n    \"\"\"Return a YAML representation string of this model.\n\n    Returns\n    -------\n        The YAML representation string of this model.\n    \"\"\"\n    # TODO: Pydantic and YAML serialization/deserialization is not supported natively.\n    # This could be improved.\n    # https://github.com/pydantic/pydantic/issues/1043\n    # Explore if this worth using this: https://github.com/NowanIlfideme/pydantic-yaml\n    return yaml.safe_dump(yaml.safe_load(self.model_dump_json(serialize_as_any=True, exclude_unset=True)), indent=2, width=math.inf)\n
"},{"location":"api/inventory.models.input/#anta.inventory.models.AntaInventoryHost","title":"AntaInventoryHost","text":"

Bases: BaseModel

Host entry of AntaInventoryInput.

Attributes:

Name Type Description host IP Address or FQDN of the device.

port: Custom eAPI port to use. name: Custom name of the device. tags: Tags of the device. disable_cache: Disable cache for this device.

"},{"location":"api/inventory.models.input/#anta.inventory.models.AntaInventoryNetwork","title":"AntaInventoryNetwork","text":"

Bases: BaseModel

Network entry of AntaInventoryInput.

Attributes:

Name Type Description network Subnet to use for scanning.

tags: Tags of the devices in this network. disable_cache: Disable cache for all devices in this network.

"},{"location":"api/inventory.models.input/#anta.inventory.models.AntaInventoryRange","title":"AntaInventoryRange","text":"

Bases: BaseModel

IP Range entry of AntaInventoryInput.

Attributes:

Name Type Description start IPv4 or IPv6 address for the beginning of the range.

stop: IPv4 or IPv6 address for the end of the range. tags: Tags of the devices in this IP range. disable_cache: Disable cache for all devices in this IP range.

"},{"location":"api/models/","title":"Test models","text":""},{"location":"api/models/#test-definition","title":"Test definition","text":""},{"location":"api/models/#uml-diagram","title":"UML Diagram","text":""},{"location":"api/models/#anta.models.AntaTest","title":"AntaTest","text":"
AntaTest(device: AntaDevice, inputs: dict[str, Any] | AntaTest.Input | None = None, eos_data: list[dict[Any, Any] | str] | None = None)\n

Bases: ABC

Abstract class defining a test in ANTA.

The goal of this class is to handle the heavy lifting and make writing a test as simple as possible.

Examples

The following is an example of an AntaTest subclass implementation:

    class VerifyReachability(AntaTest):\n        name = \"VerifyReachability\"\n        description = \"Test the network reachability to one or many destination IP(s).\"\n        categories = [\"connectivity\"]\n        commands = [AntaTemplate(template=\"ping vrf {vrf} {dst} source {src} repeat 2\")]\n\n        class Input(AntaTest.Input):\n            hosts: list[Host]\n            class Host(BaseModel):\n                dst: IPv4Address\n                src: IPv4Address\n                vrf: str = \"default\"\n\n        def render(self, template: AntaTemplate) -> list[AntaCommand]:\n            return [template.render(dst=host.dst, src=host.src, vrf=host.vrf) for host in self.inputs.hosts]\n\n        @AntaTest.anta_test\n        def test(self) -> None:\n            failures = []\n            for command in self.instance_commands:\n                src, dst = command.params.src, command.params.dst\n                if \"2 received\" not in command.json_output[\"messages\"][0]:\n                    failures.append((str(src), str(dst)))\n            if not failures:\n                self.result.is_success()\n            else:\n                self.result.is_failure(f\"Connectivity test failed for the following source-destination pairs: {failures}\")\n

Attributes:

Name Type Description device AntaDevice instance on which this test is run

inputs: AntaTest.Input instance carrying the test inputs instance_commands: List of AntaCommand instances of this test result: TestResult instance representing the result of this test logger: Python logger for this test instance

Source code in anta/models.py
def __init__(\n    self,\n    device: AntaDevice,\n    inputs: dict[str, Any] | AntaTest.Input | None = None,\n    eos_data: list[dict[Any, Any] | str] | None = None,\n) -> None:\n    \"\"\"AntaTest Constructor.\n\n    Parameters\n    ----------\n        device: AntaDevice instance on which the test will be run\n        inputs: dictionary of attributes used to instantiate the AntaTest.Input instance\n        eos_data: Populate outputs of the test commands instead of collecting from devices.\n                  This list must have the same length and order than the `instance_commands` instance attribute.\n    \"\"\"\n    self.logger: logging.Logger = logging.getLogger(f\"{self.module}.{self.__class__.__name__}\")\n    self.device: AntaDevice = device\n    self.inputs: AntaTest.Input\n    self.instance_commands: list[AntaCommand] = []\n    self.result: TestResult = TestResult(\n        name=device.name,\n        test=self.name,\n        categories=self.categories,\n        description=self.description,\n    )\n    self._init_inputs(inputs)\n    if self.result.result == \"unset\":\n        self._init_commands(eos_data)\n
"},{"location":"api/models/#anta.models.AntaTest.blocked","title":"blocked property","text":"
blocked: bool\n

Check if CLI commands contain a blocked keyword.

"},{"location":"api/models/#anta.models.AntaTest.collected","title":"collected property","text":"
collected: bool\n

Return True if all commands for this test have been collected.

"},{"location":"api/models/#anta.models.AntaTest.failed_commands","title":"failed_commands property","text":"
failed_commands: list[AntaCommand]\n

Return a list of all the commands that have failed.

"},{"location":"api/models/#anta.models.AntaTest.module","title":"module property","text":"
module: str\n

Return the Python module in which this AntaTest class is defined.

"},{"location":"api/models/#anta.models.AntaTest.Input","title":"Input","text":"

Bases: BaseModel

Class defining inputs for a test in ANTA.

Examples

A valid test catalog will look like the following:

<Python module>:\n- <AntaTest subclass>:\n    result_overwrite:\n        categories:\n        - \"Overwritten category 1\"\n        description: \"Test with overwritten description\"\n        custom_field: \"Test run by John Doe\"\n

Attributes:

Name Type Description result_overwrite Define fields to overwrite in the TestResult object"},{"location":"api/models/#anta.models.AntaTest.Input.Filters","title":"Filters","text":"

Bases: BaseModel

Runtime filters to map tests with list of tags or devices.

Attributes:

Name Type Description tags Tag of devices on which to run the test."},{"location":"api/models/#anta.models.AntaTest.Input.ResultOverwrite","title":"ResultOverwrite","text":"

Bases: BaseModel

Test inputs model to overwrite result fields.

Attributes:

Name Type Description description overwrite TestResult.description

categories: overwrite TestResult.categories custom_field: a free string that will be included in the TestResult object

"},{"location":"api/models/#anta.models.AntaTest.Input.__hash__","title":"__hash__","text":"
__hash__() -> int\n

Implement generic hashing for AntaTest.Input.

This will work in most cases but this does not consider 2 lists with different ordering as equal.

Source code in anta/models.py
def __hash__(self) -> int:\n    \"\"\"Implement generic hashing for AntaTest.Input.\n\n    This will work in most cases but this does not consider 2 lists with different ordering as equal.\n    \"\"\"\n    return hash(self.model_dump_json())\n
"},{"location":"api/models/#anta.models.AntaTest.anta_test","title":"anta_test staticmethod","text":"
anta_test(function: F) -> Callable[..., Coroutine[Any, Any, TestResult]]\n

Decorate the test() method in child classes.

This decorator implements (in this order):

  1. Instantiate the command outputs if eos_data is provided to the test() method
  2. Collect the commands from the device
  3. Run the test() method
  4. Catches any exception in test() user code and set the result instance attribute
Source code in anta/models.py
@staticmethod\ndef anta_test(function: F) -> Callable[..., Coroutine[Any, Any, TestResult]]:\n    \"\"\"Decorate the `test()` method in child classes.\n\n    This decorator implements (in this order):\n\n    1. Instantiate the command outputs if `eos_data` is provided to the `test()` method\n    2. Collect the commands from the device\n    3. Run the `test()` method\n    4. Catches any exception in `test()` user code and set the `result` instance attribute\n    \"\"\"\n\n    @wraps(function)\n    async def wrapper(\n        self: AntaTest,\n        eos_data: list[dict[Any, Any] | str] | None = None,\n        **kwargs: dict[str, Any],\n    ) -> TestResult:\n        \"\"\"Inner function for the anta_test decorator.\n\n        Parameters\n        ----------\n            self: The test instance.\n            eos_data: Populate outputs of the test commands instead of collecting from devices.\n                      This list must have the same length and order than the `instance_commands` instance attribute.\n            kwargs: Any keyword argument to pass to the test.\n\n        Returns\n        -------\n            result: TestResult instance attribute populated with error status if any\n\n        \"\"\"\n        if self.result.result != \"unset\":\n            return self.result\n\n        # Data\n        if eos_data is not None:\n            self.save_commands_data(eos_data)\n            self.logger.debug(\"Test %s initialized with input data %s\", self.name, eos_data)\n\n        # If some data is missing, try to collect\n        if not self.collected:\n            await self.collect()\n            if self.result.result != \"unset\":\n                AntaTest.update_progress()\n                return self.result\n\n            if cmds := self.failed_commands:\n                unsupported_commands = [f\"'{c.command}' is not supported on {self.device.hw_model}\" for c in cmds if not c.supported]\n                if unsupported_commands:\n                    msg = f\"Test {self.name} has been skipped because it is not supported on {self.device.hw_model}: {GITHUB_SUGGESTION}\"\n                    self.logger.warning(msg)\n                    self.result.is_skipped(\"\\n\".join(unsupported_commands))\n                else:\n                    self.result.is_error(message=\"\\n\".join([f\"{c.command} has failed: {', '.join(c.errors)}\" for c in cmds]))\n                AntaTest.update_progress()\n                return self.result\n\n        try:\n            function(self, **kwargs)\n        except Exception as e:  # pylint: disable=broad-exception-caught\n            # test() is user-defined code.\n            # We need to catch everything if we want the AntaTest object\n            # to live until the reporting\n            message = f\"Exception raised for test {self.name} (on device {self.device.name})\"\n            anta_log_exception(e, message, self.logger)\n            self.result.is_error(message=exc_to_str(e))\n\n        # TODO: find a correct way to time test execution\n        AntaTest.update_progress()\n        return self.result\n\n    return wrapper\n
"},{"location":"api/models/#anta.models.AntaTest.collect","title":"collect async","text":"
collect() -> None\n

Collect outputs of all commands of this test class from the device of this test instance.

Source code in anta/models.py
async def collect(self) -> None:\n    \"\"\"Collect outputs of all commands of this test class from the device of this test instance.\"\"\"\n    try:\n        if self.blocked is False:\n            await self.device.collect_commands(self.instance_commands, collection_id=self.name)\n    except Exception as e:  # pylint: disable=broad-exception-caught\n        # device._collect() is user-defined code.\n        # We need to catch everything if we want the AntaTest object\n        # to live until the reporting\n        message = f\"Exception raised while collecting commands for test {self.name} (on device {self.device.name})\"\n        anta_log_exception(e, message, self.logger)\n        self.result.is_error(message=exc_to_str(e))\n
"},{"location":"api/models/#anta.models.AntaTest.render","title":"render","text":"
render(template: AntaTemplate) -> list[AntaCommand]\n

Render an AntaTemplate instance of this AntaTest using the provided AntaTest.Input instance at self.inputs.

This is not an abstract method because it does not need to be implemented if there is no AntaTemplate for this test.

Source code in anta/models.py
def render(self, template: AntaTemplate) -> list[AntaCommand]:\n    \"\"\"Render an AntaTemplate instance of this AntaTest using the provided AntaTest.Input instance at self.inputs.\n\n    This is not an abstract method because it does not need to be implemented if there is\n    no AntaTemplate for this test.\n    \"\"\"\n    _ = template\n    msg = f\"AntaTemplate are provided but render() method has not been implemented for {self.module}.{self.__class__.__name__}\"\n    raise NotImplementedError(msg)\n
"},{"location":"api/models/#anta.models.AntaTest.save_commands_data","title":"save_commands_data","text":"
save_commands_data(eos_data: list[dict[str, Any] | str]) -> None\n

Populate output of all AntaCommand instances in instance_commands.

Source code in anta/models.py
def save_commands_data(self, eos_data: list[dict[str, Any] | str]) -> None:\n    \"\"\"Populate output of all AntaCommand instances in `instance_commands`.\"\"\"\n    if len(eos_data) > len(self.instance_commands):\n        self.result.is_error(message=\"Test initialization error: Trying to save more data than there are commands for the test\")\n        return\n    if len(eos_data) < len(self.instance_commands):\n        self.result.is_error(message=\"Test initialization error: Trying to save less data than there are commands for the test\")\n        return\n    for index, data in enumerate(eos_data or []):\n        self.instance_commands[index].output = data\n
"},{"location":"api/models/#anta.models.AntaTest.test","title":"test abstractmethod","text":"
test() -> Coroutine[Any, Any, TestResult]\n

Core of the test logic.

This is an abstractmethod that must be implemented by child classes. It must set the correct status of the result instance attribute with the appropriate outcome of the test.

Examples

It must be implemented using the AntaTest.anta_test decorator:

@AntaTest.anta_test\ndef test(self) -> None:\n    self.result.is_success()\n    for command in self.instance_commands:\n        if not self._test_command(command): # _test_command() is an arbitrary test logic\n            self.result.is_failure(\"Failure reason\")\n

Source code in anta/models.py
@abstractmethod\ndef test(self) -> Coroutine[Any, Any, TestResult]:\n    \"\"\"Core of the test logic.\n\n    This is an abstractmethod that must be implemented by child classes.\n    It must set the correct status of the `result` instance attribute with the appropriate outcome of the test.\n\n    Examples\n    --------\n    It must be implemented using the `AntaTest.anta_test` decorator:\n        ```python\n        @AntaTest.anta_test\n        def test(self) -> None:\n            self.result.is_success()\n            for command in self.instance_commands:\n                if not self._test_command(command): # _test_command() is an arbitrary test logic\n                    self.result.is_failure(\"Failure reason\")\n        ```\n\n    \"\"\"\n
"},{"location":"api/models/#command-definition","title":"Command definition","text":""},{"location":"api/models/#uml-diagram_1","title":"UML Diagram","text":"

Warning

CLI commands are protected to avoid execution of critical commands such as reload or write erase.

  • Reload command: ^reload\\s*\\w*
  • Configure mode: ^conf\\w*\\s*(terminal|session)*
  • Write: ^wr\\w*\\s*\\w+
"},{"location":"api/models/#anta.models.AntaCommand","title":"AntaCommand","text":"

Bases: BaseModel

Class to define a command.

Info

eAPI models are revisioned, this means that if a model is modified in a non-backwards compatible way, then its revision will be bumped up (revisions are numbers, default value is 1).

By default an eAPI request will return revision 1 of the model instance, this ensures that older management software will not suddenly stop working when a switch is upgraded. A revision applies to a particular CLI command whereas a version is global and is internally translated to a specific revision for each CLI command in the RPC.

Revision has precedence over version.

Attributes:

Name Type Description command Device command

version: eAPI version - valid values are 1 or \u201clatest\u201d. revision: eAPI revision of the command. Valid values are 1 to 99. Revision has precedence over version. ofmt: eAPI output - json or text. output: Output of the command. Only defined if there was no errors. template: AntaTemplate object used to render this command. errors: If the command execution fails, eAPI returns a list of strings detailing the error(s). params: Pydantic Model containing the variables values used to render the template. use_cache: Enable or disable caching for this AntaCommand if the AntaDevice supports it.

"},{"location":"api/models/#anta.models.AntaCommand.collected","title":"collected property","text":"
collected: bool\n

Return True if the command has been collected, False otherwise.

A command that has not been collected could have returned an error. See error property.

"},{"location":"api/models/#anta.models.AntaCommand.error","title":"error property","text":"
error: bool\n

Return True if the command returned an error, False otherwise.

"},{"location":"api/models/#anta.models.AntaCommand.json_output","title":"json_output property","text":"
json_output: dict[str, Any]\n

Get the command output as JSON.

"},{"location":"api/models/#anta.models.AntaCommand.requires_privileges","title":"requires_privileges property","text":"
requires_privileges: bool\n

Return True if the command requires privileged mode, False otherwise.

Raises:

Type Description RuntimeError

If the command has not been collected and has not returned an error. AntaDevice.collect() must be called before this property.

"},{"location":"api/models/#anta.models.AntaCommand.supported","title":"supported property","text":"
supported: bool\n

Return True if the command is supported on the device hardware platform, False otherwise.

Raises:

Type Description RuntimeError

If the command has not been collected and has not returned an error. AntaDevice.collect() must be called before this property.

"},{"location":"api/models/#anta.models.AntaCommand.text_output","title":"text_output property","text":"
text_output: str\n

Get the command output as a string.

"},{"location":"api/models/#anta.models.AntaCommand.uid","title":"uid property","text":"
uid: str\n

Generate a unique identifier for this command.

"},{"location":"api/models/#template-definition","title":"Template definition","text":""},{"location":"api/models/#uml-diagram_2","title":"UML Diagram","text":""},{"location":"api/models/#anta.models.AntaTemplate","title":"AntaTemplate","text":"
AntaTemplate(template: str, version: Literal[1, 'latest'] = 'latest', revision: Revision | None = None, ofmt: Literal['json', 'text'] = 'json', *, use_cache: bool = True)\n

Class to define a command template as Python f-string.

Can render a command from parameters.

Attributes:

Name Type Description template Python f-string. Example: 'show vlan {vlan_id}'

version: eAPI version - valid values are 1 or \u201clatest\u201d. revision: Revision of the command. Valid values are 1 to 99. Revision has precedence over version. ofmt: eAPI output - json or text. use_cache: Enable or disable caching for this AntaTemplate if the AntaDevice supports it.

Source code in anta/models.py
def __init__(  # noqa: PLR0913\n    self,\n    template: str,\n    version: Literal[1, \"latest\"] = \"latest\",\n    revision: Revision | None = None,\n    ofmt: Literal[\"json\", \"text\"] = \"json\",\n    *,\n    use_cache: bool = True,\n) -> None:\n    # pylint: disable=too-many-arguments\n    self.template = template\n    self.version = version\n    self.revision = revision\n    self.ofmt = ofmt\n    self.use_cache = use_cache\n\n    # Create a AntaTemplateParams model to elegantly store AntaTemplate variables\n    field_names = [fname for _, fname, _, _ in Formatter().parse(self.template) if fname]\n    # Extracting the type from the params based on the expected field_names from the template\n    fields: dict[str, Any] = {key: (Any, ...) for key in field_names}\n    self.params_schema = create_model(\n        \"AntaParams\",\n        __base__=AntaParamsBaseModel,\n        **fields,\n    )\n
"},{"location":"api/models/#anta.models.AntaTemplate.__repr__","title":"__repr__","text":"
__repr__() -> str\n

Return the representation of the class.

Copying pydantic model style, excluding params_schema

Source code in anta/models.py
def __repr__(self) -> str:\n    \"\"\"Return the representation of the class.\n\n    Copying pydantic model style, excluding `params_schema`\n    \"\"\"\n    return \" \".join(f\"{a}={v!r}\" for a, v in vars(self).items() if a != \"params_schema\")\n
"},{"location":"api/models/#anta.models.AntaTemplate.render","title":"render","text":"
render(**params: str | int | bool) -> AntaCommand\n

Render an AntaCommand from an AntaTemplate instance.

Keep the parameters used in the AntaTemplate instance.

Returns:

Type Description The rendered AntaCommand.

This AntaCommand instance have a template attribute that references this AntaTemplate instance.

Raises:

Type Description AntaTemplateRenderError

If a parameter is missing to render the AntaTemplate instance.

Source code in anta/models.py
def render(self, **params: str | int | bool) -> AntaCommand:\n    \"\"\"Render an AntaCommand from an AntaTemplate instance.\n\n    Keep the parameters used in the AntaTemplate instance.\n\n    Parameters\n    ----------\n        params: dictionary of variables with string values to render the Python f-string\n\n    Returns\n    -------\n        The rendered AntaCommand.\n        This AntaCommand instance have a template attribute that references this\n        AntaTemplate instance.\n\n    Raises\n    ------\n        AntaTemplateRenderError\n            If a parameter is missing to render the AntaTemplate instance.\n    \"\"\"\n    try:\n        command = self.template.format(**params)\n    except (KeyError, SyntaxError) as e:\n        raise AntaTemplateRenderError(self, e.args[0]) from e\n    return AntaCommand(\n        command=command,\n        ofmt=self.ofmt,\n        version=self.version,\n        revision=self.revision,\n        template=self,\n        params=self.params_schema(**params),\n        use_cache=self.use_cache,\n    )\n
"},{"location":"api/report_manager/","title":"Report Manager","text":""},{"location":"api/report_manager/#anta.reporter.ReportTable","title":"ReportTable","text":"

TableReport Generate a Table based on TestResult.

"},{"location":"api/report_manager/#anta.reporter.ReportTable.report_all","title":"report_all","text":"
report_all(manager: ResultManager, title: str = 'All tests results') -> Table\n

Create a table report with all tests for one or all devices.

Create table with full output: Host / Test / Status / Message

Returns:

Type Description A fully populated rich `Table` Source code in anta/reporter/__init__.py
def report_all(self, manager: ResultManager, title: str = \"All tests results\") -> Table:\n    \"\"\"Create a table report with all tests for one or all devices.\n\n    Create table with full output: Host / Test / Status / Message\n\n    Parameters\n    ----------\n        manager: A ResultManager instance.\n        title: Title for the report. Defaults to 'All tests results'.\n\n    Returns\n    -------\n        A fully populated rich `Table`\n\n    \"\"\"\n    table = Table(title=title, show_lines=True)\n    headers = [\"Device\", \"Test Name\", \"Test Status\", \"Message(s)\", \"Test description\", \"Test category\"]\n    table = self._build_headers(headers=headers, table=table)\n\n    def add_line(result: TestResult) -> None:\n        state = self._color_result(result.result)\n        message = self._split_list_to_txt_list(result.messages) if len(result.messages) > 0 else \"\"\n        categories = \", \".join(result.categories)\n        table.add_row(str(result.name), result.test, state, message, result.description, categories)\n\n    for result in manager.results:\n        add_line(result)\n    return table\n
"},{"location":"api/report_manager/#anta.reporter.ReportTable.report_summary_devices","title":"report_summary_devices","text":"
report_summary_devices(manager: ResultManager, devices: list[str] | None = None, title: str = 'Summary per device') -> Table\n

Create a table report with result aggregated per device.

Create table with full output: Host | Number of success | Number of failure | Number of error | List of nodes in error or failure

Returns:

Type Description A fully populated rich `Table`. Source code in anta/reporter/__init__.py
def report_summary_devices(\n    self,\n    manager: ResultManager,\n    devices: list[str] | None = None,\n    title: str = \"Summary per device\",\n) -> Table:\n    \"\"\"Create a table report with result aggregated per device.\n\n    Create table with full output: Host | Number of success | Number of failure | Number of error | List of nodes in error or failure\n\n    Parameters\n    ----------\n        manager: A ResultManager instance.\n        devices: List of device names to include. None to select all devices.\n        title: Title of the report.\n\n    Returns\n    -------\n        A fully populated rich `Table`.\n    \"\"\"\n    table = Table(title=title, show_lines=True)\n    headers = [\n        \"Device\",\n        \"# of success\",\n        \"# of skipped\",\n        \"# of failure\",\n        \"# of errors\",\n        \"List of failed or error test cases\",\n    ]\n    table = self._build_headers(headers=headers, table=table)\n    for device in manager.get_devices():\n        if devices is None or device in devices:\n            results = manager.filter_by_devices({device}).results\n            nb_failure = len([result for result in results if result.result == \"failure\"])\n            nb_error = len([result for result in results if result.result == \"error\"])\n            list_failure = [result.test for result in results if result.result in [\"failure\", \"error\"]]\n            nb_success = len([result for result in results if result.result == \"success\"])\n            nb_skipped = len([result for result in results if result.result == \"skipped\"])\n            table.add_row(\n                device,\n                str(nb_success),\n                str(nb_skipped),\n                str(nb_failure),\n                str(nb_error),\n                str(list_failure),\n            )\n    return table\n
"},{"location":"api/report_manager/#anta.reporter.ReportTable.report_summary_tests","title":"report_summary_tests","text":"
report_summary_tests(manager: ResultManager, tests: list[str] | None = None, title: str = 'Summary per test') -> Table\n

Create a table report with result aggregated per test.

Create table with full output: Test | Number of success | Number of failure | Number of error | List of nodes in error or failure

Returns:

Type Description A fully populated rich `Table`. Source code in anta/reporter/__init__.py
def report_summary_tests(\n    self,\n    manager: ResultManager,\n    tests: list[str] | None = None,\n    title: str = \"Summary per test\",\n) -> Table:\n    \"\"\"Create a table report with result aggregated per test.\n\n    Create table with full output: Test | Number of success | Number of failure | Number of error | List of nodes in error or failure\n\n    Parameters\n    ----------\n        manager: A ResultManager instance.\n        tests: List of test names to include. None to select all tests.\n        title: Title of the report.\n\n    Returns\n    -------\n        A fully populated rich `Table`.\n    \"\"\"\n    table = Table(title=title, show_lines=True)\n    headers = [\n        \"Test Case\",\n        \"# of success\",\n        \"# of skipped\",\n        \"# of failure\",\n        \"# of errors\",\n        \"List of failed or error nodes\",\n    ]\n    table = self._build_headers(headers=headers, table=table)\n    for test in manager.get_tests():\n        if tests is None or test in tests:\n            results = manager.filter_by_tests({test}).results\n            nb_failure = len([result for result in results if result.result == \"failure\"])\n            nb_error = len([result for result in results if result.result == \"error\"])\n            list_failure = [result.name for result in results if result.result in [\"failure\", \"error\"]]\n            nb_success = len([result for result in results if result.result == \"success\"])\n            nb_skipped = len([result for result in results if result.result == \"skipped\"])\n            table.add_row(\n                test,\n                str(nb_success),\n                str(nb_skipped),\n                str(nb_failure),\n                str(nb_error),\n                str(list_failure),\n            )\n    return table\n
"},{"location":"api/result_manager/","title":"Result Manager module","text":""},{"location":"api/result_manager/#result-manager-definition","title":"Result Manager definition","text":""},{"location":"api/result_manager/#uml-diagram","title":"UML Diagram","text":""},{"location":"api/result_manager/#anta.result_manager.ResultManager","title":"ResultManager","text":"
ResultManager()\n

Helper to manage Test Results and generate reports.

Examples
Create Inventory:\n\n    inventory_anta = AntaInventory.parse(\n        filename='examples/inventory.yml',\n        username='ansible',\n        password='ansible',\n    )\n\nCreate Result Manager:\n\n    manager = ResultManager()\n\nRun tests for all connected devices:\n\n    for device in inventory_anta.get_inventory().devices:\n        manager.add(\n            VerifyNTP(device=device).test()\n        )\n        manager.add(\n            VerifyEOSVersion(device=device).test(version='4.28.3M')\n        )\n\nPrint result in native format:\n\n    manager.results\n    [\n        TestResult(\n            name=\"pf1\",\n            test=\"VerifyZeroTouch\",\n            categories=[\"configuration\"],\n            description=\"Verifies ZeroTouch is disabled\",\n            result=\"success\",\n            messages=[],\n            custom_field=None,\n        ),\n        TestResult(\n            name=\"pf1\",\n            test='VerifyNTP',\n            categories=[\"software\"],\n            categories=['system'],\n            description='Verifies if NTP is synchronised.',\n            result='failure',\n            messages=[\"The device is not synchronized with the configured NTP server(s): 'NTP is disabled.'\"],\n            custom_field=None,\n        ),\n    ]\n

The status of the class is initialized to \u201cunset\u201d

Then when adding a test with a status that is NOT \u2018error\u2019 the following table shows the updated status:

Current Status Added test Status Updated Status unset Any Any skipped unset, skipped skipped skipped success success skipped failure failure success unset, skipped, success success success failure failure failure unset, skipped success, failure failure

If the status of the added test is error, the status is untouched and the error_status is set to True.

Source code in anta/result_manager/__init__.py
def __init__(self) -> None:\n    \"\"\"Class constructor.\n\n    The status of the class is initialized to \"unset\"\n\n    Then when adding a test with a status that is NOT 'error' the following\n    table shows the updated status:\n\n    | Current Status |         Added test Status       | Updated Status |\n    | -------------- | ------------------------------- | -------------- |\n    |      unset     |              Any                |       Any      |\n    |     skipped    |         unset, skipped          |     skipped    |\n    |     skipped    |            success              |     success    |\n    |     skipped    |            failure              |     failure    |\n    |     success    |     unset, skipped, success     |     success    |\n    |     success    |            failure              |     failure    |\n    |     failure    | unset, skipped success, failure |     failure    |\n\n    If the status of the added test is error, the status is untouched and the\n    error_status is set to True.\n    \"\"\"\n    self._result_entries: list[TestResult] = []\n    self.status: TestStatus = \"unset\"\n    self.error_status = False\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.json","title":"json property","text":"
json: str\n

Get a JSON representation of the results.

"},{"location":"api/result_manager/#anta.result_manager.ResultManager.results","title":"results property writable","text":"
results: list[TestResult]\n

Get the list of TestResult.

"},{"location":"api/result_manager/#anta.result_manager.ResultManager.add","title":"add","text":"
add(result: TestResult) -> None\n

Add a result to the ResultManager instance.

Source code in anta/result_manager/__init__.py
def add(self, result: TestResult) -> None:\n    \"\"\"Add a result to the ResultManager instance.\n\n    Parameters\n    ----------\n        result: TestResult to add to the ResultManager instance.\n    \"\"\"\n\n    def _update_status(test_status: TestStatus) -> None:\n        result_validator: TypeAdapter[TestStatus] = TypeAdapter(TestStatus)\n        result_validator.validate_python(test_status)\n        if test_status == \"error\":\n            self.error_status = True\n            return\n        if self.status == \"unset\" or self.status == \"skipped\" and test_status in {\"success\", \"failure\"}:\n            self.status = test_status\n        elif self.status == \"success\" and test_status == \"failure\":\n            self.status = \"failure\"\n\n    self._result_entries.append(result)\n    _update_status(result.result)\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.filter","title":"filter","text":"
filter(hide: set[TestStatus]) -> ResultManager\n

Get a filtered ResultManager based on test status.

Returns:

Type Description A filtered `ResultManager`. Source code in anta/result_manager/__init__.py
def filter(self, hide: set[TestStatus]) -> ResultManager:\n    \"\"\"Get a filtered ResultManager based on test status.\n\n    Parameters\n    ----------\n        hide: set of TestStatus literals to select tests to hide based on their status.\n\n    Returns\n    -------\n        A filtered `ResultManager`.\n    \"\"\"\n    manager = ResultManager()\n    manager.results = [test for test in self._result_entries if test.result not in hide]\n    return manager\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.filter_by_devices","title":"filter_by_devices","text":"
filter_by_devices(devices: set[str]) -> ResultManager\n

Get a filtered ResultManager that only contains specific devices.

Returns:

Type Description A filtered `ResultManager`. Source code in anta/result_manager/__init__.py
def filter_by_devices(self, devices: set[str]) -> ResultManager:\n    \"\"\"Get a filtered ResultManager that only contains specific devices.\n\n    Parameters\n    ----------\n        devices: Set of device names to filter the results.\n\n    Returns\n    -------\n        A filtered `ResultManager`.\n    \"\"\"\n    manager = ResultManager()\n    manager.results = [result for result in self._result_entries if result.name in devices]\n    return manager\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.filter_by_tests","title":"filter_by_tests","text":"
filter_by_tests(tests: set[str]) -> ResultManager\n

Get a filtered ResultManager that only contains specific tests.

Returns:

Type Description A filtered `ResultManager`. Source code in anta/result_manager/__init__.py
def filter_by_tests(self, tests: set[str]) -> ResultManager:\n    \"\"\"Get a filtered ResultManager that only contains specific tests.\n\n    Parameters\n    ----------\n        tests: Set of test names to filter the results.\n\n    Returns\n    -------\n        A filtered `ResultManager`.\n    \"\"\"\n    manager = ResultManager()\n    manager.results = [result for result in self._result_entries if result.test in tests]\n    return manager\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.get_devices","title":"get_devices","text":"
get_devices() -> set[str]\n

Get the set of all the device names.

Returns:

Type Description Set of device names. Source code in anta/result_manager/__init__.py
def get_devices(self) -> set[str]:\n    \"\"\"Get the set of all the device names.\n\n    Returns\n    -------\n        Set of device names.\n    \"\"\"\n    return {str(result.name) for result in self._result_entries}\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.get_status","title":"get_status","text":"
get_status(*, ignore_error: bool = False) -> str\n

Return the current status including error_status if ignore_error is False.

Source code in anta/result_manager/__init__.py
def get_status(self, *, ignore_error: bool = False) -> str:\n    \"\"\"Return the current status including error_status if ignore_error is False.\"\"\"\n    return \"error\" if self.error_status and not ignore_error else self.status\n
"},{"location":"api/result_manager/#anta.result_manager.ResultManager.get_tests","title":"get_tests","text":"
get_tests() -> set[str]\n

Get the set of all the test names.

Returns:

Type Description Set of test names. Source code in anta/result_manager/__init__.py
def get_tests(self) -> set[str]:\n    \"\"\"Get the set of all the test names.\n\n    Returns\n    -------\n        Set of test names.\n    \"\"\"\n    return {str(result.test) for result in self._result_entries}\n
"},{"location":"api/result_manager_models/","title":"Result Manager models","text":""},{"location":"api/result_manager_models/#test-result-model","title":"Test Result model","text":""},{"location":"api/result_manager_models/#uml-diagram","title":"UML Diagram","text":""},{"location":"api/result_manager_models/#anta.result_manager.models.TestResult","title":"TestResult","text":"

Bases: BaseModel

Describe the result of a test from a single device.

Attributes:

Name Type Description name Device name where the test has run.

test: Test name runs on the device. categories: List of categories the TestResult belongs to, by default the AntaTest categories. description: TestResult description, by default the AntaTest description. result: Result of the test. Can be one of \u201cunset\u201d, \u201csuccess\u201d, \u201cfailure\u201d, \u201cerror\u201d or \u201cskipped\u201d. messages: Message to report after the test if any. custom_field: Custom field to store a string for flexibility in integrating with ANTA

"},{"location":"api/result_manager_models/#anta.result_manager.models.TestResult.is_error","title":"is_error","text":"
is_error(message: str | None = None) -> None\n

Set status to error.

Source code in anta/result_manager/models.py
def is_error(self, message: str | None = None) -> None:\n    \"\"\"Set status to error.\n\n    Parameters\n    ----------\n        message: Optional message related to the test\n\n    \"\"\"\n    self._set_status(\"error\", message)\n
"},{"location":"api/result_manager_models/#anta.result_manager.models.TestResult.is_failure","title":"is_failure","text":"
is_failure(message: str | None = None) -> None\n

Set status to failure.

Source code in anta/result_manager/models.py
def is_failure(self, message: str | None = None) -> None:\n    \"\"\"Set status to failure.\n\n    Parameters\n    ----------\n        message: Optional message related to the test\n\n    \"\"\"\n    self._set_status(\"failure\", message)\n
"},{"location":"api/result_manager_models/#anta.result_manager.models.TestResult.is_skipped","title":"is_skipped","text":"
is_skipped(message: str | None = None) -> None\n

Set status to skipped.

Source code in anta/result_manager/models.py
def is_skipped(self, message: str | None = None) -> None:\n    \"\"\"Set status to skipped.\n\n    Parameters\n    ----------\n        message: Optional message related to the test\n\n    \"\"\"\n    self._set_status(\"skipped\", message)\n
"},{"location":"api/result_manager_models/#anta.result_manager.models.TestResult.is_success","title":"is_success","text":"
is_success(message: str | None = None) -> None\n

Set status to success.

Source code in anta/result_manager/models.py
def is_success(self, message: str | None = None) -> None:\n    \"\"\"Set status to success.\n\n    Parameters\n    ----------\n        message: Optional message related to the test\n\n    \"\"\"\n    self._set_status(\"success\", message)\n
"},{"location":"api/runner/","title":"Runner","text":""},{"location":"api/runner/#anta.runner","title":"runner","text":"

ANTA runner function.

"},{"location":"api/runner/#anta.runner.adjust_rlimit_nofile","title":"adjust_rlimit_nofile","text":"
adjust_rlimit_nofile() -> tuple[int, int]\n

Adjust the maximum number of open file descriptors for the ANTA process.

The limit is set to the lower of the current hard limit and the value of the ANTA_NOFILE environment variable.

If the ANTA_NOFILE environment variable is not set or is invalid, DEFAULT_NOFILE is used.

Returns:

Type Description tuple[int, int]: The new soft and hard limits for open file descriptors. Source code in anta/runner.py
def adjust_rlimit_nofile() -> tuple[int, int]:\n    \"\"\"Adjust the maximum number of open file descriptors for the ANTA process.\n\n    The limit is set to the lower of the current hard limit and the value of the ANTA_NOFILE environment variable.\n\n    If the `ANTA_NOFILE` environment variable is not set or is invalid, `DEFAULT_NOFILE` is used.\n\n    Returns\n    -------\n        tuple[int, int]: The new soft and hard limits for open file descriptors.\n    \"\"\"\n    try:\n        nofile = int(os.environ.get(\"ANTA_NOFILE\", DEFAULT_NOFILE))\n    except ValueError as exception:\n        logger.warning(\"The ANTA_NOFILE environment variable value is invalid: %s\\nDefault to %s.\", exc_to_str(exception), DEFAULT_NOFILE)\n        nofile = DEFAULT_NOFILE\n\n    limits = resource.getrlimit(resource.RLIMIT_NOFILE)\n    logger.debug(\"Initial limit numbers for open file descriptors for the current ANTA process: Soft Limit: %s | Hard Limit: %s\", limits[0], limits[1])\n    nofile = min(limits[1], nofile)\n    logger.debug(\"Setting soft limit for open file descriptors for the current ANTA process to %s\", nofile)\n    resource.setrlimit(resource.RLIMIT_NOFILE, (nofile, limits[1]))\n    return resource.getrlimit(resource.RLIMIT_NOFILE)\n
"},{"location":"api/runner/#anta.runner.get_coroutines","title":"get_coroutines","text":"
get_coroutines(selected_tests: defaultdict[AntaDevice, set[AntaTestDefinition]]) -> list[Coroutine[Any, Any, TestResult]]\n

Get the coroutines for the ANTA run.

Returns:

Type Description The list of coroutines to run. Source code in anta/runner.py
def get_coroutines(selected_tests: defaultdict[AntaDevice, set[AntaTestDefinition]]) -> list[Coroutine[Any, Any, TestResult]]:\n    \"\"\"Get the coroutines for the ANTA run.\n\n    Parameters\n    ----------\n        selected_tests: A mapping of devices to the tests to run. The selected tests are generated by the `prepare_tests` function.\n\n    Returns\n    -------\n        The list of coroutines to run.\n    \"\"\"\n    coros = []\n    for device, test_definitions in selected_tests.items():\n        for test in test_definitions:\n            try:\n                test_instance = test.test(device=device, inputs=test.inputs)\n                coros.append(test_instance.test())\n            except Exception as e:  # noqa: PERF203, pylint: disable=broad-exception-caught\n                # An AntaTest instance is potentially user-defined code.\n                # We need to catch everything and exit gracefully with an error message.\n                message = \"\\n\".join(\n                    [\n                        f\"There is an error when creating test {test.test.module}.{test.test.__name__}.\",\n                        f\"If this is not a custom test implementation: {GITHUB_SUGGESTION}\",\n                    ],\n                )\n                anta_log_exception(e, message, logger)\n    return coros\n
"},{"location":"api/runner/#anta.runner.log_cache_statistics","title":"log_cache_statistics","text":"
log_cache_statistics(devices: list[AntaDevice]) -> None\n

Log cache statistics for each device in the inventory.

Source code in anta/runner.py
def log_cache_statistics(devices: list[AntaDevice]) -> None:\n    \"\"\"Log cache statistics for each device in the inventory.\n\n    Parameters\n    ----------\n        devices: List of devices in the inventory.\n    \"\"\"\n    for device in devices:\n        if device.cache_statistics is not None:\n            msg = (\n                f\"Cache statistics for '{device.name}': \"\n                f\"{device.cache_statistics['cache_hits']} hits / {device.cache_statistics['total_commands_sent']} \"\n                f\"command(s) ({device.cache_statistics['cache_hit_ratio']})\"\n            )\n            logger.info(msg)\n        else:\n            logger.info(\"Caching is not enabled on %s\", device.name)\n
"},{"location":"api/runner/#anta.runner.main","title":"main async","text":"
main(manager: ResultManager, inventory: AntaInventory, catalog: AntaCatalog, devices: set[str] | None = None, tests: set[str] | None = None, tags: set[str] | None = None, *, established_only: bool = True, dry_run: bool = False) -> None\n

Run ANTA.

Use this as an entrypoint to the test framework in your script. ResultManager object gets updated with the test results.

Source code in anta/runner.py
@cprofile()\nasync def main(  # noqa: PLR0913\n    manager: ResultManager,\n    inventory: AntaInventory,\n    catalog: AntaCatalog,\n    devices: set[str] | None = None,\n    tests: set[str] | None = None,\n    tags: set[str] | None = None,\n    *,\n    established_only: bool = True,\n    dry_run: bool = False,\n) -> None:\n    # pylint: disable=too-many-arguments\n    \"\"\"Run ANTA.\n\n    Use this as an entrypoint to the test framework in your script.\n    ResultManager object gets updated with the test results.\n\n    Parameters\n    ----------\n        manager: ResultManager object to populate with the test results.\n        inventory: AntaInventory object that includes the device(s).\n        catalog: AntaCatalog object that includes the list of tests.\n        devices: Devices on which to run tests. None means all devices. These may come from the `--device / -d` CLI option in NRFU.\n        tests: Tests to run against devices. None means all tests. These may come from the `--test / -t` CLI option in NRFU.\n        tags: Tags to filter devices from the inventory. These may come from the `--tags` CLI option in NRFU.\n        established_only: Include only established device(s).\n        dry_run: Build the list of coroutine to run and stop before test execution.\n    \"\"\"\n    # Adjust the maximum number of open file descriptors for the ANTA process\n    limits = adjust_rlimit_nofile()\n\n    if not catalog.tests:\n        logger.info(\"The list of tests is empty, exiting\")\n        return\n\n    with Catchtime(logger=logger, message=\"Preparing ANTA NRFU Run\"):\n        # Setup the inventory\n        selected_inventory = inventory if dry_run else await setup_inventory(inventory, tags, devices, established_only=established_only)\n        if selected_inventory is None:\n            return\n\n        with Catchtime(logger=logger, message=\"Preparing the tests\"):\n            selected_tests = prepare_tests(selected_inventory, catalog, tests, tags)\n            if selected_tests is None:\n                return\n\n        run_info = (\n            \"--- ANTA NRFU Run Information ---\\n\"\n            f\"Number of devices: {len(inventory)} ({len(selected_inventory)} established)\\n\"\n            f\"Total number of selected tests: {catalog.final_tests_count}\\n\"\n            f\"Maximum number of open file descriptors for the current ANTA process: {limits[0]}\\n\"\n            \"---------------------------------\"\n        )\n\n        logger.info(run_info)\n\n        if catalog.final_tests_count > limits[0]:\n            logger.warning(\n                \"The number of concurrent tests is higher than the open file descriptors limit for this ANTA process.\\n\"\n                \"Errors may occur while running the tests.\\n\"\n                \"Please consult the ANTA FAQ.\"\n            )\n\n        coroutines = get_coroutines(selected_tests)\n\n    if dry_run:\n        logger.info(\"Dry-run mode, exiting before running the tests.\")\n        for coro in coroutines:\n            coro.close()\n        return\n\n    if AntaTest.progress is not None:\n        AntaTest.nrfu_task = AntaTest.progress.add_task(\"Running NRFU Tests...\", total=len(coroutines))\n\n    with Catchtime(logger=logger, message=\"Running ANTA tests\"):\n        test_results = await asyncio.gather(*coroutines)\n        for r in test_results:\n            manager.add(r)\n\n    log_cache_statistics(selected_inventory.devices)\n
"},{"location":"api/runner/#anta.runner.prepare_tests","title":"prepare_tests","text":"
prepare_tests(inventory: AntaInventory, catalog: AntaCatalog, tests: set[str] | None, tags: set[str] | None) -> defaultdict[AntaDevice, set[AntaTestDefinition]] | None\n

Prepare the tests to run.

Returns:

Type Description A mapping of devices to the tests to run or None if there are no tests to run. Source code in anta/runner.py
def prepare_tests(\n    inventory: AntaInventory, catalog: AntaCatalog, tests: set[str] | None, tags: set[str] | None\n) -> defaultdict[AntaDevice, set[AntaTestDefinition]] | None:\n    \"\"\"Prepare the tests to run.\n\n    Parameters\n    ----------\n        inventory: AntaInventory object that includes the device(s).\n        catalog: AntaCatalog object that includes the list of tests.\n        tests: Tests to run against devices. None means all tests.\n        tags: Tags to filter devices from the inventory.\n\n    Returns\n    -------\n        A mapping of devices to the tests to run or None if there are no tests to run.\n    \"\"\"\n    # Build indexes for the catalog. If `tests` is set, filter the indexes based on these tests\n    catalog.build_indexes(filtered_tests=tests)\n\n    # Using a set to avoid inserting duplicate tests\n    device_to_tests: defaultdict[AntaDevice, set[AntaTestDefinition]] = defaultdict(set)\n\n    # Create AntaTestRunner tuples from the tags\n    for device in inventory.devices:\n        if tags:\n            # If there are CLI tags, only execute tests with matching tags\n            device_to_tests[device].update(catalog.get_tests_by_tags(tags))\n        else:\n            # If there is no CLI tags, execute all tests that do not have any tags\n            device_to_tests[device].update(catalog.tag_to_tests[None])\n\n            # Then add the tests with matching tags from device tags\n            device_to_tests[device].update(catalog.get_tests_by_tags(device.tags))\n\n        catalog.final_tests_count += len(device_to_tests[device])\n\n    if catalog.final_tests_count == 0:\n        msg = (\n            f\"There are no tests{f' matching the tags {tags} ' if tags else ' '}to run in the current test catalog and device inventory, please verify your inputs.\"\n        )\n        logger.warning(msg)\n        return None\n\n    return device_to_tests\n
"},{"location":"api/runner/#anta.runner.setup_inventory","title":"setup_inventory async","text":"
setup_inventory(inventory: AntaInventory, tags: set[str] | None, devices: set[str] | None, *, established_only: bool) -> AntaInventory | None\n

Set up the inventory for the ANTA run.

Returns:

Type Description AntaInventory | None: The filtered inventory or None if there are no devices to run tests on. Source code in anta/runner.py
async def setup_inventory(inventory: AntaInventory, tags: set[str] | None, devices: set[str] | None, *, established_only: bool) -> AntaInventory | None:\n    \"\"\"Set up the inventory for the ANTA run.\n\n    Parameters\n    ----------\n        inventory: AntaInventory object that includes the device(s).\n        tags: Tags to filter devices from the inventory.\n        devices: Devices on which to run tests. None means all devices.\n\n    Returns\n    -------\n        AntaInventory | None: The filtered inventory or None if there are no devices to run tests on.\n    \"\"\"\n    if len(inventory) == 0:\n        logger.info(\"The inventory is empty, exiting\")\n        return None\n\n    # Filter the inventory based on the CLI provided tags and devices if any\n    selected_inventory = inventory.get_inventory(tags=tags, devices=devices) if tags or devices else inventory\n\n    with Catchtime(logger=logger, message=\"Connecting to devices\"):\n        # Connect to the devices\n        await selected_inventory.connect_inventory()\n\n    # Remove devices that are unreachable\n    selected_inventory = selected_inventory.get_inventory(established_only=established_only)\n\n    # If there are no devices in the inventory after filtering, exit\n    if not selected_inventory.devices:\n        msg = f'No reachable device {f\"matching the tags {tags} \" if tags else \"\"}was found.{f\" Selected devices: {devices} \" if devices is not None else \"\"}'\n        logger.warning(msg)\n        return None\n\n    return selected_inventory\n
"},{"location":"api/tests.aaa/","title":"AAA","text":""},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAcctConsoleMethods","title":"VerifyAcctConsoleMethods","text":"

Verifies the AAA accounting console method lists for different accounting types (system, exec, commands, dot1x).

Expected Results
  • Success: The test will pass if the provided AAA accounting console method list is matching in the configured accounting types.
  • Failure: The test will fail if the provided AAA accounting console method list is NOT matching in the configured accounting types.
Examples
anta.tests.aaa:\n  - VerifyAcctConsoleMethods:\n      methods:\n        - local\n        - none\n        - logging\n      types:\n        - system\n        - exec\n        - commands\n        - dot1x\n
Source code in anta/tests/aaa.py
class VerifyAcctConsoleMethods(AntaTest):\n    \"\"\"Verifies the AAA accounting console method lists for different accounting types (system, exec, commands, dot1x).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided AAA accounting console method list is matching in the configured accounting types.\n    * Failure: The test will fail if the provided AAA accounting console method list is NOT matching in the configured accounting types.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyAcctConsoleMethods:\n          methods:\n            - local\n            - none\n            - logging\n          types:\n            - system\n            - exec\n            - commands\n            - dot1x\n    ```\n    \"\"\"\n\n    name = \"VerifyAcctConsoleMethods\"\n    description = \"Verifies the AAA accounting console method lists for different accounting types (system, exec, commands, dot1x).\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show aaa methods accounting\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAcctConsoleMethods test.\"\"\"\n\n        methods: list[AAAAuthMethod]\n        \"\"\"List of AAA accounting console methods. Methods should be in the right order.\"\"\"\n        types: set[Literal[\"commands\", \"exec\", \"system\", \"dot1x\"]]\n        \"\"\"List of accounting console types to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAcctConsoleMethods.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        not_matching = []\n        not_configured = []\n        for k, v in command_output.items():\n            acct_type = k.replace(\"AcctMethods\", \"\")\n            if acct_type not in self.inputs.types:\n                # We do not need to verify this accounting type\n                continue\n            for methods in v.values():\n                if \"consoleAction\" not in methods:\n                    not_configured.append(acct_type)\n                if methods[\"consoleMethods\"] != self.inputs.methods:\n                    not_matching.append(acct_type)\n        if not_configured:\n            self.result.is_failure(f\"AAA console accounting is not configured for {not_configured}\")\n            return\n        if not not_matching:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"AAA accounting console methods {self.inputs.methods} are not matching for {not_matching}\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAcctConsoleMethods-attributes","title":"Inputs","text":"Name Type Description Default methods list[AAAAuthMethod] List of AAA accounting console methods. Methods should be in the right order. - types set[Literal['commands', 'exec', 'system', 'dot1x']] List of accounting console types to verify. -"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAcctDefaultMethods","title":"VerifyAcctDefaultMethods","text":"

Verifies the AAA accounting default method lists for different accounting types (system, exec, commands, dot1x).

Expected Results
  • Success: The test will pass if the provided AAA accounting default method list is matching in the configured accounting types.
  • Failure: The test will fail if the provided AAA accounting default method list is NOT matching in the configured accounting types.
Examples
anta.tests.aaa:\n  - VerifyAcctDefaultMethods:\n      methods:\n        - local\n        - none\n        - logging\n      types:\n        - system\n        - exec\n        - commands\n        - dot1x\n
Source code in anta/tests/aaa.py
class VerifyAcctDefaultMethods(AntaTest):\n    \"\"\"Verifies the AAA accounting default method lists for different accounting types (system, exec, commands, dot1x).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided AAA accounting default method list is matching in the configured accounting types.\n    * Failure: The test will fail if the provided AAA accounting default method list is NOT matching in the configured accounting types.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyAcctDefaultMethods:\n          methods:\n            - local\n            - none\n            - logging\n          types:\n            - system\n            - exec\n            - commands\n            - dot1x\n    ```\n    \"\"\"\n\n    name = \"VerifyAcctDefaultMethods\"\n    description = \"Verifies the AAA accounting default method lists for different accounting types (system, exec, commands, dot1x).\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show aaa methods accounting\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAcctDefaultMethods test.\"\"\"\n\n        methods: list[AAAAuthMethod]\n        \"\"\"List of AAA accounting methods. Methods should be in the right order.\"\"\"\n        types: set[Literal[\"commands\", \"exec\", \"system\", \"dot1x\"]]\n        \"\"\"List of accounting types to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAcctDefaultMethods.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        not_matching = []\n        not_configured = []\n        for k, v in command_output.items():\n            acct_type = k.replace(\"AcctMethods\", \"\")\n            if acct_type not in self.inputs.types:\n                # We do not need to verify this accounting type\n                continue\n            for methods in v.values():\n                if \"defaultAction\" not in methods:\n                    not_configured.append(acct_type)\n                if methods[\"defaultMethods\"] != self.inputs.methods:\n                    not_matching.append(acct_type)\n        if not_configured:\n            self.result.is_failure(f\"AAA default accounting is not configured for {not_configured}\")\n            return\n        if not not_matching:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"AAA accounting default methods {self.inputs.methods} are not matching for {not_matching}\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAcctDefaultMethods-attributes","title":"Inputs","text":"Name Type Description Default methods list[AAAAuthMethod] List of AAA accounting methods. Methods should be in the right order. - types set[Literal['commands', 'exec', 'system', 'dot1x']] List of accounting types to verify. -"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAuthenMethods","title":"VerifyAuthenMethods","text":"

Verifies the AAA authentication method lists for different authentication types (login, enable, dot1x).

Expected Results
  • Success: The test will pass if the provided AAA authentication method list is matching in the configured authentication types.
  • Failure: The test will fail if the provided AAA authentication method list is NOT matching in the configured authentication types.
Examples
anta.tests.aaa:\n  - VerifyAuthenMethods:\n    methods:\n      - local\n      - none\n      - logging\n    types:\n      - login\n      - enable\n      - dot1x\n
Source code in anta/tests/aaa.py
class VerifyAuthenMethods(AntaTest):\n    \"\"\"Verifies the AAA authentication method lists for different authentication types (login, enable, dot1x).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided AAA authentication method list is matching in the configured authentication types.\n    * Failure: The test will fail if the provided AAA authentication method list is NOT matching in the configured authentication types.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyAuthenMethods:\n        methods:\n          - local\n          - none\n          - logging\n        types:\n          - login\n          - enable\n          - dot1x\n    ```\n    \"\"\"\n\n    name = \"VerifyAuthenMethods\"\n    description = \"Verifies the AAA authentication method lists for different authentication types (login, enable, dot1x).\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show aaa methods authentication\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAuthenMethods test.\"\"\"\n\n        methods: list[AAAAuthMethod]\n        \"\"\"List of AAA authentication methods. Methods should be in the right order.\"\"\"\n        types: set[Literal[\"login\", \"enable\", \"dot1x\"]]\n        \"\"\"List of authentication types to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAuthenMethods.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        not_matching: list[str] = []\n        for k, v in command_output.items():\n            auth_type = k.replace(\"AuthenMethods\", \"\")\n            if auth_type not in self.inputs.types:\n                # We do not need to verify this accounting type\n                continue\n            if auth_type == \"login\":\n                if \"login\" not in v:\n                    self.result.is_failure(\"AAA authentication methods are not configured for login console\")\n                    return\n                if v[\"login\"][\"methods\"] != self.inputs.methods:\n                    self.result.is_failure(f\"AAA authentication methods {self.inputs.methods} are not matching for login console\")\n                    return\n            not_matching.extend(auth_type for methods in v.values() if methods[\"methods\"] != self.inputs.methods)\n\n        if not not_matching:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"AAA authentication methods {self.inputs.methods} are not matching for {not_matching}\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAuthenMethods-attributes","title":"Inputs","text":"Name Type Description Default methods list[AAAAuthMethod] List of AAA authentication methods. Methods should be in the right order. - types set[Literal['login', 'enable', 'dot1x']] List of authentication types to verify. -"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAuthzMethods","title":"VerifyAuthzMethods","text":"

Verifies the AAA authorization method lists for different authorization types (commands, exec).

Expected Results
  • Success: The test will pass if the provided AAA authorization method list is matching in the configured authorization types.
  • Failure: The test will fail if the provided AAA authorization method list is NOT matching in the configured authorization types.
Examples
anta.tests.aaa:\n  - VerifyAuthzMethods:\n      methods:\n        - local\n        - none\n        - logging\n      types:\n        - commands\n        - exec\n
Source code in anta/tests/aaa.py
class VerifyAuthzMethods(AntaTest):\n    \"\"\"Verifies the AAA authorization method lists for different authorization types (commands, exec).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided AAA authorization method list is matching in the configured authorization types.\n    * Failure: The test will fail if the provided AAA authorization method list is NOT matching in the configured authorization types.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyAuthzMethods:\n          methods:\n            - local\n            - none\n            - logging\n          types:\n            - commands\n            - exec\n    ```\n    \"\"\"\n\n    name = \"VerifyAuthzMethods\"\n    description = \"Verifies the AAA authorization method lists for different authorization types (commands, exec).\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show aaa methods authorization\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAuthzMethods test.\"\"\"\n\n        methods: list[AAAAuthMethod]\n        \"\"\"List of AAA authorization methods. Methods should be in the right order.\"\"\"\n        types: set[Literal[\"commands\", \"exec\"]]\n        \"\"\"List of authorization types to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAuthzMethods.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        not_matching: list[str] = []\n        for k, v in command_output.items():\n            authz_type = k.replace(\"AuthzMethods\", \"\")\n            if authz_type not in self.inputs.types:\n                # We do not need to verify this accounting type\n                continue\n            not_matching.extend(authz_type for methods in v.values() if methods[\"methods\"] != self.inputs.methods)\n\n        if not not_matching:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"AAA authorization methods {self.inputs.methods} are not matching for {not_matching}\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyAuthzMethods-attributes","title":"Inputs","text":"Name Type Description Default methods list[AAAAuthMethod] List of AAA authorization methods. Methods should be in the right order. - types set[Literal['commands', 'exec']] List of authorization types to verify. -"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyTacacsServerGroups","title":"VerifyTacacsServerGroups","text":"

Verifies if the provided TACACS server group(s) are configured.

Expected Results
  • Success: The test will pass if the provided TACACS server group(s) are configured.
  • Failure: The test will fail if one or all the provided TACACS server group(s) are NOT configured.
Examples
anta.tests.aaa:\n  - VerifyTacacsServerGroups:\n      groups:\n        - TACACS-GROUP1\n        - TACACS-GROUP2\n
Source code in anta/tests/aaa.py
class VerifyTacacsServerGroups(AntaTest):\n    \"\"\"Verifies if the provided TACACS server group(s) are configured.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided TACACS server group(s) are configured.\n    * Failure: The test will fail if one or all the provided TACACS server group(s) are NOT configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyTacacsServerGroups:\n          groups:\n            - TACACS-GROUP1\n            - TACACS-GROUP2\n    ```\n    \"\"\"\n\n    name = \"VerifyTacacsServerGroups\"\n    description = \"Verifies if the provided TACACS server group(s) are configured.\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show tacacs\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyTacacsServerGroups test.\"\"\"\n\n        groups: list[str]\n        \"\"\"List of TACACS server groups.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTacacsServerGroups.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        tacacs_groups = command_output[\"groups\"]\n        if not tacacs_groups:\n            self.result.is_failure(\"No TACACS server group(s) are configured\")\n            return\n        not_configured = [group for group in self.inputs.groups if group not in tacacs_groups]\n        if not not_configured:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"TACACS server group(s) {not_configured} are not configured\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyTacacsServerGroups-attributes","title":"Inputs","text":"Name Type Description Default groups list[str] List of TACACS server groups. -"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyTacacsServers","title":"VerifyTacacsServers","text":"

Verifies TACACS servers are configured for a specified VRF.

Expected Results
  • Success: The test will pass if the provided TACACS servers are configured in the specified VRF.
  • Failure: The test will fail if the provided TACACS servers are NOT configured in the specified VRF.
Examples
anta.tests.aaa:\n  - VerifyTacacsServers:\n      servers:\n        - 10.10.10.21\n        - 10.10.10.22\n      vrf: MGMT\n
Source code in anta/tests/aaa.py
class VerifyTacacsServers(AntaTest):\n    \"\"\"Verifies TACACS servers are configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided TACACS servers are configured in the specified VRF.\n    * Failure: The test will fail if the provided TACACS servers are NOT configured in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyTacacsServers:\n          servers:\n            - 10.10.10.21\n            - 10.10.10.22\n          vrf: MGMT\n    ```\n    \"\"\"\n\n    name = \"VerifyTacacsServers\"\n    description = \"Verifies TACACS servers are configured for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show tacacs\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyTacacsServers test.\"\"\"\n\n        servers: list[IPv4Address]\n        \"\"\"List of TACACS servers.\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF to transport TACACS messages. Defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTacacsServers.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        tacacs_servers = command_output[\"tacacsServers\"]\n        if not tacacs_servers:\n            self.result.is_failure(\"No TACACS servers are configured\")\n            return\n        not_configured = [\n            str(server)\n            for server in self.inputs.servers\n            if not any(\n                str(server) == tacacs_server[\"serverInfo\"][\"hostname\"] and self.inputs.vrf == tacacs_server[\"serverInfo\"][\"vrf\"] for tacacs_server in tacacs_servers\n            )\n        ]\n        if not not_configured:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"TACACS servers {not_configured} are not configured in VRF {self.inputs.vrf}\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyTacacsServers-attributes","title":"Inputs","text":"Name Type Description Default servers list[IPv4Address] List of TACACS servers. - vrf str The name of the VRF to transport TACACS messages. Defaults to `default`. 'default'"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyTacacsSourceIntf","title":"VerifyTacacsSourceIntf","text":"

Verifies TACACS source-interface for a specified VRF.

Expected Results
  • Success: The test will pass if the provided TACACS source-interface is configured in the specified VRF.
  • Failure: The test will fail if the provided TACACS source-interface is NOT configured in the specified VRF.
Examples
anta.tests.aaa:\n  - VerifyTacacsSourceIntf:\n      intf: Management0\n      vrf: MGMT\n
Source code in anta/tests/aaa.py
class VerifyTacacsSourceIntf(AntaTest):\n    \"\"\"Verifies TACACS source-interface for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided TACACS source-interface is configured in the specified VRF.\n    * Failure: The test will fail if the provided TACACS source-interface is NOT configured in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.aaa:\n      - VerifyTacacsSourceIntf:\n          intf: Management0\n          vrf: MGMT\n    ```\n    \"\"\"\n\n    name = \"VerifyTacacsSourceIntf\"\n    description = \"Verifies TACACS source-interface for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"aaa\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show tacacs\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyTacacsSourceIntf test.\"\"\"\n\n        intf: str\n        \"\"\"Source-interface to use as source IP of TACACS messages.\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF to transport TACACS messages. Defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTacacsSourceIntf.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        try:\n            if command_output[\"srcIntf\"][self.inputs.vrf] == self.inputs.intf:\n                self.result.is_success()\n            else:\n                self.result.is_failure(f\"Wrong source-interface configured in VRF {self.inputs.vrf}\")\n        except KeyError:\n            self.result.is_failure(f\"Source-interface {self.inputs.intf} is not configured in VRF {self.inputs.vrf}\")\n
"},{"location":"api/tests.aaa/#anta.tests.aaa.VerifyTacacsSourceIntf-attributes","title":"Inputs","text":"Name Type Description Default intf str Source-interface to use as source IP of TACACS messages. - vrf str The name of the VRF to transport TACACS messages. Defaults to `default`. 'default'"},{"location":"api/tests.avt/","title":"Adaptive Virtual Topology","text":""},{"location":"api/tests.avt/#anta.tests.avt.VerifyAVTPathHealth","title":"VerifyAVTPathHealth","text":"

Verifies the status of all Adaptive Virtual Topology (AVT) paths for all VRFs.

Expected Results
  • Success: The test will pass if all AVT paths for all VRFs are active and valid.
  • Failure: The test will fail if the AVT path is not configured or if any AVT path under any VRF is either inactive or invalid.
Examples
anta.tests.avt:\n  - VerifyAVTPathHealth:\n
Source code in anta/tests/avt.py
class VerifyAVTPathHealth(AntaTest):\n    \"\"\"\n    Verifies the status of all Adaptive Virtual Topology (AVT) paths for all VRFs.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all AVT paths for all VRFs are active and valid.\n    * Failure: The test will fail if the AVT path is not configured or if any AVT path under any VRF is either inactive or invalid.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.avt:\n      - VerifyAVTPathHealth:\n    ```\n    \"\"\"\n\n    name = \"VerifyAVTPathHealth\"\n    description = \"Verifies the status of all AVT paths for all VRFs.\"\n    categories: ClassVar[list[str]] = [\"avt\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show adaptive-virtual-topology path\")]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAVTPathHealth.\"\"\"\n        # Initialize the test result as success\n        self.result.is_success()\n\n        # Get the command output\n        command_output = self.instance_commands[0].json_output.get(\"vrfs\", {})\n\n        # Check if AVT is configured\n        if not command_output:\n            self.result.is_failure(\"Adaptive virtual topology paths are not configured.\")\n            return\n\n        # Iterate over each VRF\n        for vrf, vrf_data in command_output.items():\n            # Iterate over each AVT path\n            for profile, avt_path in vrf_data.get(\"avts\", {}).items():\n                for path, flags in avt_path.get(\"avtPaths\", {}).items():\n                    # Get the status of the AVT path\n                    valid = flags[\"flags\"][\"valid\"]\n                    active = flags[\"flags\"][\"active\"]\n\n                    # Check the status of the AVT path\n                    if not valid and not active:\n                        self.result.is_failure(f\"AVT path {path} for profile {profile} in VRF {vrf} is invalid and not active.\")\n                    elif not valid:\n                        self.result.is_failure(f\"AVT path {path} for profile {profile} in VRF {vrf} is invalid.\")\n                    elif not active:\n                        self.result.is_failure(f\"AVT path {path} for profile {profile} in VRF {vrf} is not active.\")\n
"},{"location":"api/tests.avt/#anta.tests.avt.VerifyAVTRole","title":"VerifyAVTRole","text":"

Verifies the Adaptive Virtual Topology (AVT) role of a device.

Expected Results
  • Success: The test will pass if the AVT role of the device matches the expected role.
  • Failure: The test will fail if the AVT is not configured or if the AVT role does not match the expected role.
Examples
anta.tests.avt:\n  - VerifyAVTRole:\n      role: edge\n
Source code in anta/tests/avt.py
class VerifyAVTRole(AntaTest):\n    \"\"\"\n    Verifies the Adaptive Virtual Topology (AVT) role of a device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the AVT role of the device matches the expected role.\n    * Failure: The test will fail if the AVT is not configured or if the AVT role does not match the expected role.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.avt:\n      - VerifyAVTRole:\n          role: edge\n    ```\n    \"\"\"\n\n    name = \"VerifyAVTRole\"\n    description = \"Verifies the AVT role of a device.\"\n    categories: ClassVar[list[str]] = [\"avt\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show adaptive-virtual-topology path\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAVTRole test.\"\"\"\n\n        role: str\n        \"\"\"Expected AVT role of the device.\"\"\"\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAVTRole.\"\"\"\n        # Initialize the test result as success\n        self.result.is_success()\n\n        # Get the command output\n        command_output = self.instance_commands[0].json_output\n\n        # Check if the AVT role matches the expected role\n        if self.inputs.role != command_output.get(\"role\"):\n            self.result.is_failure(f\"Expected AVT role as `{self.inputs.role}`, but found `{command_output.get('role')}` instead.\")\n
"},{"location":"api/tests.avt/#anta.tests.avt.VerifyAVTRole-attributes","title":"Inputs","text":"Name Type Description Default role str Expected AVT role of the device. -"},{"location":"api/tests.avt/#anta.tests.avt.VerifyAVTSpecificPath","title":"VerifyAVTSpecificPath","text":"

Verifies the status and type of an Adaptive Virtual Topology (AVT) path for a specified VRF.

Expected Results
  • Success: The test will pass if all AVT paths for the specified VRF are active, valid, and match the specified type (direct/multihop) if provided. If multiple paths are configured, the test will pass only if all the paths are valid and active.
  • Failure: The test will fail if no AVT paths are configured for the specified VRF, or if any configured path is not active, valid, or does not match the specified type.
Examples
anta.tests.avt:\n  - VerifyAVTSpecificPath:\n      avt_paths:\n        - avt_name: CONTROL-PLANE-PROFILE\n          vrf: default\n          destination: 10.101.255.2\n          next_hop: 10.101.255.1\n          path_type: direct\n
Source code in anta/tests/avt.py
class VerifyAVTSpecificPath(AntaTest):\n    \"\"\"\n    Verifies the status and type of an Adaptive Virtual Topology (AVT) path for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all AVT paths for the specified VRF are active, valid, and match the specified type (direct/multihop) if provided.\n               If multiple paths are configured, the test will pass only if all the paths are valid and active.\n    * Failure: The test will fail if no AVT paths are configured for the specified VRF, or if any configured path is not active, valid,\n               or does not match the specified type.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.avt:\n      - VerifyAVTSpecificPath:\n          avt_paths:\n            - avt_name: CONTROL-PLANE-PROFILE\n              vrf: default\n              destination: 10.101.255.2\n              next_hop: 10.101.255.1\n              path_type: direct\n    ```\n    \"\"\"\n\n    name = \"VerifyAVTSpecificPath\"\n    description = \"Verifies the status and type of an AVT path for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"avt\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaTemplate(template=\"show adaptive-virtual-topology path vrf {vrf} avt {avt_name} destination {destination}\")\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAVTSpecificPath test.\"\"\"\n\n        avt_paths: list[AVTPaths]\n        \"\"\"List of AVT paths to verify.\"\"\"\n\n        class AVTPaths(BaseModel):\n            \"\"\"Model for the details of AVT paths.\"\"\"\n\n            vrf: str = \"default\"\n            \"\"\"The VRF for the AVT path. Defaults to 'default' if not provided.\"\"\"\n            avt_name: str\n            \"\"\"Name of the adaptive virtual topology.\"\"\"\n            destination: IPv4Address\n            \"\"\"The IPv4 address of the AVT peer.\"\"\"\n            next_hop: IPv4Address\n            \"\"\"The IPv4 address of the next hop for the AVT peer.\"\"\"\n            path_type: str | None = None\n            \"\"\"The type of the AVT path. If not provided, both 'direct' and 'multihop' paths are considered.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each input AVT path/peer.\"\"\"\n        return [template.render(vrf=path.vrf, avt_name=path.avt_name, destination=path.destination) for path in self.inputs.avt_paths]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAVTSpecificPath.\"\"\"\n        # Assume the test is successful until a failure is detected\n        self.result.is_success()\n\n        # Process each command in the instance\n        for command, input_avt in zip(self.instance_commands, self.inputs.avt_paths):\n            # Extract the command output and parameters\n            vrf = command.params.vrf\n            avt_name = command.params.avt_name\n            peer = str(command.params.destination)\n\n            command_output = command.json_output.get(\"vrfs\", {})\n\n            # If no AVT is configured, mark the test as failed and skip to the next command\n            if not command_output:\n                self.result.is_failure(f\"AVT configuration for peer '{peer}' under topology '{avt_name}' in VRF '{vrf}' is not found.\")\n                continue\n\n            # Extract the AVT paths\n            avt_paths = get_value(command_output, f\"{vrf}.avts.{avt_name}.avtPaths\")\n            next_hop, input_path_type = str(input_avt.next_hop), input_avt.path_type\n\n            nexthop_path_found = path_type_found = False\n\n            # Check each AVT path\n            for path, path_data in avt_paths.items():\n                # If the path does not match the expected next hop, skip to the next path\n                if path_data.get(\"nexthopAddr\") != next_hop:\n                    continue\n\n                nexthop_path_found = True\n                path_type = \"direct\" if get_value(path_data, \"flags.directPath\") else \"multihop\"\n\n                # If the path type does not match the expected path type, skip to the next path\n                if input_path_type and path_type != input_path_type:\n                    continue\n\n                path_type_found = True\n                valid = get_value(path_data, \"flags.valid\")\n                active = get_value(path_data, \"flags.active\")\n\n                # Check the path status and type against the expected values\n                if not all([valid, active]):\n                    failure_reasons = []\n                    if not get_value(path_data, \"flags.active\"):\n                        failure_reasons.append(\"inactive\")\n                    if not get_value(path_data, \"flags.valid\"):\n                        failure_reasons.append(\"invalid\")\n                    # Construct the failure message prefix\n                    failed_log = f\"AVT path '{path}' for topology '{avt_name}' in VRF '{vrf}'\"\n                    self.result.is_failure(f\"{failed_log} is {', '.join(failure_reasons)}.\")\n\n            # If no matching next hop or path type was found, mark the test as failed\n            if not nexthop_path_found or not path_type_found:\n                self.result.is_failure(\n                    f\"No '{input_path_type}' path found with next-hop address '{next_hop}' for AVT peer '{peer}' under topology '{avt_name}' in VRF '{vrf}'.\"\n                )\n
"},{"location":"api/tests.avt/#anta.tests.avt.VerifyAVTSpecificPath-attributes","title":"Inputs","text":"Name Type Description Default avt_paths list[AVTPaths] List of AVT paths to verify. -"},{"location":"api/tests.avt/#anta.tests.avt.VerifyAVTSpecificPath-attributes","title":"AVTPaths","text":"Name Type Description Default vrf str The VRF for the AVT path. Defaults to 'default' if not provided. 'default' avt_name str Name of the adaptive virtual topology. - destination IPv4Address The IPv4 address of the AVT peer. - next_hop IPv4Address The IPv4 address of the next hop for the AVT peer. - path_type str | None The type of the AVT path. If not provided, both 'direct' and 'multihop' paths are considered. None"},{"location":"api/tests.bfd/","title":"BFD","text":""},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDPeersHealth","title":"VerifyBFDPeersHealth","text":"

Verifies the health of IPv4 BFD peers across all VRFs.

It checks that no BFD peer is in the down state and that the discriminator value of the remote system is not zero.

Optionally, it can also verify that BFD peers have not been down before a specified threshold of hours.

Expected Results
  • Success: The test will pass if all IPv4 BFD peers are up, the discriminator value of each remote system is non-zero, and the last downtime of each peer is above the defined threshold.
  • Failure: The test will fail if any IPv4 BFD peer is down, the discriminator value of any remote system is zero, or the last downtime of any peer is below the defined threshold.
Examples
anta.tests.bfd:\n  - VerifyBFDPeersHealth:\n      down_threshold: 2\n
Source code in anta/tests/bfd.py
class VerifyBFDPeersHealth(AntaTest):\n    \"\"\"Verifies the health of IPv4 BFD peers across all VRFs.\n\n    It checks that no BFD peer is in the down state and that the discriminator value of the remote system is not zero.\n\n    Optionally, it can also verify that BFD peers have not been down before a specified threshold of hours.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all IPv4 BFD peers are up, the discriminator value of each remote system is non-zero,\n               and the last downtime of each peer is above the defined threshold.\n    * Failure: The test will fail if any IPv4 BFD peer is down, the discriminator value of any remote system is zero,\n               or the last downtime of any peer is below the defined threshold.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.bfd:\n      - VerifyBFDPeersHealth:\n          down_threshold: 2\n    ```\n    \"\"\"\n\n    name = \"VerifyBFDPeersHealth\"\n    description = \"Verifies the health of all IPv4 BFD peers.\"\n    categories: ClassVar[list[str]] = [\"bfd\"]\n    # revision 1 as later revision introduces additional nesting for type\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"show bfd peers\", revision=1),\n        AntaCommand(command=\"show clock\", revision=1),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBFDPeersHealth test.\"\"\"\n\n        down_threshold: int | None = Field(default=None, gt=0)\n        \"\"\"Optional down threshold in hours to check if a BFD peer was down before those hours or not.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBFDPeersHealth.\"\"\"\n        # Initialize failure strings\n        down_failures = []\n        up_failures = []\n\n        # Extract the current timestamp and command output\n        clock_output = self.instance_commands[1].json_output\n        current_timestamp = clock_output[\"utcTime\"]\n        bfd_output = self.instance_commands[0].json_output\n\n        # set the initial result\n        self.result.is_success()\n\n        # Check if any IPv4 BFD peer is configured\n        ipv4_neighbors_exist = any(vrf_data[\"ipv4Neighbors\"] for vrf_data in bfd_output[\"vrfs\"].values())\n        if not ipv4_neighbors_exist:\n            self.result.is_failure(\"No IPv4 BFD peers are configured for any VRF.\")\n            return\n\n        # Iterate over IPv4 BFD peers\n        for vrf, vrf_data in bfd_output[\"vrfs\"].items():\n            for peer, neighbor_data in vrf_data[\"ipv4Neighbors\"].items():\n                for peer_data in neighbor_data[\"peerStats\"].values():\n                    peer_status = peer_data[\"status\"]\n                    remote_disc = peer_data[\"remoteDisc\"]\n                    remote_disc_info = f\" with remote disc {remote_disc}\" if remote_disc == 0 else \"\"\n                    last_down = peer_data[\"lastDown\"]\n                    hours_difference = (\n                        datetime.fromtimestamp(current_timestamp, tz=timezone.utc) - datetime.fromtimestamp(last_down, tz=timezone.utc)\n                    ).total_seconds() / 3600\n\n                    # Check if peer status is not up\n                    if peer_status != \"up\":\n                        down_failures.append(f\"{peer} is {peer_status} in {vrf} VRF{remote_disc_info}.\")\n\n                    # Check if the last down is within the threshold\n                    elif self.inputs.down_threshold and hours_difference < self.inputs.down_threshold:\n                        up_failures.append(f\"{peer} in {vrf} VRF was down {round(hours_difference)} hours ago{remote_disc_info}.\")\n\n                    # Check if remote disc is 0\n                    elif remote_disc == 0:\n                        up_failures.append(f\"{peer} in {vrf} VRF has remote disc {remote_disc}.\")\n\n        # Check if there are any failures\n        if down_failures:\n            down_failures_str = \"\\n\".join(down_failures)\n            self.result.is_failure(f\"Following BFD peers are not up:\\n{down_failures_str}\")\n        if up_failures:\n            up_failures_str = \"\\n\".join(up_failures)\n            self.result.is_failure(f\"\\nFollowing BFD peers were down:\\n{up_failures_str}\")\n
"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDPeersHealth-attributes","title":"Inputs","text":"Name Type Description Default down_threshold int | None Optional down threshold in hours to check if a BFD peer was down before those hours or not. Field(default=None, gt=0)"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDPeersIntervals","title":"VerifyBFDPeersIntervals","text":"

Verifies the timers of the IPv4 BFD peers in the specified VRF.

Expected Results
  • Success: The test will pass if the timers of the IPv4 BFD peers are correct in the specified VRF.
  • Failure: The test will fail if the IPv4 BFD peers are not found or their timers are incorrect in the specified VRF.
Examples
anta.tests.bfd:\n  - VerifyBFDPeersIntervals:\n      bfd_peers:\n        - peer_address: 192.0.255.8\n          vrf: default\n          tx_interval: 1200\n          rx_interval: 1200\n          multiplier: 3\n        - peer_address: 192.0.255.7\n          vrf: default\n          tx_interval: 1200\n          rx_interval: 1200\n          multiplier: 3\n
Source code in anta/tests/bfd.py
class VerifyBFDPeersIntervals(AntaTest):\n    \"\"\"Verifies the timers of the IPv4 BFD peers in the specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the timers of the IPv4 BFD peers are correct in the specified VRF.\n    * Failure: The test will fail if the IPv4 BFD peers are not found or their timers are incorrect in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.bfd:\n      - VerifyBFDPeersIntervals:\n          bfd_peers:\n            - peer_address: 192.0.255.8\n              vrf: default\n              tx_interval: 1200\n              rx_interval: 1200\n              multiplier: 3\n            - peer_address: 192.0.255.7\n              vrf: default\n              tx_interval: 1200\n              rx_interval: 1200\n              multiplier: 3\n    ```\n    \"\"\"\n\n    name = \"VerifyBFDPeersIntervals\"\n    description = \"Verifies the timers of the IPv4 BFD peers in the specified VRF.\"\n    categories: ClassVar[list[str]] = [\"bfd\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bfd peers detail\", revision=4)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBFDPeersIntervals test.\"\"\"\n\n        bfd_peers: list[BFDPeer]\n        \"\"\"List of BFD peers.\"\"\"\n\n        class BFDPeer(BaseModel):\n            \"\"\"Model for an IPv4 BFD peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BFD peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BFD peer. If not provided, it defaults to `default`.\"\"\"\n            tx_interval: BfdInterval\n            \"\"\"Tx interval of BFD peer in milliseconds.\"\"\"\n            rx_interval: BfdInterval\n            \"\"\"Rx interval of BFD peer in milliseconds.\"\"\"\n            multiplier: BfdMultiplier\n            \"\"\"Multiplier of BFD peer.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBFDPeersIntervals.\"\"\"\n        failures: dict[Any, Any] = {}\n\n        # Iterating over BFD peers\n        for bfd_peers in self.inputs.bfd_peers:\n            peer = str(bfd_peers.peer_address)\n            vrf = bfd_peers.vrf\n\n            # Converting milliseconds intervals into actual value\n            tx_interval = bfd_peers.tx_interval * 1000\n            rx_interval = bfd_peers.rx_interval * 1000\n            multiplier = bfd_peers.multiplier\n            bfd_output = get_value(\n                self.instance_commands[0].json_output,\n                f\"vrfs..{vrf}..ipv4Neighbors..{peer}..peerStats..\",\n                separator=\"..\",\n            )\n\n            # Check if BFD peer configured\n            if not bfd_output:\n                failures[peer] = {vrf: \"Not Configured\"}\n                continue\n\n            bfd_details = bfd_output.get(\"peerStatsDetail\", {})\n            intervals_ok = (\n                bfd_details.get(\"operTxInterval\") == tx_interval and bfd_details.get(\"operRxInterval\") == rx_interval and bfd_details.get(\"detectMult\") == multiplier\n            )\n\n            # Check timers of BFD peer\n            if not intervals_ok:\n                failures[peer] = {\n                    vrf: {\n                        \"tx_interval\": bfd_details.get(\"operTxInterval\"),\n                        \"rx_interval\": bfd_details.get(\"operRxInterval\"),\n                        \"multiplier\": bfd_details.get(\"detectMult\"),\n                    }\n                }\n\n        # Check if any failures\n        if not failures:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BFD peers are not configured or timers are not correct:\\n{failures}\")\n
"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDPeersIntervals-attributes","title":"Inputs","text":"Name Type Description Default bfd_peers list[BFDPeer] List of BFD peers. -"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDPeersIntervals-attributes","title":"BFDPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BFD peer. - vrf str Optional VRF for BFD peer. If not provided, it defaults to `default`. 'default' tx_interval BfdInterval Tx interval of BFD peer in milliseconds. - rx_interval BfdInterval Rx interval of BFD peer in milliseconds. - multiplier BfdMultiplier Multiplier of BFD peer. -"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDSpecificPeers","title":"VerifyBFDSpecificPeers","text":"

Verifies if the IPv4 BFD peer\u2019s sessions are UP and remote disc is non-zero in the specified VRF.

Expected Results
  • Success: The test will pass if IPv4 BFD peers are up and remote disc is non-zero in the specified VRF.
  • Failure: The test will fail if IPv4 BFD peers are not found, the status is not UP or remote disc is zero in the specified VRF.
Examples
anta.tests.bfd:\n  - VerifyBFDSpecificPeers:\n      bfd_peers:\n        - peer_address: 192.0.255.8\n          vrf: default\n        - peer_address: 192.0.255.7\n          vrf: default\n
Source code in anta/tests/bfd.py
class VerifyBFDSpecificPeers(AntaTest):\n    \"\"\"Verifies if the IPv4 BFD peer's sessions are UP and remote disc is non-zero in the specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if IPv4 BFD peers are up and remote disc is non-zero in the specified VRF.\n    * Failure: The test will fail if IPv4 BFD peers are not found, the status is not UP or remote disc is zero in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.bfd:\n      - VerifyBFDSpecificPeers:\n          bfd_peers:\n            - peer_address: 192.0.255.8\n              vrf: default\n            - peer_address: 192.0.255.7\n              vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyBFDSpecificPeers\"\n    description = \"Verifies the IPv4 BFD peer's sessions and remote disc in the specified VRF.\"\n    categories: ClassVar[list[str]] = [\"bfd\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bfd peers\", revision=4)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBFDSpecificPeers test.\"\"\"\n\n        bfd_peers: list[BFDPeer]\n        \"\"\"List of IPv4 BFD peers.\"\"\"\n\n        class BFDPeer(BaseModel):\n            \"\"\"Model for an IPv4 BFD peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BFD peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BFD peer. If not provided, it defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBFDSpecificPeers.\"\"\"\n        failures: dict[Any, Any] = {}\n\n        # Iterating over BFD peers\n        for bfd_peer in self.inputs.bfd_peers:\n            peer = str(bfd_peer.peer_address)\n            vrf = bfd_peer.vrf\n            bfd_output = get_value(\n                self.instance_commands[0].json_output,\n                f\"vrfs..{vrf}..ipv4Neighbors..{peer}..peerStats..\",\n                separator=\"..\",\n            )\n\n            # Check if BFD peer configured\n            if not bfd_output:\n                failures[peer] = {vrf: \"Not Configured\"}\n                continue\n\n            # Check BFD peer status and remote disc\n            if not (bfd_output.get(\"status\") == \"up\" and bfd_output.get(\"remoteDisc\") != 0):\n                failures[peer] = {\n                    vrf: {\n                        \"status\": bfd_output.get(\"status\"),\n                        \"remote_disc\": bfd_output.get(\"remoteDisc\"),\n                    }\n                }\n\n        if not failures:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BFD peers are not configured, status is not up or remote disc is zero:\\n{failures}\")\n
"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDSpecificPeers-attributes","title":"Inputs","text":"Name Type Description Default bfd_peers list[BFDPeer] List of IPv4 BFD peers. -"},{"location":"api/tests.bfd/#anta.tests.bfd.VerifyBFDSpecificPeers-attributes","title":"BFDPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BFD peer. - vrf str Optional VRF for BFD peer. If not provided, it defaults to `default`. 'default'"},{"location":"api/tests.configuration/","title":"Configuration","text":""},{"location":"api/tests.configuration/#anta.tests.configuration.VerifyRunningConfigDiffs","title":"VerifyRunningConfigDiffs","text":"

Verifies there is no difference between the running-config and the startup-config.

Expected Results
  • Success: The test will pass if there is no difference between the running-config and the startup-config.
  • Failure: The test will fail if there is a difference between the running-config and the startup-config.
Examples
anta.tests.configuration:\n  - VerifyRunningConfigDiffs:\n
Source code in anta/tests/configuration.py
class VerifyRunningConfigDiffs(AntaTest):\n    \"\"\"Verifies there is no difference between the running-config and the startup-config.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there is no difference between the running-config and the startup-config.\n    * Failure: The test will fail if there is a difference between the running-config and the startup-config.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.configuration:\n      - VerifyRunningConfigDiffs:\n    ```\n    \"\"\"\n\n    name = \"VerifyRunningConfigDiffs\"\n    description = \"Verifies there is no difference between the running-config and the startup-config\"\n    categories: ClassVar[list[str]] = [\"configuration\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show running-config diffs\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyRunningConfigDiffs.\"\"\"\n        command_output = self.instance_commands[0].text_output\n        if command_output == \"\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(command_output)\n
"},{"location":"api/tests.configuration/#anta.tests.configuration.VerifyRunningConfigLines","title":"VerifyRunningConfigLines","text":"

Verifies the given regular expression patterns are present in the running-config.

Warning

Since this uses regular expression searches on the whole running-config, it can drastically impact performance and should only be used if no other test is available.

If possible, try using another ANTA test that is more specific.

Expected Results
  • Success: The test will pass if all the patterns are found in the running-config.
  • Failure: The test will fail if any of the patterns are NOT found in the running-config.
Examples
anta.tests.configuration:\n  - VerifyRunningConfigLines:\n        regex_patterns:\n            - \"^enable password.*$\"\n            - \"bla bla\"\n
Source code in anta/tests/configuration.py
class VerifyRunningConfigLines(AntaTest):\n    \"\"\"Verifies the given regular expression patterns are present in the running-config.\n\n    !!! warning\n        Since this uses regular expression searches on the whole running-config, it can\n        drastically impact performance and should only be used if no other test is available.\n\n        If possible, try using another ANTA test that is more specific.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all the patterns are found in the running-config.\n    * Failure: The test will fail if any of the patterns are NOT found in the running-config.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.configuration:\n      - VerifyRunningConfigLines:\n            regex_patterns:\n                - \"^enable password.*$\"\n                - \"bla bla\"\n    ```\n    \"\"\"\n\n    name = \"VerifyRunningConfigLines\"\n    description = \"Search the Running-Config for the given RegEx patterns.\"\n    categories: ClassVar[list[str]] = [\"configuration\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show running-config\", ofmt=\"text\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyRunningConfigLines test.\"\"\"\n\n        regex_patterns: list[RegexString]\n        \"\"\"List of regular expressions.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyRunningConfigLines.\"\"\"\n        failure_msgs = []\n        command_output = self.instance_commands[0].text_output\n\n        for pattern in self.inputs.regex_patterns:\n            re_search = re.compile(pattern, flags=re.MULTILINE)\n\n            if not re_search.search(command_output):\n                failure_msgs.append(f\"'{pattern}'\")\n\n        if not failure_msgs:\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"Following patterns were not found: \" + \",\".join(failure_msgs))\n
"},{"location":"api/tests.configuration/#anta.tests.configuration.VerifyRunningConfigLines-attributes","title":"Inputs","text":"Name Type Description Default regex_patterns list[RegexString] List of regular expressions. -"},{"location":"api/tests.configuration/#anta.tests.configuration.VerifyZeroTouch","title":"VerifyZeroTouch","text":"

Verifies ZeroTouch is disabled.

Expected Results
  • Success: The test will pass if ZeroTouch is disabled.
  • Failure: The test will fail if ZeroTouch is enabled.
Examples
anta.tests.configuration:\n  - VerifyZeroTouch:\n
Source code in anta/tests/configuration.py
class VerifyZeroTouch(AntaTest):\n    \"\"\"Verifies ZeroTouch is disabled.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if ZeroTouch is disabled.\n    * Failure: The test will fail if ZeroTouch is enabled.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.configuration:\n      - VerifyZeroTouch:\n    ```\n    \"\"\"\n\n    name = \"VerifyZeroTouch\"\n    description = \"Verifies ZeroTouch is disabled\"\n    categories: ClassVar[list[str]] = [\"configuration\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show zerotouch\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyZeroTouch.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"mode\"] == \"disabled\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"ZTP is NOT disabled\")\n
"},{"location":"api/tests.connectivity/","title":"Connectivity","text":""},{"location":"api/tests.connectivity/#anta.tests.connectivity.VerifyLLDPNeighbors","title":"VerifyLLDPNeighbors","text":"

Verifies that the provided LLDP neighbors are present and connected with the correct configuration.

Expected Results
  • Success: The test will pass if each of the provided LLDP neighbors is present and connected to the specified port and device.
  • Failure: The test will fail if any of the following conditions are met:
    • The provided LLDP neighbor is not found.
    • The system name or port of the LLDP neighbor does not match the provided information.
Examples
anta.tests.connectivity:\n  - VerifyLLDPNeighbors:\n      neighbors:\n        - port: Ethernet1\n          neighbor_device: DC1-SPINE1\n          neighbor_port: Ethernet1\n        - port: Ethernet2\n          neighbor_device: DC1-SPINE2\n          neighbor_port: Ethernet1\n
Source code in anta/tests/connectivity.py
class VerifyLLDPNeighbors(AntaTest):\n    \"\"\"Verifies that the provided LLDP neighbors are present and connected with the correct configuration.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if each of the provided LLDP neighbors is present and connected to the specified port and device.\n    * Failure: The test will fail if any of the following conditions are met:\n        - The provided LLDP neighbor is not found.\n        - The system name or port of the LLDP neighbor does not match the provided information.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.connectivity:\n      - VerifyLLDPNeighbors:\n          neighbors:\n            - port: Ethernet1\n              neighbor_device: DC1-SPINE1\n              neighbor_port: Ethernet1\n            - port: Ethernet2\n              neighbor_device: DC1-SPINE2\n              neighbor_port: Ethernet1\n    ```\n    \"\"\"\n\n    name = \"VerifyLLDPNeighbors\"\n    description = \"Verifies that the provided LLDP neighbors are connected properly.\"\n    categories: ClassVar[list[str]] = [\"connectivity\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show lldp neighbors detail\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyLLDPNeighbors test.\"\"\"\n\n        neighbors: list[Neighbor]\n        \"\"\"List of LLDP neighbors.\"\"\"\n\n        class Neighbor(BaseModel):\n            \"\"\"Model for an LLDP neighbor.\"\"\"\n\n            port: Interface\n            \"\"\"LLDP port.\"\"\"\n            neighbor_device: str\n            \"\"\"LLDP neighbor device.\"\"\"\n            neighbor_port: Interface\n            \"\"\"LLDP neighbor port.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLLDPNeighbors.\"\"\"\n        failures: dict[str, list[str]] = {}\n\n        output = self.instance_commands[0].json_output[\"lldpNeighbors\"]\n\n        for neighbor in self.inputs.neighbors:\n            if neighbor.port not in output:\n                failures.setdefault(\"Port(s) not configured\", []).append(neighbor.port)\n                continue\n\n            if len(lldp_neighbor_info := output[neighbor.port][\"lldpNeighborInfo\"]) == 0:\n                failures.setdefault(\"No LLDP neighbor(s) on port(s)\", []).append(neighbor.port)\n                continue\n\n            if not any(\n                info[\"systemName\"] == neighbor.neighbor_device and info[\"neighborInterfaceInfo\"][\"interfaceId_v2\"] == neighbor.neighbor_port\n                for info in lldp_neighbor_info\n            ):\n                neighbors = \"\\n      \".join(\n                    [\n                        f\"{neighbor[0]}_{neighbor[1]}\"\n                        for neighbor in [(info[\"systemName\"], info[\"neighborInterfaceInfo\"][\"interfaceId_v2\"]) for info in lldp_neighbor_info]\n                    ]\n                )\n                failures.setdefault(\"Wrong LLDP neighbor(s) on port(s)\", []).append(f\"{neighbor.port}\\n      {neighbors}\")\n\n        if not failures:\n            self.result.is_success()\n        else:\n            failure_messages = []\n            for failure_type, ports in failures.items():\n                ports_str = \"\\n   \".join(ports)\n                failure_messages.append(f\"{failure_type}:\\n   {ports_str}\")\n            self.result.is_failure(\"\\n\".join(failure_messages))\n
"},{"location":"api/tests.connectivity/#anta.tests.connectivity.VerifyLLDPNeighbors-attributes","title":"Inputs","text":"Name Type Description Default neighbors list[Neighbor] List of LLDP neighbors. -"},{"location":"api/tests.connectivity/#anta.tests.connectivity.VerifyLLDPNeighbors-attributes","title":"Neighbor","text":"Name Type Description Default port Interface LLDP port. - neighbor_device str LLDP neighbor device. - neighbor_port Interface LLDP neighbor port. -"},{"location":"api/tests.connectivity/#anta.tests.connectivity.VerifyReachability","title":"VerifyReachability","text":"

Test network reachability to one or many destination IP(s).

Expected Results
  • Success: The test will pass if all destination IP(s) are reachable.
  • Failure: The test will fail if one or many destination IP(s) are unreachable.
Examples
anta.tests.connectivity:\n  - VerifyReachability:\n      hosts:\n        - source: Management0\n          destination: 1.1.1.1\n          vrf: MGMT\n        - source: Management0\n          destination: 8.8.8.8\n          vrf: MGMT\n
Source code in anta/tests/connectivity.py
class VerifyReachability(AntaTest):\n    \"\"\"Test network reachability to one or many destination IP(s).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all destination IP(s) are reachable.\n    * Failure: The test will fail if one or many destination IP(s) are unreachable.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.connectivity:\n      - VerifyReachability:\n          hosts:\n            - source: Management0\n              destination: 1.1.1.1\n              vrf: MGMT\n            - source: Management0\n              destination: 8.8.8.8\n              vrf: MGMT\n    ```\n    \"\"\"\n\n    name = \"VerifyReachability\"\n    description = \"Test the network reachability to one or many destination IP(s).\"\n    categories: ClassVar[list[str]] = [\"connectivity\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"ping vrf {vrf} {destination} source {source} repeat {repeat}\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyReachability test.\"\"\"\n\n        hosts: list[Host]\n        \"\"\"List of host to ping.\"\"\"\n\n        class Host(BaseModel):\n            \"\"\"Model for a remote host to ping.\"\"\"\n\n            destination: IPv4Address\n            \"\"\"IPv4 address to ping.\"\"\"\n            source: IPv4Address | Interface\n            \"\"\"IPv4 address source IP or egress interface to use.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"VRF context. Defaults to `default`.\"\"\"\n            repeat: int = 2\n            \"\"\"Number of ping repetition. Defaults to 2.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each host in the input list.\"\"\"\n        return [template.render(destination=host.destination, source=host.source, vrf=host.vrf, repeat=host.repeat) for host in self.inputs.hosts]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyReachability.\"\"\"\n        failures = []\n        for command in self.instance_commands:\n            src = command.params.source\n            dst = command.params.destination\n            repeat = command.params.repeat\n\n            if f\"{repeat} received\" not in command.json_output[\"messages\"][0]:\n                failures.append((str(src), str(dst)))\n\n        if not failures:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Connectivity test failed for the following source-destination pairs: {failures}\")\n
"},{"location":"api/tests.connectivity/#anta.tests.connectivity.VerifyReachability-attributes","title":"Inputs","text":"Name Type Description Default hosts list[Host] List of host to ping. -"},{"location":"api/tests.connectivity/#anta.tests.connectivity.VerifyReachability-attributes","title":"Host","text":"Name Type Description Default destination IPv4Address IPv4 address to ping. - source IPv4Address | Interface IPv4 address source IP or egress interface to use. - vrf str VRF context. Defaults to `default`. 'default' repeat int Number of ping repetition. Defaults to 2. 2"},{"location":"api/tests.field_notices/","title":"Field Notices","text":""},{"location":"api/tests.field_notices/#anta.tests.field_notices.VerifyFieldNotice44Resolution","title":"VerifyFieldNotice44Resolution","text":"

Verifies if the device is using an Aboot version that fixes the bug discussed in the Field Notice 44.

Aboot manages system settings prior to EOS initialization.

Reference: https://www.arista.com/en/support/advisories-notices/field-notice/8756-field-notice-44

Expected Results
  • Success: The test will pass if the device is using an Aboot version that fixes the bug discussed in the Field Notice 44.
  • Failure: The test will fail if the device is not using an Aboot version that fixes the bug discussed in the Field Notice 44.
Examples
anta.tests.field_notices:\n  - VerifyFieldNotice44Resolution:\n
Source code in anta/tests/field_notices.py
class VerifyFieldNotice44Resolution(AntaTest):\n    \"\"\"Verifies if the device is using an Aboot version that fixes the bug discussed in the Field Notice 44.\n\n    Aboot manages system settings prior to EOS initialization.\n\n    Reference: https://www.arista.com/en/support/advisories-notices/field-notice/8756-field-notice-44\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is using an Aboot version that fixes the bug discussed in the Field Notice 44.\n    * Failure: The test will fail if the device is not using an Aboot version that fixes the bug discussed in the Field Notice 44.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.field_notices:\n      - VerifyFieldNotice44Resolution:\n    ```\n    \"\"\"\n\n    name = \"VerifyFieldNotice44Resolution\"\n    description = \"Verifies that the device is using the correct Aboot version per FN0044.\"\n    categories: ClassVar[list[str]] = [\"field notices\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show version detail\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyFieldNotice44Resolution.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        devices = [\n            \"DCS-7010T-48\",\n            \"DCS-7010T-48-DC\",\n            \"DCS-7050TX-48\",\n            \"DCS-7050TX-64\",\n            \"DCS-7050TX-72\",\n            \"DCS-7050TX-72Q\",\n            \"DCS-7050TX-96\",\n            \"DCS-7050TX2-128\",\n            \"DCS-7050SX-64\",\n            \"DCS-7050SX-72\",\n            \"DCS-7050SX-72Q\",\n            \"DCS-7050SX2-72Q\",\n            \"DCS-7050SX-96\",\n            \"DCS-7050SX2-128\",\n            \"DCS-7050QX-32S\",\n            \"DCS-7050QX2-32S\",\n            \"DCS-7050SX3-48YC12\",\n            \"DCS-7050CX3-32S\",\n            \"DCS-7060CX-32S\",\n            \"DCS-7060CX2-32S\",\n            \"DCS-7060SX2-48YC6\",\n            \"DCS-7160-48YC6\",\n            \"DCS-7160-48TC6\",\n            \"DCS-7160-32CQ\",\n            \"DCS-7280SE-64\",\n            \"DCS-7280SE-68\",\n            \"DCS-7280SE-72\",\n            \"DCS-7150SC-24-CLD\",\n            \"DCS-7150SC-64-CLD\",\n            \"DCS-7020TR-48\",\n            \"DCS-7020TRA-48\",\n            \"DCS-7020SR-24C2\",\n            \"DCS-7020SRG-24C2\",\n            \"DCS-7280TR-48C6\",\n            \"DCS-7280TRA-48C6\",\n            \"DCS-7280SR-48C6\",\n            \"DCS-7280SRA-48C6\",\n            \"DCS-7280SRAM-48C6\",\n            \"DCS-7280SR2K-48C6-M\",\n            \"DCS-7280SR2-48YC6\",\n            \"DCS-7280SR2A-48YC6\",\n            \"DCS-7280SRM-40CX2\",\n            \"DCS-7280QR-C36\",\n            \"DCS-7280QRA-C36S\",\n        ]\n        variants = [\"-SSD-F\", \"-SSD-R\", \"-M-F\", \"-M-R\", \"-F\", \"-R\"]\n\n        model = command_output[\"modelName\"]\n        for variant in variants:\n            model = model.replace(variant, \"\")\n        if model not in devices:\n            self.result.is_skipped(\"device is not impacted by FN044\")\n            return\n\n        for component in command_output[\"details\"][\"components\"]:\n            if component[\"name\"] == \"Aboot\":\n                aboot_version = component[\"version\"].split(\"-\")[2]\n                break\n        else:\n            self.result.is_failure(\"Aboot component not found\")\n            return\n\n        self.result.is_success()\n        incorrect_aboot_version = (\n            aboot_version.startswith(\"4.0.\")\n            and int(aboot_version.split(\".\")[2]) < 7\n            or aboot_version.startswith(\"4.1.\")\n            and int(aboot_version.split(\".\")[2]) < 1\n            or (\n                aboot_version.startswith(\"6.0.\")\n                and int(aboot_version.split(\".\")[2]) < 9\n                or aboot_version.startswith(\"6.1.\")\n                and int(aboot_version.split(\".\")[2]) < 7\n            )\n        )\n        if incorrect_aboot_version:\n            self.result.is_failure(f\"device is running incorrect version of aboot ({aboot_version})\")\n
"},{"location":"api/tests.field_notices/#anta.tests.field_notices.VerifyFieldNotice72Resolution","title":"VerifyFieldNotice72Resolution","text":"

Verifies if the device is potentially exposed to Field Notice 72, and if the issue has been mitigated.

Reference: https://www.arista.com/en/support/advisories-notices/field-notice/17410-field-notice-0072

Expected Results
  • Success: The test will pass if the device is not exposed to FN72 and the issue has been mitigated.
  • Failure: The test will fail if the device is exposed to FN72 and the issue has not been mitigated.
Examples
anta.tests.field_notices:\n  - VerifyFieldNotice72Resolution:\n
Source code in anta/tests/field_notices.py
class VerifyFieldNotice72Resolution(AntaTest):\n    \"\"\"Verifies if the device is potentially exposed to Field Notice 72, and if the issue has been mitigated.\n\n    Reference: https://www.arista.com/en/support/advisories-notices/field-notice/17410-field-notice-0072\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is not exposed to FN72 and the issue has been mitigated.\n    * Failure: The test will fail if the device is exposed to FN72 and the issue has not been mitigated.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.field_notices:\n      - VerifyFieldNotice72Resolution:\n    ```\n    \"\"\"\n\n    name = \"VerifyFieldNotice72Resolution\"\n    description = \"Verifies if the device is exposed to FN0072, and if the issue has been mitigated.\"\n    categories: ClassVar[list[str]] = [\"field notices\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show version detail\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyFieldNotice72Resolution.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        devices = [\"DCS-7280SR3-48YC8\", \"DCS-7280SR3K-48YC8\"]\n        variants = [\"-SSD-F\", \"-SSD-R\", \"-M-F\", \"-M-R\", \"-F\", \"-R\"]\n        model = command_output[\"modelName\"]\n\n        for variant in variants:\n            model = model.replace(variant, \"\")\n        if model not in devices:\n            self.result.is_skipped(\"Platform is not impacted by FN072\")\n            return\n\n        serial = command_output[\"serialNumber\"]\n        number = int(serial[3:7])\n\n        if \"JPE\" not in serial and \"JAS\" not in serial:\n            self.result.is_skipped(\"Device not exposed\")\n            return\n\n        if model == \"DCS-7280SR3-48YC8\" and \"JPE\" in serial and number >= 2131:\n            self.result.is_skipped(\"Device not exposed\")\n            return\n\n        if model == \"DCS-7280SR3-48YC8\" and \"JAS\" in serial and number >= 2041:\n            self.result.is_skipped(\"Device not exposed\")\n            return\n\n        if model == \"DCS-7280SR3K-48YC8\" and \"JPE\" in serial and number >= 2134:\n            self.result.is_skipped(\"Device not exposed\")\n            return\n\n        if model == \"DCS-7280SR3K-48YC8\" and \"JAS\" in serial and number >= 2041:\n            self.result.is_skipped(\"Device not exposed\")\n            return\n\n        # Because each of the if checks above will return if taken, we only run the long check if we get this far\n        for entry in command_output[\"details\"][\"components\"]:\n            if entry[\"name\"] == \"FixedSystemvrm1\":\n                if int(entry[\"version\"]) < 7:\n                    self.result.is_failure(\"Device is exposed to FN72\")\n                else:\n                    self.result.is_success(\"FN72 is mitigated\")\n                return\n        # We should never hit this point\n        self.result.is_error(\"Error in running test - FixedSystemvrm1 not found\")\n
"},{"location":"api/tests.greent/","title":"GreenT","text":""},{"location":"api/tests.greent/#anta.tests.greent.VerifyGreenT","title":"VerifyGreenT","text":"

Verifies if a GreenT (GRE Encapsulated Telemetry) policy other than the default is created.

Expected Results
  • Success: The test will pass if a GreenT policy is created other than the default one.
  • Failure: The test will fail if no other GreenT policy is created.
Examples
anta.tests.greent:\n  - VerifyGreenTCounters:\n
Source code in anta/tests/greent.py
class VerifyGreenT(AntaTest):\n    \"\"\"Verifies if a GreenT (GRE Encapsulated Telemetry) policy other than the default is created.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if a GreenT policy is created other than the default one.\n    * Failure: The test will fail if no other GreenT policy is created.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.greent:\n      - VerifyGreenTCounters:\n    ```\n    \"\"\"\n\n    name = \"VerifyGreenT\"\n    description = \"Verifies if a GreenT policy is created.\"\n    categories: ClassVar[list[str]] = [\"greent\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show monitor telemetry postcard policy profile\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyGreenT.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        profiles = [profile for profile in command_output[\"profiles\"] if profile != \"default\"]\n\n        if profiles:\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"No GreenT policy is created\")\n
"},{"location":"api/tests.greent/#anta.tests.greent.VerifyGreenTCounters","title":"VerifyGreenTCounters","text":"

Verifies if the GreenT (GRE Encapsulated Telemetry) counters are incremented.

Expected Results
  • Success: The test will pass if the GreenT counters are incremented.
  • Failure: The test will fail if the GreenT counters are not incremented.
Examples
anta.tests.greent:\n  - VerifyGreenT:\n
Source code in anta/tests/greent.py
class VerifyGreenTCounters(AntaTest):\n    \"\"\"Verifies if the GreenT (GRE Encapsulated Telemetry) counters are incremented.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the GreenT counters are incremented.\n    * Failure: The test will fail if the GreenT counters are not incremented.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.greent:\n      - VerifyGreenT:\n    ```\n    \"\"\"\n\n    name = \"VerifyGreenTCounters\"\n    description = \"Verifies if the GreenT counters are incremented.\"\n    categories: ClassVar[list[str]] = [\"greent\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show monitor telemetry postcard counters\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyGreenTCounters.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        if command_output[\"grePktSent\"] > 0:\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"GreenT counters are not incremented\")\n
"},{"location":"api/tests.hardware/","title":"Hardware","text":""},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyAdverseDrops","title":"VerifyAdverseDrops","text":"

Verifies there are no adverse drops on DCS-7280 and DCS-7500 family switches (Arad/Jericho chips).

Expected Results
  • Success: The test will pass if there are no adverse drops.
  • Failure: The test will fail if there are adverse drops.
Examples
anta.tests.hardware:\n  - VerifyAdverseDrops:\n
Source code in anta/tests/hardware.py
class VerifyAdverseDrops(AntaTest):\n    \"\"\"Verifies there are no adverse drops on DCS-7280 and DCS-7500 family switches (Arad/Jericho chips).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are no adverse drops.\n    * Failure: The test will fail if there are adverse drops.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyAdverseDrops:\n    ```\n    \"\"\"\n\n    name = \"VerifyAdverseDrops\"\n    description = \"Verifies there are no adverse drops on DCS-7280 and DCS-7500 family switches.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show hardware counter drop\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAdverseDrops.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        total_adverse_drop = command_output.get(\"totalAdverseDrops\", \"\")\n        if total_adverse_drop == 0:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device totalAdverseDrops counter is: '{total_adverse_drop}'\")\n
"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyEnvironmentCooling","title":"VerifyEnvironmentCooling","text":"

Verifies the status of power supply fans and all fan trays.

Expected Results
  • Success: The test will pass if the fans status are within the accepted states list.
  • Failure: The test will fail if some fans status is not within the accepted states list.
Examples
anta.tests.hardware:\n  - VerifyEnvironmentCooling:\n      states:\n        - ok\n
Source code in anta/tests/hardware.py
class VerifyEnvironmentCooling(AntaTest):\n    \"\"\"Verifies the status of power supply fans and all fan trays.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the fans status are within the accepted states list.\n    * Failure: The test will fail if some fans status is not within the accepted states list.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyEnvironmentCooling:\n          states:\n            - ok\n    ```\n    \"\"\"\n\n    name = \"VerifyEnvironmentCooling\"\n    description = \"Verifies the status of power supply fans and all fan trays.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system environment cooling\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyEnvironmentCooling test.\"\"\"\n\n        states: list[str]\n        \"\"\"List of accepted states of fan status.\"\"\"\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyEnvironmentCooling.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n        # First go through power supplies fans\n        for power_supply in command_output.get(\"powerSupplySlots\", []):\n            for fan in power_supply.get(\"fans\", []):\n                if (state := fan[\"status\"]) not in self.inputs.states:\n                    self.result.is_failure(f\"Fan {fan['label']} on PowerSupply {power_supply['label']} is: '{state}'\")\n        # Then go through fan trays\n        for fan_tray in command_output.get(\"fanTraySlots\", []):\n            for fan in fan_tray.get(\"fans\", []):\n                if (state := fan[\"status\"]) not in self.inputs.states:\n                    self.result.is_failure(f\"Fan {fan['label']} on Fan Tray {fan_tray['label']} is: '{state}'\")\n
"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyEnvironmentCooling-attributes","title":"Inputs","text":"Name Type Description Default states list[str] List of accepted states of fan status. -"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyEnvironmentPower","title":"VerifyEnvironmentPower","text":"

Verifies the power supplies status.

Expected Results
  • Success: The test will pass if the power supplies status are within the accepted states list.
  • Failure: The test will fail if some power supplies status is not within the accepted states list.
Examples
anta.tests.hardware:\n  - VerifyEnvironmentPower:\n      states:\n        - ok\n
Source code in anta/tests/hardware.py
class VerifyEnvironmentPower(AntaTest):\n    \"\"\"Verifies the power supplies status.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the power supplies status are within the accepted states list.\n    * Failure: The test will fail if some power supplies status is not within the accepted states list.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyEnvironmentPower:\n          states:\n            - ok\n    ```\n    \"\"\"\n\n    name = \"VerifyEnvironmentPower\"\n    description = \"Verifies the power supplies status.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system environment power\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyEnvironmentPower test.\"\"\"\n\n        states: list[str]\n        \"\"\"List of accepted states list of power supplies status.\"\"\"\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyEnvironmentPower.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        power_supplies = command_output.get(\"powerSupplies\", \"{}\")\n        wrong_power_supplies = {\n            powersupply: {\"state\": value[\"state\"]} for powersupply, value in dict(power_supplies).items() if value[\"state\"] not in self.inputs.states\n        }\n        if not wrong_power_supplies:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following power supplies status are not in the accepted states list: {wrong_power_supplies}\")\n
"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyEnvironmentPower-attributes","title":"Inputs","text":"Name Type Description Default states list[str] List of accepted states list of power supplies status. -"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyEnvironmentSystemCooling","title":"VerifyEnvironmentSystemCooling","text":"

Verifies the device\u2019s system cooling status.

Expected Results
  • Success: The test will pass if the system cooling status is OK: \u2018coolingOk\u2019.
  • Failure: The test will fail if the system cooling status is NOT OK.
Examples
anta.tests.hardware:\n  - VerifyEnvironmentSystemCooling:\n
Source code in anta/tests/hardware.py
class VerifyEnvironmentSystemCooling(AntaTest):\n    \"\"\"Verifies the device's system cooling status.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the system cooling status is OK: 'coolingOk'.\n    * Failure: The test will fail if the system cooling status is NOT OK.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyEnvironmentSystemCooling:\n    ```\n    \"\"\"\n\n    name = \"VerifyEnvironmentSystemCooling\"\n    description = \"Verifies the system cooling status.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system environment cooling\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyEnvironmentSystemCooling.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        sys_status = command_output.get(\"systemStatus\", \"\")\n        self.result.is_success()\n        if sys_status != \"coolingOk\":\n            self.result.is_failure(f\"Device system cooling is not OK: '{sys_status}'\")\n
"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyTemperature","title":"VerifyTemperature","text":"

Verifies if the device temperature is within acceptable limits.

Expected Results
  • Success: The test will pass if the device temperature is currently OK: \u2018temperatureOk\u2019.
  • Failure: The test will fail if the device temperature is NOT OK.
Examples
anta.tests.hardware:\n  - VerifyTemperature:\n
Source code in anta/tests/hardware.py
class VerifyTemperature(AntaTest):\n    \"\"\"Verifies if the device temperature is within acceptable limits.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device temperature is currently OK: 'temperatureOk'.\n    * Failure: The test will fail if the device temperature is NOT OK.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyTemperature:\n    ```\n    \"\"\"\n\n    name = \"VerifyTemperature\"\n    description = \"Verifies the device temperature.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system environment temperature\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTemperature.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        temperature_status = command_output.get(\"systemStatus\", \"\")\n        if temperature_status == \"temperatureOk\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device temperature exceeds acceptable limits. Current system status: '{temperature_status}'\")\n
"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyTransceiversManufacturers","title":"VerifyTransceiversManufacturers","text":"

Verifies if all the transceivers come from approved manufacturers.

Expected Results
  • Success: The test will pass if all transceivers are from approved manufacturers.
  • Failure: The test will fail if some transceivers are from unapproved manufacturers.
Examples
anta.tests.hardware:\n  - VerifyTransceiversManufacturers:\n      manufacturers:\n        - Not Present\n        - Arista Networks\n        - Arastra, Inc.\n
Source code in anta/tests/hardware.py
class VerifyTransceiversManufacturers(AntaTest):\n    \"\"\"Verifies if all the transceivers come from approved manufacturers.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all transceivers are from approved manufacturers.\n    * Failure: The test will fail if some transceivers are from unapproved manufacturers.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyTransceiversManufacturers:\n          manufacturers:\n            - Not Present\n            - Arista Networks\n            - Arastra, Inc.\n    ```\n    \"\"\"\n\n    name = \"VerifyTransceiversManufacturers\"\n    description = \"Verifies if all transceivers come from approved manufacturers.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show inventory\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyTransceiversManufacturers test.\"\"\"\n\n        manufacturers: list[str]\n        \"\"\"List of approved transceivers manufacturers.\"\"\"\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTransceiversManufacturers.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        wrong_manufacturers = {\n            interface: value[\"mfgName\"] for interface, value in command_output[\"xcvrSlots\"].items() if value[\"mfgName\"] not in self.inputs.manufacturers\n        }\n        if not wrong_manufacturers:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Some transceivers are from unapproved manufacturers: {wrong_manufacturers}\")\n
"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyTransceiversManufacturers-attributes","title":"Inputs","text":"Name Type Description Default manufacturers list[str] List of approved transceivers manufacturers. -"},{"location":"api/tests.hardware/#anta.tests.hardware.VerifyTransceiversTemperature","title":"VerifyTransceiversTemperature","text":"

Verifies if all the transceivers are operating at an acceptable temperature.

Expected Results
  • Success: The test will pass if all transceivers status are OK: \u2018ok\u2019.
  • Failure: The test will fail if some transceivers are NOT OK.
Examples
anta.tests.hardware:\n  - VerifyTransceiversTemperature:\n
Source code in anta/tests/hardware.py
class VerifyTransceiversTemperature(AntaTest):\n    \"\"\"Verifies if all the transceivers are operating at an acceptable temperature.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all transceivers status are OK: 'ok'.\n    * Failure: The test will fail if some transceivers are NOT OK.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.hardware:\n      - VerifyTransceiversTemperature:\n    ```\n    \"\"\"\n\n    name = \"VerifyTransceiversTemperature\"\n    description = \"Verifies the transceivers temperature.\"\n    categories: ClassVar[list[str]] = [\"hardware\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system environment temperature transceiver\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTransceiversTemperature.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        sensors = command_output.get(\"tempSensors\", \"\")\n        wrong_sensors = {\n            sensor[\"name\"]: {\n                \"hwStatus\": sensor[\"hwStatus\"],\n                \"alertCount\": sensor[\"alertCount\"],\n            }\n            for sensor in sensors\n            if sensor[\"hwStatus\"] != \"ok\" or sensor[\"alertCount\"] != 0\n        }\n        if not wrong_sensors:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following sensors are operating outside the acceptable temperature range or have raised alerts: {wrong_sensors}\")\n
"},{"location":"api/tests.interfaces/","title":"Interfaces","text":""},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyIPProxyARP","title":"VerifyIPProxyARP","text":"

Verifies if Proxy-ARP is enabled for the provided list of interface(s).

Expected Results
  • Success: The test will pass if Proxy-ARP is enabled on the specified interface(s).
  • Failure: The test will fail if Proxy-ARP is disabled on the specified interface(s).
Examples
anta.tests.interfaces:\n  - VerifyIPProxyARP:\n      interfaces:\n        - Ethernet1\n        - Ethernet2\n
Source code in anta/tests/interfaces.py
class VerifyIPProxyARP(AntaTest):\n    \"\"\"Verifies if Proxy-ARP is enabled for the provided list of interface(s).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if Proxy-ARP is enabled on the specified interface(s).\n    * Failure: The test will fail if Proxy-ARP is disabled on the specified interface(s).\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyIPProxyARP:\n          interfaces:\n            - Ethernet1\n            - Ethernet2\n    ```\n    \"\"\"\n\n    name = \"VerifyIPProxyARP\"\n    description = \"Verifies if Proxy ARP is enabled.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show ip interface {intf}\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyIPProxyARP test.\"\"\"\n\n        interfaces: list[str]\n        \"\"\"List of interfaces to be tested.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each interface in the input list.\"\"\"\n        return [template.render(intf=intf) for intf in self.inputs.interfaces]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIPProxyARP.\"\"\"\n        disabled_intf = []\n        for command in self.instance_commands:\n            intf = command.params.intf\n            if not command.json_output[\"interfaces\"][intf][\"proxyArp\"]:\n                disabled_intf.append(intf)\n        if disabled_intf:\n            self.result.is_failure(f\"The following interface(s) have Proxy-ARP disabled: {disabled_intf}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyIPProxyARP-attributes","title":"Inputs","text":"Name Type Description Default interfaces list[str] List of interfaces to be tested. -"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyIllegalLACP","title":"VerifyIllegalLACP","text":"

Verifies there are no illegal LACP packets in all port channels.

Expected Results
  • Success: The test will pass if there are no illegal LACP packets received.
  • Failure: The test will fail if there is at least one illegal LACP packet received.
Examples
anta.tests.interfaces:\n  - VerifyIllegalLACP:\n
Source code in anta/tests/interfaces.py
class VerifyIllegalLACP(AntaTest):\n    \"\"\"Verifies there are no illegal LACP packets in all port channels.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are no illegal LACP packets received.\n    * Failure: The test will fail if there is at least one illegal LACP packet received.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyIllegalLACP:\n    ```\n    \"\"\"\n\n    name = \"VerifyIllegalLACP\"\n    description = \"Verifies there are no illegal LACP packets in all port channels.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show lacp counters all-ports\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIllegalLACP.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        po_with_illegal_lacp: list[dict[str, dict[str, int]]] = []\n        for portchannel, portchannel_dict in command_output[\"portChannels\"].items():\n            po_with_illegal_lacp.extend(\n                {portchannel: interface} for interface, interface_dict in portchannel_dict[\"interfaces\"].items() if interface_dict[\"illegalRxCount\"] != 0\n            )\n        if not po_with_illegal_lacp:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following port-channels have received illegal LACP packets on the following ports: {po_with_illegal_lacp}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceDiscards","title":"VerifyInterfaceDiscards","text":"

Verifies that the interfaces packet discard counters are equal to zero.

Expected Results
  • Success: The test will pass if all interfaces have discard counters equal to zero.
  • Failure: The test will fail if one or more interfaces have non-zero discard counters.
Examples
anta.tests.interfaces:\n  - VerifyInterfaceDiscards:\n
Source code in anta/tests/interfaces.py
class VerifyInterfaceDiscards(AntaTest):\n    \"\"\"Verifies that the interfaces packet discard counters are equal to zero.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all interfaces have discard counters equal to zero.\n    * Failure: The test will fail if one or more interfaces have non-zero discard counters.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfaceDiscards:\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfaceDiscards\"\n    description = \"Verifies there are no interface discard counters.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces counters discards\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfaceDiscards.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        wrong_interfaces: list[dict[str, dict[str, int]]] = []\n        for interface, outer_v in command_output[\"interfaces\"].items():\n            wrong_interfaces.extend({interface: outer_v} for value in outer_v.values() if value > 0)\n        if not wrong_interfaces:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following interfaces have non 0 discard counter(s): {wrong_interfaces}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceErrDisabled","title":"VerifyInterfaceErrDisabled","text":"

Verifies there are no interfaces in the errdisabled state.

Expected Results
  • Success: The test will pass if there are no interfaces in the errdisabled state.
  • Failure: The test will fail if there is at least one interface in the errdisabled state.
Examples
anta.tests.interfaces:\n  - VerifyInterfaceErrDisabled:\n
Source code in anta/tests/interfaces.py
class VerifyInterfaceErrDisabled(AntaTest):\n    \"\"\"Verifies there are no interfaces in the errdisabled state.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are no interfaces in the errdisabled state.\n    * Failure: The test will fail if there is at least one interface in the errdisabled state.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfaceErrDisabled:\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfaceErrDisabled\"\n    description = \"Verifies there are no interfaces in the errdisabled state.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces status\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfaceErrDisabled.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        errdisabled_interfaces = [interface for interface, value in command_output[\"interfaceStatuses\"].items() if value[\"linkStatus\"] == \"errdisabled\"]\n        if errdisabled_interfaces:\n            self.result.is_failure(f\"The following interfaces are in error disabled state: {errdisabled_interfaces}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceErrors","title":"VerifyInterfaceErrors","text":"

Verifies that the interfaces error counters are equal to zero.

Expected Results
  • Success: The test will pass if all interfaces have error counters equal to zero.
  • Failure: The test will fail if one or more interfaces have non-zero error counters.
Examples
anta.tests.interfaces:\n  - VerifyInterfaceErrors:\n
Source code in anta/tests/interfaces.py
class VerifyInterfaceErrors(AntaTest):\n    \"\"\"Verifies that the interfaces error counters are equal to zero.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all interfaces have error counters equal to zero.\n    * Failure: The test will fail if one or more interfaces have non-zero error counters.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfaceErrors:\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfaceErrors\"\n    description = \"Verifies there are no interface error counters.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces counters errors\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfaceErrors.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        wrong_interfaces: list[dict[str, dict[str, int]]] = []\n        for interface, counters in command_output[\"interfaceErrorCounters\"].items():\n            if any(value > 0 for value in counters.values()) and all(interface not in wrong_interface for wrong_interface in wrong_interfaces):\n                wrong_interfaces.append({interface: counters})\n        if not wrong_interfaces:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following interface(s) have non-zero error counters: {wrong_interfaces}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceIPv4","title":"VerifyInterfaceIPv4","text":"

Verifies if an interface is configured with a correct primary and list of optional secondary IPv4 addresses.

Expected Results
  • Success: The test will pass if an interface is configured with a correct primary and secondary IPv4 address.
  • Failure: The test will fail if an interface is not found or the primary and secondary IPv4 addresses do not match with the input.
Examples
anta.tests.interfaces:\n  - VerifyInterfaceIPv4:\n      interfaces:\n        - name: Ethernet2\n          primary_ip: 172.30.11.0/31\n          secondary_ips:\n            - 10.10.10.0/31\n            - 10.10.10.10/31\n
Source code in anta/tests/interfaces.py
class VerifyInterfaceIPv4(AntaTest):\n    \"\"\"Verifies if an interface is configured with a correct primary and list of optional secondary IPv4 addresses.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if an interface is configured with a correct primary and secondary IPv4 address.\n    * Failure: The test will fail if an interface is not found or the primary and secondary IPv4 addresses do not match with the input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfaceIPv4:\n          interfaces:\n            - name: Ethernet2\n              primary_ip: 172.30.11.0/31\n              secondary_ips:\n                - 10.10.10.0/31\n                - 10.10.10.10/31\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfaceIPv4\"\n    description = \"Verifies the interface IPv4 addresses.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show ip interface {interface}\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyInterfaceIPv4 test.\"\"\"\n\n        interfaces: list[InterfaceDetail]\n        \"\"\"List of interfaces with their details.\"\"\"\n\n        class InterfaceDetail(BaseModel):\n            \"\"\"Model for an interface detail.\"\"\"\n\n            name: Interface\n            \"\"\"Name of the interface.\"\"\"\n            primary_ip: IPv4Network\n            \"\"\"Primary IPv4 address in CIDR notation.\"\"\"\n            secondary_ips: list[IPv4Network] | None = None\n            \"\"\"Optional list of secondary IPv4 addresses in CIDR notation.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each interface in the input list.\"\"\"\n        return [template.render(interface=interface.name) for interface in self.inputs.interfaces]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfaceIPv4.\"\"\"\n        self.result.is_success()\n        for command in self.instance_commands:\n            intf = command.params.interface\n            for interface in self.inputs.interfaces:\n                if interface.name == intf:\n                    input_interface_detail = interface\n                    break\n            else:\n                self.result.is_error(f\"Could not find `{intf}` in the input interfaces. {GITHUB_SUGGESTION}\")\n                continue\n\n            input_primary_ip = str(input_interface_detail.primary_ip)\n            failed_messages = []\n\n            # Check if the interface has an IP address configured\n            if not (interface_output := get_value(command.json_output, f\"interfaces.{intf}.interfaceAddress\")):\n                self.result.is_failure(f\"For interface `{intf}`, IP address is not configured.\")\n                continue\n\n            primary_ip = get_value(interface_output, \"primaryIp\")\n\n            # Combine IP address and subnet for primary IP\n            actual_primary_ip = f\"{primary_ip['address']}/{primary_ip['maskLen']}\"\n\n            # Check if the primary IP address matches the input\n            if actual_primary_ip != input_primary_ip:\n                failed_messages.append(f\"The expected primary IP address is `{input_primary_ip}`, but the actual primary IP address is `{actual_primary_ip}`.\")\n\n            if (param_secondary_ips := input_interface_detail.secondary_ips) is not None:\n                input_secondary_ips = sorted([str(network) for network in param_secondary_ips])\n                secondary_ips = get_value(interface_output, \"secondaryIpsOrderedList\")\n\n                # Combine IP address and subnet for secondary IPs\n                actual_secondary_ips = sorted([f\"{secondary_ip['address']}/{secondary_ip['maskLen']}\" for secondary_ip in secondary_ips])\n\n                # Check if the secondary IP address is configured\n                if not actual_secondary_ips:\n                    failed_messages.append(\n                        f\"The expected secondary IP addresses are `{input_secondary_ips}`, but the actual secondary IP address is not configured.\"\n                    )\n\n                # Check if the secondary IP addresses match the input\n                elif actual_secondary_ips != input_secondary_ips:\n                    failed_messages.append(\n                        f\"The expected secondary IP addresses are `{input_secondary_ips}`, but the actual secondary IP addresses are `{actual_secondary_ips}`.\"\n                    )\n\n            if failed_messages:\n                self.result.is_failure(f\"For interface `{intf}`, \" + \" \".join(failed_messages))\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceIPv4-attributes","title":"Inputs","text":"Name Type Description Default interfaces list[InterfaceDetail] List of interfaces with their details. -"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceIPv4-attributes","title":"InterfaceDetail","text":"Name Type Description Default name Interface Name of the interface. - primary_ip IPv4Network Primary IPv4 address in CIDR notation. - secondary_ips list[IPv4Network] | None Optional list of secondary IPv4 addresses in CIDR notation. None"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceUtilization","title":"VerifyInterfaceUtilization","text":"

Verifies that the utilization of interfaces is below a certain threshold.

Load interval (default to 5 minutes) is defined in device configuration. This test has been implemented for full-duplex interfaces only.

Expected Results
  • Success: The test will pass if all interfaces have a usage below the threshold.
  • Failure: The test will fail if one or more interfaces have a usage above the threshold.
  • Error: The test will error out if the device has at least one non full-duplex interface.
Examples
anta.tests.interfaces:\n  - VerifyInterfaceUtilization:\n      threshold: 70.0\n
Source code in anta/tests/interfaces.py
class VerifyInterfaceUtilization(AntaTest):\n    \"\"\"Verifies that the utilization of interfaces is below a certain threshold.\n\n    Load interval (default to 5 minutes) is defined in device configuration.\n    This test has been implemented for full-duplex interfaces only.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all interfaces have a usage below the threshold.\n    * Failure: The test will fail if one or more interfaces have a usage above the threshold.\n    * Error: The test will error out if the device has at least one non full-duplex interface.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfaceUtilization:\n          threshold: 70.0\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfaceUtilization\"\n    description = \"Verifies that the utilization of interfaces is below a certain threshold.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"show interfaces counters rates\", revision=1),\n        AntaCommand(command=\"show interfaces\", revision=1),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyInterfaceUtilization test.\"\"\"\n\n        threshold: Percent = 75.0\n        \"\"\"Interface utilization threshold above which the test will fail. Defaults to 75%.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfaceUtilization.\"\"\"\n        duplex_full = \"duplexFull\"\n        failed_interfaces: dict[str, dict[str, float]] = {}\n        rates = self.instance_commands[0].json_output\n        interfaces = self.instance_commands[1].json_output\n\n        for intf, rate in rates[\"interfaces\"].items():\n            # The utilization logic has been implemented for full-duplex interfaces only\n            if ((duplex := (interface := interfaces[\"interfaces\"][intf]).get(\"duplex\", None)) is not None and duplex != duplex_full) or (\n                (members := interface.get(\"memberInterfaces\", None)) is not None and any(stats[\"duplex\"] != duplex_full for stats in members.values())\n            ):\n                self.result.is_error(f\"Interface {intf} or one of its member interfaces is not Full-Duplex. VerifyInterfaceUtilization has not been implemented.\")\n                return\n\n            if (bandwidth := interfaces[\"interfaces\"][intf][\"bandwidth\"]) == 0:\n                self.logger.debug(\"Interface %s has been ignored due to null bandwidth value\", intf)\n                continue\n\n            for bps_rate in (\"inBpsRate\", \"outBpsRate\"):\n                usage = rate[bps_rate] / bandwidth * 100\n                if usage > self.inputs.threshold:\n                    failed_interfaces.setdefault(intf, {})[bps_rate] = usage\n\n        if not failed_interfaces:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following interfaces have a usage > {self.inputs.threshold}%: {failed_interfaces}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfaceUtilization-attributes","title":"Inputs","text":"Name Type Description Default threshold Percent Interface utilization threshold above which the test will fail. Defaults to 75%. 75.0"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfacesSpeed","title":"VerifyInterfacesSpeed","text":"

Verifies the speed, lanes, auto-negotiation status, and mode as full duplex for interfaces.

  • If the auto-negotiation status is set to True, verifies that auto-negotiation is successful, the mode is full duplex and the speed/lanes match the input.
  • If the auto-negotiation status is set to False, verifies that the mode is full duplex and the speed/lanes match the input.
Expected Results
  • Success: The test will pass if an interface is configured correctly with the specified speed, lanes, auto-negotiation status, and mode as full duplex.
  • Failure: The test will fail if an interface is not found, if the speed, lanes, and auto-negotiation status do not match the input, or mode is not full duplex.
Examples
anta.tests.interfaces:\n  - VerifyInterfacesSpeed:\n      interfaces:\n        - name: Ethernet2\n          auto: False\n          speed: 10\n        - name: Eth3\n          auto: True\n          speed: 100\n          lanes: 1\n        - name: Eth2\n          auto: False\n          speed: 2.5\n
Source code in anta/tests/interfaces.py
class VerifyInterfacesSpeed(AntaTest):\n    \"\"\"Verifies the speed, lanes, auto-negotiation status, and mode as full duplex for interfaces.\n\n    - If the auto-negotiation status is set to True, verifies that auto-negotiation is successful, the mode is full duplex and the speed/lanes match the input.\n    - If the auto-negotiation status is set to False, verifies that the mode is full duplex and the speed/lanes match the input.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if an interface is configured correctly with the specified speed, lanes, auto-negotiation status, and mode as full duplex.\n    * Failure: The test will fail if an interface is not found, if the speed, lanes, and auto-negotiation status do not match the input, or mode is not full duplex.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfacesSpeed:\n          interfaces:\n            - name: Ethernet2\n              auto: False\n              speed: 10\n            - name: Eth3\n              auto: True\n              speed: 100\n              lanes: 1\n            - name: Eth2\n              auto: False\n              speed: 2.5\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfacesSpeed\"\n    description = \"Verifies the speed, lanes, auto-negotiation status, and mode as full duplex for interfaces.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Inputs for the VerifyInterfacesSpeed test.\"\"\"\n\n        interfaces: list[InterfaceDetail]\n        \"\"\"List of interfaces to be tested\"\"\"\n\n        class InterfaceDetail(BaseModel):\n            \"\"\"Detail of an interface.\"\"\"\n\n            name: EthernetInterface\n            \"\"\"The name of the interface.\"\"\"\n            auto: bool\n            \"\"\"The auto-negotiation status of the interface.\"\"\"\n            speed: float = Field(ge=1, le=1000)\n            \"\"\"The speed of the interface in Gigabits per second. Valid range is 1 to 1000.\"\"\"\n            lanes: None | int = Field(None, ge=1, le=8)\n            \"\"\"The number of lanes in the interface. Valid range is 1 to 8. This field is optional.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfacesSpeed.\"\"\"\n        self.result.is_success()\n        command_output = self.instance_commands[0].json_output\n\n        # Iterate over all the interfaces\n        for interface in self.inputs.interfaces:\n            intf = interface.name\n\n            # Check if interface exists\n            if not (interface_output := get_value(command_output, f\"interfaces.{intf}\")):\n                self.result.is_failure(f\"Interface `{intf}` is not found.\")\n                continue\n\n            auto_negotiation = interface_output.get(\"autoNegotiate\")\n            actual_lanes = interface_output.get(\"lanes\")\n\n            # Collecting actual interface details\n            actual_interface_output = {\n                \"auto negotiation\": auto_negotiation if interface.auto is True else None,\n                \"duplex mode\": interface_output.get(\"duplex\"),\n                \"speed\": interface_output.get(\"bandwidth\"),\n                \"lanes\": actual_lanes if interface.lanes is not None else None,\n            }\n\n            # Forming expected interface details\n            expected_interface_output = {\n                \"auto negotiation\": \"success\" if interface.auto is True else None,\n                \"duplex mode\": \"duplexFull\",\n                \"speed\": interface.speed * BPS_GBPS_CONVERSIONS,\n                \"lanes\": interface.lanes,\n            }\n\n            # Forming failure message\n            if actual_interface_output != expected_interface_output:\n                for output in [actual_interface_output, expected_interface_output]:\n                    # Convert speed to Gbps for readability\n                    if output[\"speed\"] is not None:\n                        output[\"speed\"] = f\"{custom_division(output['speed'], BPS_GBPS_CONVERSIONS)}Gbps\"\n                failed_log = get_failed_logs(expected_interface_output, actual_interface_output)\n                self.result.is_failure(f\"For interface {intf}:{failed_log}\\n\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfacesSpeed-attributes","title":"Inputs","text":"Name Type Description Default interfaces list[InterfaceDetail] List of interfaces to be tested -"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfacesSpeed-attributes","title":"InterfaceDetail","text":"Name Type Description Default name EthernetInterface The name of the interface. - auto bool The auto-negotiation status of the interface. - speed float The speed of the interface in Gigabits per second. Valid range is 1 to 1000. Field(ge=1, le=1000) lanes None | int The number of lanes in the interface. Valid range is 1 to 8. This field is optional. Field(None, ge=1, le=8)"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfacesStatus","title":"VerifyInterfacesStatus","text":"

Verifies if the provided list of interfaces are all in the expected state.

  • If line protocol status is provided, prioritize checking against both status and line protocol status
  • If line protocol status is not provided and interface status is \u201cup\u201d, expect both status and line protocol to be \u201cup\u201d
  • If interface status is not \u201cup\u201d, check only the interface status without considering line protocol status
Expected Results
  • Success: The test will pass if the provided interfaces are all in the expected state.
  • Failure: The test will fail if any interface is not in the expected state.
Examples
anta.tests.interfaces:\n  - VerifyInterfacesStatus:\n      interfaces:\n        - name: Ethernet1\n          status: up\n        - name: Port-Channel100\n          status: down\n          line_protocol_status: lowerLayerDown\n        - name: Ethernet49/1\n          status: adminDown\n          line_protocol_status: notPresent\n
Source code in anta/tests/interfaces.py
class VerifyInterfacesStatus(AntaTest):\n    \"\"\"Verifies if the provided list of interfaces are all in the expected state.\n\n    - If line protocol status is provided, prioritize checking against both status and line protocol status\n    - If line protocol status is not provided and interface status is \"up\", expect both status and line protocol to be \"up\"\n    - If interface status is not \"up\", check only the interface status without considering line protocol status\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided interfaces are all in the expected state.\n    * Failure: The test will fail if any interface is not in the expected state.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyInterfacesStatus:\n          interfaces:\n            - name: Ethernet1\n              status: up\n            - name: Port-Channel100\n              status: down\n              line_protocol_status: lowerLayerDown\n            - name: Ethernet49/1\n              status: adminDown\n              line_protocol_status: notPresent\n    ```\n    \"\"\"\n\n    name = \"VerifyInterfacesStatus\"\n    description = \"Verifies the status of the provided interfaces.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces description\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyInterfacesStatus test.\"\"\"\n\n        interfaces: list[InterfaceState]\n        \"\"\"List of interfaces with their expected state.\"\"\"\n\n        class InterfaceState(BaseModel):\n            \"\"\"Model for an interface state.\"\"\"\n\n            name: Interface\n            \"\"\"Interface to validate.\"\"\"\n            status: Literal[\"up\", \"down\", \"adminDown\"]\n            \"\"\"Expected status of the interface.\"\"\"\n            line_protocol_status: Literal[\"up\", \"down\", \"testing\", \"unknown\", \"dormant\", \"notPresent\", \"lowerLayerDown\"] | None = None\n            \"\"\"Expected line protocol status of the interface.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyInterfacesStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        self.result.is_success()\n\n        intf_not_configured = []\n        intf_wrong_state = []\n\n        for interface in self.inputs.interfaces:\n            if (intf_status := get_value(command_output[\"interfaceDescriptions\"], interface.name, separator=\"..\")) is None:\n                intf_not_configured.append(interface.name)\n                continue\n\n            status = \"up\" if intf_status[\"interfaceStatus\"] in {\"up\", \"connected\"} else intf_status[\"interfaceStatus\"]\n            proto = \"up\" if intf_status[\"lineProtocolStatus\"] in {\"up\", \"connected\"} else intf_status[\"lineProtocolStatus\"]\n\n            # If line protocol status is provided, prioritize checking against both status and line protocol status\n            if interface.line_protocol_status:\n                if interface.status != status or interface.line_protocol_status != proto:\n                    intf_wrong_state.append(f\"{interface.name} is {status}/{proto}\")\n\n            # If line protocol status is not provided and interface status is \"up\", expect both status and proto to be \"up\"\n            # If interface status is not \"up\", check only the interface status without considering line protocol status\n            elif (interface.status == \"up\" and (status != \"up\" or proto != \"up\")) or (interface.status != status):\n                intf_wrong_state.append(f\"{interface.name} is {status}/{proto}\")\n\n        if intf_not_configured:\n            self.result.is_failure(f\"The following interface(s) are not configured: {intf_not_configured}\")\n\n        if intf_wrong_state:\n            self.result.is_failure(f\"The following interface(s) are not in the expected state: {intf_wrong_state}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfacesStatus-attributes","title":"Inputs","text":"Name Type Description Default interfaces list[InterfaceState] List of interfaces with their expected state. -"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyInterfacesStatus-attributes","title":"InterfaceState","text":"Name Type Description Default name Interface Interface to validate. - status Literal['up', 'down', 'adminDown'] Expected status of the interface. - line_protocol_status Literal['up', 'down', 'testing', 'unknown', 'dormant', 'notPresent', 'lowerLayerDown'] | None Expected line protocol status of the interface. None"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyIpVirtualRouterMac","title":"VerifyIpVirtualRouterMac","text":"

Verifies the IP virtual router MAC address.

Expected Results
  • Success: The test will pass if the IP virtual router MAC address matches the input.
  • Failure: The test will fail if the IP virtual router MAC address does not match the input.
Examples
anta.tests.interfaces:\n  - VerifyIpVirtualRouterMac:\n      mac_address: 00:1c:73:00:dc:01\n
Source code in anta/tests/interfaces.py
class VerifyIpVirtualRouterMac(AntaTest):\n    \"\"\"Verifies the IP virtual router MAC address.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the IP virtual router MAC address matches the input.\n    * Failure: The test will fail if the IP virtual router MAC address does not match the input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyIpVirtualRouterMac:\n          mac_address: 00:1c:73:00:dc:01\n    ```\n    \"\"\"\n\n    name = \"VerifyIpVirtualRouterMac\"\n    description = \"Verifies the IP virtual router MAC address.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip virtual-router\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyIpVirtualRouterMac test.\"\"\"\n\n        mac_address: MacAddress\n        \"\"\"IP virtual router MAC address.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIpVirtualRouterMac.\"\"\"\n        command_output = self.instance_commands[0].json_output[\"virtualMacs\"]\n        mac_address_found = get_item(command_output, \"macAddress\", self.inputs.mac_address)\n\n        if mac_address_found is None:\n            self.result.is_failure(f\"IP virtual router MAC address `{self.inputs.mac_address}` is not configured.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyIpVirtualRouterMac-attributes","title":"Inputs","text":"Name Type Description Default mac_address MacAddress IP virtual router MAC address. -"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyL2MTU","title":"VerifyL2MTU","text":"

Verifies the global layer 2 Maximum Transfer Unit (MTU) for all L2 interfaces.

Test that L2 interfaces are configured with the correct MTU. It supports Ethernet, Port Channel and VLAN interfaces. You can define a global MTU to check and also an MTU per interface and also ignored some interfaces.

Expected Results
  • Success: The test will pass if all layer 2 interfaces have the proper MTU configured.
  • Failure: The test will fail if one or many layer 2 interfaces have the wrong MTU configured.
Examples
anta.tests.interfaces:\n  - VerifyL2MTU:\n      mtu: 1500\n      ignored_interfaces:\n        - Management1\n        - Vxlan1\n      specific_mtu:\n        - Ethernet1/1: 1500\n
Source code in anta/tests/interfaces.py
class VerifyL2MTU(AntaTest):\n    \"\"\"Verifies the global layer 2 Maximum Transfer Unit (MTU) for all L2 interfaces.\n\n    Test that L2 interfaces are configured with the correct MTU. It supports Ethernet, Port Channel and VLAN interfaces.\n    You can define a global MTU to check and also an MTU per interface and also ignored some interfaces.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all layer 2 interfaces have the proper MTU configured.\n    * Failure: The test will fail if one or many layer 2 interfaces have the wrong MTU configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyL2MTU:\n          mtu: 1500\n          ignored_interfaces:\n            - Management1\n            - Vxlan1\n          specific_mtu:\n            - Ethernet1/1: 1500\n    ```\n    \"\"\"\n\n    name = \"VerifyL2MTU\"\n    description = \"Verifies the global L2 MTU of all L2 interfaces.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyL2MTU test.\"\"\"\n\n        mtu: int = 9214\n        \"\"\"Default MTU we should have configured on all non-excluded interfaces. Defaults to 9214.\"\"\"\n        ignored_interfaces: list[str] = Field(default=[\"Management\", \"Loopback\", \"Vxlan\", \"Tunnel\"])\n        \"\"\"A list of L2 interfaces to ignore. Defaults to [\"Management\", \"Loopback\", \"Vxlan\", \"Tunnel\"]\"\"\"\n        specific_mtu: list[dict[str, int]] = Field(default=[])\n        \"\"\"A list of dictionary of L2 interfaces with their specific MTU configured\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyL2MTU.\"\"\"\n        # Parameter to save incorrect interface settings\n        wrong_l2mtu_intf: list[dict[str, int]] = []\n        command_output = self.instance_commands[0].json_output\n        # Set list of interfaces with specific settings\n        specific_interfaces: list[str] = []\n        if self.inputs.specific_mtu:\n            for d in self.inputs.specific_mtu:\n                specific_interfaces.extend(d)\n        for interface, values in command_output[\"interfaces\"].items():\n            catch_interface = re.findall(r\"^[e,p][a-zA-Z]+[-,a-zA-Z]*\\d+\\/*\\d*\", interface, re.IGNORECASE)\n            if len(catch_interface) and catch_interface[0] not in self.inputs.ignored_interfaces and values[\"forwardingModel\"] == \"bridged\":\n                if interface in specific_interfaces:\n                    wrong_l2mtu_intf.extend({interface: values[\"mtu\"]} for custom_data in self.inputs.specific_mtu if values[\"mtu\"] != custom_data[interface])\n                # Comparison with generic setting\n                elif values[\"mtu\"] != self.inputs.mtu:\n                    wrong_l2mtu_intf.append({interface: values[\"mtu\"]})\n        if wrong_l2mtu_intf:\n            self.result.is_failure(f\"Some L2 interfaces do not have correct MTU configured:\\n{wrong_l2mtu_intf}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyL2MTU-attributes","title":"Inputs","text":"Name Type Description Default mtu int Default MTU we should have configured on all non-excluded interfaces. Defaults to 9214. 9214 ignored_interfaces list[str] A list of L2 interfaces to ignore. Defaults to [\"Management\", \"Loopback\", \"Vxlan\", \"Tunnel\"] Field(default=['Management', 'Loopback', 'Vxlan', 'Tunnel']) specific_mtu list[dict[str, int]] A list of dictionary of L2 interfaces with their specific MTU configured Field(default=[])"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyL3MTU","title":"VerifyL3MTU","text":"

Verifies the global layer 3 Maximum Transfer Unit (MTU) for all L3 interfaces.

Test that L3 interfaces are configured with the correct MTU. It supports Ethernet, Port Channel and VLAN interfaces.

You can define a global MTU to check, or an MTU per interface and you can also ignored some interfaces.

Expected Results
  • Success: The test will pass if all layer 3 interfaces have the proper MTU configured.
  • Failure: The test will fail if one or many layer 3 interfaces have the wrong MTU configured.
Examples
anta.tests.interfaces:\n  - VerifyL3MTU:\n      mtu: 1500\n      ignored_interfaces:\n          - Vxlan1\n      specific_mtu:\n          - Ethernet1: 2500\n
Source code in anta/tests/interfaces.py
class VerifyL3MTU(AntaTest):\n    \"\"\"Verifies the global layer 3 Maximum Transfer Unit (MTU) for all L3 interfaces.\n\n    Test that L3 interfaces are configured with the correct MTU. It supports Ethernet, Port Channel and VLAN interfaces.\n\n    You can define a global MTU to check, or an MTU per interface and you can also ignored some interfaces.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all layer 3 interfaces have the proper MTU configured.\n    * Failure: The test will fail if one or many layer 3 interfaces have the wrong MTU configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyL3MTU:\n          mtu: 1500\n          ignored_interfaces:\n              - Vxlan1\n          specific_mtu:\n              - Ethernet1: 2500\n    ```\n    \"\"\"\n\n    name = \"VerifyL3MTU\"\n    description = \"Verifies the global L3 MTU of all L3 interfaces.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyL3MTU test.\"\"\"\n\n        mtu: int = 1500\n        \"\"\"Default MTU we should have configured on all non-excluded interfaces. Defaults to 1500.\"\"\"\n        ignored_interfaces: list[str] = Field(default=[\"Management\", \"Loopback\", \"Vxlan\", \"Tunnel\"])\n        \"\"\"A list of L3 interfaces to ignore\"\"\"\n        specific_mtu: list[dict[str, int]] = Field(default=[])\n        \"\"\"A list of dictionary of L3 interfaces with their specific MTU configured\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyL3MTU.\"\"\"\n        # Parameter to save incorrect interface settings\n        wrong_l3mtu_intf: list[dict[str, int]] = []\n        command_output = self.instance_commands[0].json_output\n        # Set list of interfaces with specific settings\n        specific_interfaces: list[str] = []\n        if self.inputs.specific_mtu:\n            for d in self.inputs.specific_mtu:\n                specific_interfaces.extend(d)\n        for interface, values in command_output[\"interfaces\"].items():\n            if re.findall(r\"[a-z]+\", interface, re.IGNORECASE)[0] not in self.inputs.ignored_interfaces and values[\"forwardingModel\"] == \"routed\":\n                if interface in specific_interfaces:\n                    wrong_l3mtu_intf.extend({interface: values[\"mtu\"]} for custom_data in self.inputs.specific_mtu if values[\"mtu\"] != custom_data[interface])\n                # Comparison with generic setting\n                elif values[\"mtu\"] != self.inputs.mtu:\n                    wrong_l3mtu_intf.append({interface: values[\"mtu\"]})\n        if wrong_l3mtu_intf:\n            self.result.is_failure(f\"Some interfaces do not have correct MTU configured:\\n{wrong_l3mtu_intf}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyL3MTU-attributes","title":"Inputs","text":"Name Type Description Default mtu int Default MTU we should have configured on all non-excluded interfaces. Defaults to 1500. 1500 ignored_interfaces list[str] A list of L3 interfaces to ignore Field(default=['Management', 'Loopback', 'Vxlan', 'Tunnel']) specific_mtu list[dict[str, int]] A list of dictionary of L3 interfaces with their specific MTU configured Field(default=[])"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyLoopbackCount","title":"VerifyLoopbackCount","text":"

Verifies that the device has the expected number of loopback interfaces and all are operational.

Expected Results
  • Success: The test will pass if the device has the correct number of loopback interfaces and none are down.
  • Failure: The test will fail if the loopback interface count is incorrect or any are non-operational.
Examples
anta.tests.interfaces:\n  - VerifyLoopbackCount:\n      number: 3\n
Source code in anta/tests/interfaces.py
class VerifyLoopbackCount(AntaTest):\n    \"\"\"Verifies that the device has the expected number of loopback interfaces and all are operational.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device has the correct number of loopback interfaces and none are down.\n    * Failure: The test will fail if the loopback interface count is incorrect or any are non-operational.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyLoopbackCount:\n          number: 3\n    ```\n    \"\"\"\n\n    name = \"VerifyLoopbackCount\"\n    description = \"Verifies the number of loopback interfaces and their status.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip interface brief\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyLoopbackCount test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"Number of loopback interfaces expected to be present.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoopbackCount.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        loopback_count = 0\n        down_loopback_interfaces = []\n        for interface in command_output[\"interfaces\"]:\n            interface_dict = command_output[\"interfaces\"][interface]\n            if \"Loopback\" in interface:\n                loopback_count += 1\n                if not (interface_dict[\"lineProtocolStatus\"] == \"up\" and interface_dict[\"interfaceStatus\"] == \"connected\"):\n                    down_loopback_interfaces.append(interface)\n        if loopback_count == self.inputs.number and len(down_loopback_interfaces) == 0:\n            self.result.is_success()\n        else:\n            self.result.is_failure()\n            if loopback_count != self.inputs.number:\n                self.result.is_failure(f\"Found {loopback_count} Loopbacks when expecting {self.inputs.number}\")\n            elif len(down_loopback_interfaces) != 0:  # pragma: no branch\n                self.result.is_failure(f\"The following Loopbacks are not up: {down_loopback_interfaces}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyLoopbackCount-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger Number of loopback interfaces expected to be present. -"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyPortChannels","title":"VerifyPortChannels","text":"

Verifies there are no inactive ports in all port channels.

Expected Results
  • Success: The test will pass if there are no inactive ports in all port channels.
  • Failure: The test will fail if there is at least one inactive port in a port channel.
Examples
anta.tests.interfaces:\n  - VerifyPortChannels:\n
Source code in anta/tests/interfaces.py
class VerifyPortChannels(AntaTest):\n    \"\"\"Verifies there are no inactive ports in all port channels.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are no inactive ports in all port channels.\n    * Failure: The test will fail if there is at least one inactive port in a port channel.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyPortChannels:\n    ```\n    \"\"\"\n\n    name = \"VerifyPortChannels\"\n    description = \"Verifies there are no inactive ports in all port channels.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show port-channel\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPortChannels.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        po_with_inactive_ports: list[dict[str, str]] = []\n        for portchannel, portchannel_dict in command_output[\"portChannels\"].items():\n            if len(portchannel_dict[\"inactivePorts\"]) != 0:\n                po_with_inactive_ports.extend({portchannel: portchannel_dict[\"inactivePorts\"]})\n        if not po_with_inactive_ports:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following port-channels have inactive port(s): {po_with_inactive_ports}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifySVI","title":"VerifySVI","text":"

Verifies the status of all SVIs.

Expected Results
  • Success: The test will pass if all SVIs are up.
  • Failure: The test will fail if one or many SVIs are not up.
Examples
anta.tests.interfaces:\n  - VerifySVI:\n
Source code in anta/tests/interfaces.py
class VerifySVI(AntaTest):\n    \"\"\"Verifies the status of all SVIs.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all SVIs are up.\n    * Failure: The test will fail if one or many SVIs are not up.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifySVI:\n    ```\n    \"\"\"\n\n    name = \"VerifySVI\"\n    description = \"Verifies the status of all SVIs.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip interface brief\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySVI.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        down_svis = []\n        for interface in command_output[\"interfaces\"]:\n            interface_dict = command_output[\"interfaces\"][interface]\n            if \"Vlan\" in interface and not (interface_dict[\"lineProtocolStatus\"] == \"up\" and interface_dict[\"interfaceStatus\"] == \"connected\"):\n                down_svis.append(interface)\n        if len(down_svis) == 0:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following SVIs are not up: {down_svis}\")\n
"},{"location":"api/tests.interfaces/#anta.tests.interfaces.VerifyStormControlDrops","title":"VerifyStormControlDrops","text":"

Verifies there are no interface storm-control drop counters.

Expected Results
  • Success: The test will pass if there are no storm-control drop counters.
  • Failure: The test will fail if there is at least one storm-control drop counter.
Examples
anta.tests.interfaces:\n  - VerifyStormControlDrops:\n
Source code in anta/tests/interfaces.py
class VerifyStormControlDrops(AntaTest):\n    \"\"\"Verifies there are no interface storm-control drop counters.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are no storm-control drop counters.\n    * Failure: The test will fail if there is at least one storm-control drop counter.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.interfaces:\n      - VerifyStormControlDrops:\n    ```\n    \"\"\"\n\n    name = \"VerifyStormControlDrops\"\n    description = \"Verifies there are no interface storm-control drop counters.\"\n    categories: ClassVar[list[str]] = [\"interfaces\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show storm-control\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyStormControlDrops.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        storm_controlled_interfaces: dict[str, dict[str, Any]] = {}\n        for interface, interface_dict in command_output[\"interfaces\"].items():\n            for traffic_type, traffic_type_dict in interface_dict[\"trafficTypes\"].items():\n                if \"drop\" in traffic_type_dict and traffic_type_dict[\"drop\"] != 0:\n                    storm_controlled_interface_dict = storm_controlled_interfaces.setdefault(interface, {})\n                    storm_controlled_interface_dict.update({traffic_type: traffic_type_dict[\"drop\"]})\n        if not storm_controlled_interfaces:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following interfaces have none 0 storm-control drop counters {storm_controlled_interfaces}\")\n
"},{"location":"api/tests.lanz/","title":"LANZ","text":""},{"location":"api/tests.lanz/#anta.tests.lanz.VerifyLANZ","title":"VerifyLANZ","text":"

Verifies if LANZ (Latency Analyzer) is enabled.

Expected Results
  • Success: The test will pass if LANZ is enabled.
  • Failure: The test will fail if LANZ is disabled.
Examples
anta.tests.lanz:\n  - VerifyLANZ:\n
Source code in anta/tests/lanz.py
class VerifyLANZ(AntaTest):\n    \"\"\"Verifies if LANZ (Latency Analyzer) is enabled.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if LANZ is enabled.\n    * Failure: The test will fail if LANZ is disabled.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.lanz:\n      - VerifyLANZ:\n    ```\n    \"\"\"\n\n    name = \"VerifyLANZ\"\n    description = \"Verifies if LANZ is enabled.\"\n    categories: ClassVar[list[str]] = [\"lanz\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show queue-monitor length status\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLANZ.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        if command_output[\"lanzEnabled\"] is not True:\n            self.result.is_failure(\"LANZ is not enabled\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.logging/","title":"Logging","text":""},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingAccounting","title":"VerifyLoggingAccounting","text":"

Verifies if AAA accounting logs are generated.

Expected Results
  • Success: The test will pass if AAA accounting logs are generated.
  • Failure: The test will fail if AAA accounting logs are NOT generated.
Examples
anta.tests.logging:\n  - VerifyLoggingAccounting:\n
Source code in anta/tests/logging.py
class VerifyLoggingAccounting(AntaTest):\n    \"\"\"Verifies if AAA accounting logs are generated.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if AAA accounting logs are generated.\n    * Failure: The test will fail if AAA accounting logs are NOT generated.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingAccounting:\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingAccounting\"\n    description = \"Verifies if AAA accounting logs are generated.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show aaa accounting logs | tail\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingAccounting.\"\"\"\n        pattern = r\"cmd=show aaa accounting logs\"\n        output = self.instance_commands[0].text_output\n        if re.search(pattern, output):\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"AAA accounting logs are not generated\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingErrors","title":"VerifyLoggingErrors","text":"

Verifies there are no syslog messages with a severity of ERRORS or higher.

Expected Results
  • Success: The test will pass if there are NO syslog messages with a severity of ERRORS or higher.
  • Failure: The test will fail if ERRORS or higher syslog messages are present.
Examples
anta.tests.logging:\n  - VerifyLoggingErrors:\n
Source code in anta/tests/logging.py
class VerifyLoggingErrors(AntaTest):\n    \"\"\"Verifies there are no syslog messages with a severity of ERRORS or higher.\n\n    Expected Results\n    ----------------\n      * Success: The test will pass if there are NO syslog messages with a severity of ERRORS or higher.\n      * Failure: The test will fail if ERRORS or higher syslog messages are present.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingErrors:\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingErrors\"\n    description = \"Verifies there are no syslog messages with a severity of ERRORS or higher.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show logging threshold errors\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingErrors.\"\"\"\n        command_output = self.instance_commands[0].text_output\n\n        if len(command_output) == 0:\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"Device has reported syslog messages with a severity of ERRORS or higher\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingHostname","title":"VerifyLoggingHostname","text":"

Verifies if logs are generated with the device FQDN.

Expected Results
  • Success: The test will pass if logs are generated with the device FQDN.
  • Failure: The test will fail if logs are NOT generated with the device FQDN.
Examples
anta.tests.logging:\n  - VerifyLoggingHostname:\n
Source code in anta/tests/logging.py
class VerifyLoggingHostname(AntaTest):\n    \"\"\"Verifies if logs are generated with the device FQDN.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if logs are generated with the device FQDN.\n    * Failure: The test will fail if logs are NOT generated with the device FQDN.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingHostname:\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingHostname\"\n    description = \"Verifies if logs are generated with the device FQDN.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"show hostname\", revision=1),\n        AntaCommand(command=\"send log level informational message ANTA VerifyLoggingHostname validation\", ofmt=\"text\"),\n        AntaCommand(command=\"show logging informational last 30 seconds | grep ANTA\", ofmt=\"text\", use_cache=False),\n    ]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingHostname.\"\"\"\n        output_hostname = self.instance_commands[0].json_output\n        output_logging = self.instance_commands[2].text_output\n        fqdn = output_hostname[\"fqdn\"]\n        lines = output_logging.strip().split(\"\\n\")[::-1]\n        log_pattern = r\"ANTA VerifyLoggingHostname validation\"\n        last_line_with_pattern = \"\"\n        for line in lines:\n            if re.search(log_pattern, line):\n                last_line_with_pattern = line\n                break\n        if fqdn in last_line_with_pattern:\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"Logs are not generated with the device FQDN\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingHosts","title":"VerifyLoggingHosts","text":"

Verifies logging hosts (syslog servers) for a specified VRF.

Expected Results
  • Success: The test will pass if the provided syslog servers are configured in the specified VRF.
  • Failure: The test will fail if the provided syslog servers are NOT configured in the specified VRF.
Examples
anta.tests.logging:\n  - VerifyLoggingHosts:\n      hosts:\n        - 1.1.1.1\n        - 2.2.2.2\n      vrf: default\n
Source code in anta/tests/logging.py
class VerifyLoggingHosts(AntaTest):\n    \"\"\"Verifies logging hosts (syslog servers) for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided syslog servers are configured in the specified VRF.\n    * Failure: The test will fail if the provided syslog servers are NOT configured in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingHosts:\n          hosts:\n            - 1.1.1.1\n            - 2.2.2.2\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingHosts\"\n    description = \"Verifies logging hosts (syslog servers) for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show logging\", ofmt=\"text\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyLoggingHosts test.\"\"\"\n\n        hosts: list[IPv4Address]\n        \"\"\"List of hosts (syslog servers) IP addresses.\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF to transport log messages. Defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingHosts.\"\"\"\n        output = self.instance_commands[0].text_output\n        not_configured = []\n        for host in self.inputs.hosts:\n            pattern = rf\"Logging to '{host!s}'.*VRF {self.inputs.vrf}\"\n            if not re.search(pattern, _get_logging_states(self.logger, output)):\n                not_configured.append(str(host))\n\n        if not not_configured:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Syslog servers {not_configured} are not configured in VRF {self.inputs.vrf}\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingHosts-attributes","title":"Inputs","text":"Name Type Description Default hosts list[IPv4Address] List of hosts (syslog servers) IP addresses. - vrf str The name of the VRF to transport log messages. Defaults to `default`. 'default'"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingLogsGeneration","title":"VerifyLoggingLogsGeneration","text":"

Verifies if logs are generated.

Expected Results
  • Success: The test will pass if logs are generated.
  • Failure: The test will fail if logs are NOT generated.
Examples
anta.tests.logging:\n  - VerifyLoggingLogsGeneration:\n
Source code in anta/tests/logging.py
class VerifyLoggingLogsGeneration(AntaTest):\n    \"\"\"Verifies if logs are generated.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if logs are generated.\n    * Failure: The test will fail if logs are NOT generated.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingLogsGeneration:\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingLogsGeneration\"\n    description = \"Verifies if logs are generated.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"send log level informational message ANTA VerifyLoggingLogsGeneration validation\", ofmt=\"text\"),\n        AntaCommand(command=\"show logging informational last 30 seconds | grep ANTA\", ofmt=\"text\", use_cache=False),\n    ]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingLogsGeneration.\"\"\"\n        log_pattern = r\"ANTA VerifyLoggingLogsGeneration validation\"\n        output = self.instance_commands[1].text_output\n        lines = output.strip().split(\"\\n\")[::-1]\n        for line in lines:\n            if re.search(log_pattern, line):\n                self.result.is_success()\n                return\n        self.result.is_failure(\"Logs are not generated\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingPersistent","title":"VerifyLoggingPersistent","text":"

Verifies if logging persistent is enabled and logs are saved in flash.

Expected Results
  • Success: The test will pass if logging persistent is enabled and logs are in flash.
  • Failure: The test will fail if logging persistent is disabled or no logs are saved in flash.
Examples
anta.tests.logging:\n  - VerifyLoggingPersistent:\n
Source code in anta/tests/logging.py
class VerifyLoggingPersistent(AntaTest):\n    \"\"\"Verifies if logging persistent is enabled and logs are saved in flash.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if logging persistent is enabled and logs are in flash.\n    * Failure: The test will fail if logging persistent is disabled or no logs are saved in flash.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingPersistent:\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingPersistent\"\n    description = \"Verifies if logging persistent is enabled and logs are saved in flash.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"show logging\", ofmt=\"text\"),\n        AntaCommand(command=\"dir flash:/persist/messages\", ofmt=\"text\"),\n    ]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingPersistent.\"\"\"\n        self.result.is_success()\n        log_output = self.instance_commands[0].text_output\n        dir_flash_output = self.instance_commands[1].text_output\n        if \"Persistent logging: disabled\" in _get_logging_states(self.logger, log_output):\n            self.result.is_failure(\"Persistent logging is disabled\")\n            return\n        pattern = r\"-rw-\\s+(\\d+)\"\n        persist_logs = re.search(pattern, dir_flash_output)\n        if not persist_logs or int(persist_logs.group(1)) == 0:\n            self.result.is_failure(\"No persistent logs are saved in flash\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingSourceIntf","title":"VerifyLoggingSourceIntf","text":"

Verifies logging source-interface for a specified VRF.

Expected Results
  • Success: The test will pass if the provided logging source-interface is configured in the specified VRF.
  • Failure: The test will fail if the provided logging source-interface is NOT configured in the specified VRF.
Examples
anta.tests.logging:\n  - VerifyLoggingSourceIntf:\n      interface: Management0\n      vrf: default\n
Source code in anta/tests/logging.py
class VerifyLoggingSourceIntf(AntaTest):\n    \"\"\"Verifies logging source-interface for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided logging source-interface is configured in the specified VRF.\n    * Failure: The test will fail if the provided logging source-interface is NOT configured in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingSourceIntf:\n          interface: Management0\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingSourceInt\"\n    description = \"Verifies logging source-interface for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show logging\", ofmt=\"text\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyLoggingSourceInt test.\"\"\"\n\n        interface: str\n        \"\"\"Source-interface to use as source IP of log messages.\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF to transport log messages. Defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingSourceInt.\"\"\"\n        output = self.instance_commands[0].text_output\n        pattern = rf\"Logging source-interface '{self.inputs.interface}'.*VRF {self.inputs.vrf}\"\n        if re.search(pattern, _get_logging_states(self.logger, output)):\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Source-interface '{self.inputs.interface}' is not configured in VRF {self.inputs.vrf}\")\n
"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingSourceIntf-attributes","title":"Inputs","text":"Name Type Description Default interface str Source-interface to use as source IP of log messages. - vrf str The name of the VRF to transport log messages. Defaults to `default`. 'default'"},{"location":"api/tests.logging/#anta.tests.logging.VerifyLoggingTimestamp","title":"VerifyLoggingTimestamp","text":"

Verifies if logs are generated with the appropriate timestamp.

Expected Results
  • Success: The test will pass if logs are generated with the appropriate timestamp.
  • Failure: The test will fail if logs are NOT generated with the appropriate timestamp.
Examples
anta.tests.logging:\n  - VerifyLoggingTimestamp:\n
Source code in anta/tests/logging.py
class VerifyLoggingTimestamp(AntaTest):\n    \"\"\"Verifies if logs are generated with the appropriate timestamp.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if logs are generated with the appropriate timestamp.\n    * Failure: The test will fail if logs are NOT generated with the appropriate timestamp.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.logging:\n      - VerifyLoggingTimestamp:\n    ```\n    \"\"\"\n\n    name = \"VerifyLoggingTimestamp\"\n    description = \"Verifies if logs are generated with the riate timestamp.\"\n    categories: ClassVar[list[str]] = [\"logging\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"send log level informational message ANTA VerifyLoggingTimestamp validation\", ofmt=\"text\"),\n        AntaCommand(command=\"show logging informational last 30 seconds | grep ANTA\", ofmt=\"text\", use_cache=False),\n    ]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyLoggingTimestamp.\"\"\"\n        log_pattern = r\"ANTA VerifyLoggingTimestamp validation\"\n        timestamp_pattern = r\"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{6}-\\d{2}:\\d{2}\"\n        output = self.instance_commands[1].text_output\n        lines = output.strip().split(\"\\n\")[::-1]\n        last_line_with_pattern = \"\"\n        for line in lines:\n            if re.search(log_pattern, line):\n                last_line_with_pattern = line\n                break\n        if re.search(timestamp_pattern, last_line_with_pattern):\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"Logs are not generated with the appropriate timestamp format\")\n
"},{"location":"api/tests.logging/#anta.tests.logging._get_logging_states","title":"_get_logging_states","text":"
_get_logging_states(logger: logging.Logger, command_output: str) -> str\n

Parse show logging output and gets operational logging states used in the tests in this module.

Returns:

Type Description str: The operational logging states. Source code in anta/tests/logging.py
def _get_logging_states(logger: logging.Logger, command_output: str) -> str:\n    \"\"\"Parse `show logging` output and gets operational logging states used in the tests in this module.\n\n    Parameters\n    ----------\n        logger: The logger object.\n        command_output: The `show logging` output.\n\n    Returns\n    -------\n        str: The operational logging states.\n\n    \"\"\"\n    log_states = command_output.partition(\"\\n\\nExternal configuration:\")[0]\n    logger.debug(\"Device logging states:\\n%s\", log_states)\n    return log_states\n
"},{"location":"api/tests/","title":"Overview","text":""},{"location":"api/tests/#anta-tests-landing-page","title":"ANTA Tests Landing Page","text":"

This section describes all the available tests provided by the ANTA package.

"},{"location":"api/tests/#available-tests","title":"Available Tests","text":"

Here are the tests that we currently provide:

  • AAA
  • Adaptive Virtual Topology
  • BFD
  • Configuration
  • Connectivity
  • Field Notice
  • GreenT
  • Hardware
  • Interfaces
  • LANZ
  • Logging
  • MLAG
  • Multicast
  • Profiles
  • PTP
  • Router Path Selection
  • Routing Generic
  • Routing BGP
  • Routing OSPF
  • Security
  • Services
  • SNMP
  • Software
  • STP
  • STUN
  • System
  • VLAN
  • VXLAN
"},{"location":"api/tests/#using-the-tests","title":"Using the Tests","text":"

All these tests can be imported in a catalog to be used by the ANTA CLI or in your own framework.

"},{"location":"api/tests.mlag/","title":"MLAG","text":""},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagConfigSanity","title":"VerifyMlagConfigSanity","text":"

Verifies there are no MLAG config-sanity inconsistencies.

Expected Results
  • Success: The test will pass if there are NO MLAG config-sanity inconsistencies.
  • Failure: The test will fail if there are MLAG config-sanity inconsistencies.
  • Skipped: The test will be skipped if MLAG is \u2018disabled\u2019.
  • Error: The test will give an error if \u2018mlagActive\u2019 is not found in the JSON response.
Examples
anta.tests.mlag:\n  - VerifyMlagConfigSanity:\n
Source code in anta/tests/mlag.py
class VerifyMlagConfigSanity(AntaTest):\n    \"\"\"Verifies there are no MLAG config-sanity inconsistencies.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are NO MLAG config-sanity inconsistencies.\n    * Failure: The test will fail if there are MLAG config-sanity inconsistencies.\n    * Skipped: The test will be skipped if MLAG is 'disabled'.\n    * Error: The test will give an error if 'mlagActive' is not found in the JSON response.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.mlag:\n      - VerifyMlagConfigSanity:\n    ```\n    \"\"\"\n\n    name = \"VerifyMlagConfigSanity\"\n    description = \"Verifies there are no MLAG config-sanity inconsistencies.\"\n    categories: ClassVar[list[str]] = [\"mlag\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show mlag config-sanity\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMlagConfigSanity.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if (mlag_status := get_value(command_output, \"mlagActive\")) is None:\n            self.result.is_error(message=\"Incorrect JSON response - 'mlagActive' state was not found\")\n            return\n        if mlag_status is False:\n            self.result.is_skipped(\"MLAG is disabled\")\n            return\n        keys_to_verify = [\"globalConfiguration\", \"interfaceConfiguration\"]\n        verified_output = {key: get_value(command_output, key) for key in keys_to_verify}\n        if not any(verified_output.values()):\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"MLAG config-sanity returned inconsistencies: {verified_output}\")\n
"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagDualPrimary","title":"VerifyMlagDualPrimary","text":"

Verifies the dual-primary detection and its parameters of the MLAG configuration.

Expected Results
  • Success: The test will pass if the dual-primary detection is enabled and its parameters are configured properly.
  • Failure: The test will fail if the dual-primary detection is NOT enabled or its parameters are NOT configured properly.
  • Skipped: The test will be skipped if MLAG is \u2018disabled\u2019.
Examples
anta.tests.mlag:\n  - VerifyMlagDualPrimary:\n      detection_delay: 200\n      errdisabled: True\n      recovery_delay: 60\n      recovery_delay_non_mlag: 0\n
Source code in anta/tests/mlag.py
class VerifyMlagDualPrimary(AntaTest):\n    \"\"\"Verifies the dual-primary detection and its parameters of the MLAG configuration.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the dual-primary detection is enabled and its parameters are configured properly.\n    * Failure: The test will fail if the dual-primary detection is NOT enabled or its parameters are NOT configured properly.\n    * Skipped: The test will be skipped if MLAG is 'disabled'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.mlag:\n      - VerifyMlagDualPrimary:\n          detection_delay: 200\n          errdisabled: True\n          recovery_delay: 60\n          recovery_delay_non_mlag: 0\n    ```\n    \"\"\"\n\n    name = \"VerifyMlagDualPrimary\"\n    description = \"Verifies the MLAG dual-primary detection parameters.\"\n    categories: ClassVar[list[str]] = [\"mlag\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show mlag detail\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyMlagDualPrimary test.\"\"\"\n\n        detection_delay: PositiveInteger\n        \"\"\"Delay detection (seconds).\"\"\"\n        errdisabled: bool = False\n        \"\"\"Errdisabled all interfaces when dual-primary is detected.\"\"\"\n        recovery_delay: PositiveInteger\n        \"\"\"Delay (seconds) after dual-primary detection resolves until non peer-link ports that are part of an MLAG are enabled.\"\"\"\n        recovery_delay_non_mlag: PositiveInteger\n        \"\"\"Delay (seconds) after dual-primary detection resolves until ports that are not part of an MLAG are enabled.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMlagDualPrimary.\"\"\"\n        errdisabled_action = \"errdisableAllInterfaces\" if self.inputs.errdisabled else \"none\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"state\"] == \"disabled\":\n            self.result.is_skipped(\"MLAG is disabled\")\n            return\n        if command_output[\"dualPrimaryDetectionState\"] == \"disabled\":\n            self.result.is_failure(\"Dual-primary detection is disabled\")\n            return\n        keys_to_verify = [\"detail.dualPrimaryDetectionDelay\", \"detail.dualPrimaryAction\", \"dualPrimaryMlagRecoveryDelay\", \"dualPrimaryNonMlagRecoveryDelay\"]\n        verified_output = {key: get_value(command_output, key) for key in keys_to_verify}\n        if (\n            verified_output[\"detail.dualPrimaryDetectionDelay\"] == self.inputs.detection_delay\n            and verified_output[\"detail.dualPrimaryAction\"] == errdisabled_action\n            and verified_output[\"dualPrimaryMlagRecoveryDelay\"] == self.inputs.recovery_delay\n            and verified_output[\"dualPrimaryNonMlagRecoveryDelay\"] == self.inputs.recovery_delay_non_mlag\n        ):\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The dual-primary parameters are not configured properly: {verified_output}\")\n
"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagDualPrimary-attributes","title":"Inputs","text":"Name Type Description Default detection_delay PositiveInteger Delay detection (seconds). - errdisabled bool Errdisabled all interfaces when dual-primary is detected. False recovery_delay PositiveInteger Delay (seconds) after dual-primary detection resolves until non peer-link ports that are part of an MLAG are enabled. - recovery_delay_non_mlag PositiveInteger Delay (seconds) after dual-primary detection resolves until ports that are not part of an MLAG are enabled. -"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagInterfaces","title":"VerifyMlagInterfaces","text":"

Verifies there are no inactive or active-partial MLAG ports.

Expected Results
  • Success: The test will pass if there are NO inactive or active-partial MLAG ports.
  • Failure: The test will fail if there are inactive or active-partial MLAG ports.
  • Skipped: The test will be skipped if MLAG is \u2018disabled\u2019.
Examples
anta.tests.mlag:\n  - VerifyMlagInterfaces:\n
Source code in anta/tests/mlag.py
class VerifyMlagInterfaces(AntaTest):\n    \"\"\"Verifies there are no inactive or active-partial MLAG ports.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are NO inactive or active-partial MLAG ports.\n    * Failure: The test will fail if there are inactive or active-partial MLAG ports.\n    * Skipped: The test will be skipped if MLAG is 'disabled'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.mlag:\n      - VerifyMlagInterfaces:\n    ```\n    \"\"\"\n\n    name = \"VerifyMlagInterfaces\"\n    description = \"Verifies there are no inactive or active-partial MLAG ports.\"\n    categories: ClassVar[list[str]] = [\"mlag\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show mlag\", revision=2)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMlagInterfaces.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"state\"] == \"disabled\":\n            self.result.is_skipped(\"MLAG is disabled\")\n            return\n        if command_output[\"mlagPorts\"][\"Inactive\"] == 0 and command_output[\"mlagPorts\"][\"Active-partial\"] == 0:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"MLAG status is not OK: {command_output['mlagPorts']}\")\n
"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagPrimaryPriority","title":"VerifyMlagPrimaryPriority","text":"

Verify the MLAG (Multi-Chassis Link Aggregation) primary priority.

Expected Results
  • Success: The test will pass if the MLAG state is set as \u2018primary\u2019 and the priority matches the input.
  • Failure: The test will fail if the MLAG state is not \u2018primary\u2019 or the priority doesn\u2019t match the input.
  • Skipped: The test will be skipped if MLAG is \u2018disabled\u2019.
Examples
anta.tests.mlag:\n  - VerifyMlagPrimaryPriority:\n      primary_priority: 3276\n
Source code in anta/tests/mlag.py
class VerifyMlagPrimaryPriority(AntaTest):\n    \"\"\"Verify the MLAG (Multi-Chassis Link Aggregation) primary priority.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the MLAG state is set as 'primary' and the priority matches the input.\n    * Failure: The test will fail if the MLAG state is not 'primary' or the priority doesn't match the input.\n    * Skipped: The test will be skipped if MLAG is 'disabled'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.mlag:\n      - VerifyMlagPrimaryPriority:\n          primary_priority: 3276\n    ```\n    \"\"\"\n\n    name = \"VerifyMlagPrimaryPriority\"\n    description = \"Verifies the configuration of the MLAG primary priority.\"\n    categories: ClassVar[list[str]] = [\"mlag\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show mlag detail\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyMlagPrimaryPriority test.\"\"\"\n\n        primary_priority: MlagPriority\n        \"\"\"The expected MLAG primary priority.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMlagPrimaryPriority.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n        # Skip the test if MLAG is disabled\n        if command_output[\"state\"] == \"disabled\":\n            self.result.is_skipped(\"MLAG is disabled\")\n            return\n\n        mlag_state = get_value(command_output, \"detail.mlagState\")\n        primary_priority = get_value(command_output, \"detail.primaryPriority\")\n\n        # Check MLAG state\n        if mlag_state != \"primary\":\n            self.result.is_failure(\"The device is not set as MLAG primary.\")\n\n        # Check primary priority\n        if primary_priority != self.inputs.primary_priority:\n            self.result.is_failure(\n                f\"The primary priority does not match expected. Expected `{self.inputs.primary_priority}`, but found `{primary_priority}` instead.\",\n            )\n
"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagPrimaryPriority-attributes","title":"Inputs","text":"Name Type Description Default primary_priority MlagPriority The expected MLAG primary priority. -"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagReloadDelay","title":"VerifyMlagReloadDelay","text":"

Verifies the reload-delay parameters of the MLAG configuration.

Expected Results
  • Success: The test will pass if the reload-delay parameters are configured properly.
  • Failure: The test will fail if the reload-delay parameters are NOT configured properly.
  • Skipped: The test will be skipped if MLAG is \u2018disabled\u2019.
Examples
anta.tests.mlag:\n  - VerifyMlagReloadDelay:\n      reload_delay: 300\n      reload_delay_non_mlag: 330\n
Source code in anta/tests/mlag.py
class VerifyMlagReloadDelay(AntaTest):\n    \"\"\"Verifies the reload-delay parameters of the MLAG configuration.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the reload-delay parameters are configured properly.\n    * Failure: The test will fail if the reload-delay parameters are NOT configured properly.\n    * Skipped: The test will be skipped if MLAG is 'disabled'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.mlag:\n      - VerifyMlagReloadDelay:\n          reload_delay: 300\n          reload_delay_non_mlag: 330\n    ```\n    \"\"\"\n\n    name = \"VerifyMlagReloadDelay\"\n    description = \"Verifies the MLAG reload-delay parameters.\"\n    categories: ClassVar[list[str]] = [\"mlag\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show mlag\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyMlagReloadDelay test.\"\"\"\n\n        reload_delay: PositiveInteger\n        \"\"\"Delay (seconds) after reboot until non peer-link ports that are part of an MLAG are enabled.\"\"\"\n        reload_delay_non_mlag: PositiveInteger\n        \"\"\"Delay (seconds) after reboot until ports that are not part of an MLAG are enabled.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMlagReloadDelay.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"state\"] == \"disabled\":\n            self.result.is_skipped(\"MLAG is disabled\")\n            return\n        keys_to_verify = [\"reloadDelay\", \"reloadDelayNonMlag\"]\n        verified_output = {key: get_value(command_output, key) for key in keys_to_verify}\n        if verified_output[\"reloadDelay\"] == self.inputs.reload_delay and verified_output[\"reloadDelayNonMlag\"] == self.inputs.reload_delay_non_mlag:\n            self.result.is_success()\n\n        else:\n            self.result.is_failure(f\"The reload-delay parameters are not configured properly: {verified_output}\")\n
"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagReloadDelay-attributes","title":"Inputs","text":"Name Type Description Default reload_delay PositiveInteger Delay (seconds) after reboot until non peer-link ports that are part of an MLAG are enabled. - reload_delay_non_mlag PositiveInteger Delay (seconds) after reboot until ports that are not part of an MLAG are enabled. -"},{"location":"api/tests.mlag/#anta.tests.mlag.VerifyMlagStatus","title":"VerifyMlagStatus","text":"

Verifies the health status of the MLAG configuration.

Expected Results
  • Success: The test will pass if the MLAG state is \u2018active\u2019, negotiation status is \u2018connected\u2019, peer-link status and local interface status are \u2018up\u2019.
  • Failure: The test will fail if the MLAG state is not \u2018active\u2019, negotiation status is not \u2018connected\u2019, peer-link status or local interface status are not \u2018up\u2019.
  • Skipped: The test will be skipped if MLAG is \u2018disabled\u2019.
Examples
anta.tests.mlag:\n  - VerifyMlagStatus:\n
Source code in anta/tests/mlag.py
class VerifyMlagStatus(AntaTest):\n    \"\"\"Verifies the health status of the MLAG configuration.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the MLAG state is 'active', negotiation status is 'connected',\n                   peer-link status and local interface status are 'up'.\n    * Failure: The test will fail if the MLAG state is not 'active', negotiation status is not 'connected',\n                   peer-link status or local interface status are not 'up'.\n    * Skipped: The test will be skipped if MLAG is 'disabled'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.mlag:\n      - VerifyMlagStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifyMlagStatus\"\n    description = \"Verifies the health status of the MLAG configuration.\"\n    categories: ClassVar[list[str]] = [\"mlag\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show mlag\", revision=2)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMlagStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"state\"] == \"disabled\":\n            self.result.is_skipped(\"MLAG is disabled\")\n            return\n        keys_to_verify = [\"state\", \"negStatus\", \"localIntfStatus\", \"peerLinkStatus\"]\n        verified_output = {key: get_value(command_output, key) for key in keys_to_verify}\n        if (\n            verified_output[\"state\"] == \"active\"\n            and verified_output[\"negStatus\"] == \"connected\"\n            and verified_output[\"localIntfStatus\"] == \"up\"\n            and verified_output[\"peerLinkStatus\"] == \"up\"\n        ):\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"MLAG status is not OK: {verified_output}\")\n
"},{"location":"api/tests.multicast/","title":"Multicast","text":""},{"location":"api/tests.multicast/#anta.tests.multicast.VerifyIGMPSnoopingGlobal","title":"VerifyIGMPSnoopingGlobal","text":"

Verifies the IGMP snooping global status.

Expected Results
  • Success: The test will pass if the IGMP snooping global status matches the expected status.
  • Failure: The test will fail if the IGMP snooping global status does not match the expected status.
Examples
anta.tests.multicast:\n  - VerifyIGMPSnoopingGlobal:\n      enabled: True\n
Source code in anta/tests/multicast.py
class VerifyIGMPSnoopingGlobal(AntaTest):\n    \"\"\"Verifies the IGMP snooping global status.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the IGMP snooping global status matches the expected status.\n    * Failure: The test will fail if the IGMP snooping global status does not match the expected status.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.multicast:\n      - VerifyIGMPSnoopingGlobal:\n          enabled: True\n    ```\n    \"\"\"\n\n    name = \"VerifyIGMPSnoopingGlobal\"\n    description = \"Verifies the IGMP snooping global configuration.\"\n    categories: ClassVar[list[str]] = [\"multicast\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip igmp snooping\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyIGMPSnoopingGlobal test.\"\"\"\n\n        enabled: bool\n        \"\"\"Whether global IGMP snopping must be enabled (True) or disabled (False).\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIGMPSnoopingGlobal.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n        igmp_state = command_output[\"igmpSnoopingState\"]\n        if igmp_state != \"enabled\" if self.inputs.enabled else igmp_state != \"disabled\":\n            self.result.is_failure(f\"IGMP state is not valid: {igmp_state}\")\n
"},{"location":"api/tests.multicast/#anta.tests.multicast.VerifyIGMPSnoopingGlobal-attributes","title":"Inputs","text":"Name Type Description Default enabled bool Whether global IGMP snopping must be enabled (True) or disabled (False). -"},{"location":"api/tests.multicast/#anta.tests.multicast.VerifyIGMPSnoopingVlans","title":"VerifyIGMPSnoopingVlans","text":"

Verifies the IGMP snooping status for the provided VLANs.

Expected Results
  • Success: The test will pass if the IGMP snooping status matches the expected status for the provided VLANs.
  • Failure: The test will fail if the IGMP snooping status does not match the expected status for the provided VLANs.
Examples
anta.tests.multicast:\n  - VerifyIGMPSnoopingVlans:\n      vlans:\n        10: False\n        12: False\n
Source code in anta/tests/multicast.py
class VerifyIGMPSnoopingVlans(AntaTest):\n    \"\"\"Verifies the IGMP snooping status for the provided VLANs.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the IGMP snooping status matches the expected status for the provided VLANs.\n    * Failure: The test will fail if the IGMP snooping status does not match the expected status for the provided VLANs.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.multicast:\n      - VerifyIGMPSnoopingVlans:\n          vlans:\n            10: False\n            12: False\n    ```\n    \"\"\"\n\n    name = \"VerifyIGMPSnoopingVlans\"\n    description = \"Verifies the IGMP snooping status for the provided VLANs.\"\n    categories: ClassVar[list[str]] = [\"multicast\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip igmp snooping\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyIGMPSnoopingVlans test.\"\"\"\n\n        vlans: dict[Vlan, bool]\n        \"\"\"Dictionary with VLAN ID and whether IGMP snooping must be enabled (True) or disabled (False).\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIGMPSnoopingVlans.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n        for vlan, enabled in self.inputs.vlans.items():\n            if str(vlan) not in command_output[\"vlans\"]:\n                self.result.is_failure(f\"Supplied vlan {vlan} is not present on the device.\")\n                continue\n\n            igmp_state = command_output[\"vlans\"][str(vlan)][\"igmpSnoopingState\"]\n            if igmp_state != \"enabled\" if enabled else igmp_state != \"disabled\":\n                self.result.is_failure(f\"IGMP state for vlan {vlan} is {igmp_state}\")\n
"},{"location":"api/tests.multicast/#anta.tests.multicast.VerifyIGMPSnoopingVlans-attributes","title":"Inputs","text":"Name Type Description Default vlans dict[Vlan, bool] Dictionary with VLAN ID and whether IGMP snooping must be enabled (True) or disabled (False). -"},{"location":"api/tests.path_selection/","title":"Router Path Selection","text":""},{"location":"api/tests.path_selection/#anta.tests.path_selection.VerifyPathsHealth","title":"VerifyPathsHealth","text":"

Verifies the path and telemetry state of all paths under router path-selection.

The expected states are \u2018IPsec established\u2019, \u2018Resolved\u2019 for path and \u2018active\u2019 for telemetry.

Expected Results
  • Success: The test will pass if all path states under router path-selection are either \u2018IPsec established\u2019 or \u2018Resolved\u2019 and their telemetry state as \u2018active\u2019.
  • Failure: The test will fail if router path-selection is not configured or if any path state is not \u2018IPsec established\u2019 or \u2018Resolved\u2019, or the telemetry state is \u2018inactive\u2019.
Examples
anta.tests.path_selection:\n  - VerifyPathsHealth:\n
Source code in anta/tests/path_selection.py
class VerifyPathsHealth(AntaTest):\n    \"\"\"\n    Verifies the path and telemetry state of all paths under router path-selection.\n\n    The expected states are 'IPsec established', 'Resolved' for path and 'active' for telemetry.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all path states under router path-selection are either 'IPsec established' or 'Resolved'\n               and their telemetry state as 'active'.\n    * Failure: The test will fail if router path-selection is not configured or if any path state is not 'IPsec established' or 'Resolved',\n               or the telemetry state is 'inactive'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.path_selection:\n      - VerifyPathsHealth:\n    ```\n    \"\"\"\n\n    name = \"VerifyPathsHealth\"\n    description = \"Verifies the path and telemetry state of all paths under router path-selection.\"\n    categories: ClassVar[list[str]] = [\"path-selection\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show path-selection paths\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPathsHealth.\"\"\"\n        self.result.is_success()\n\n        command_output = self.instance_commands[0].json_output[\"dpsPeers\"]\n\n        # If no paths are configured for router path-selection, the test fails\n        if not command_output:\n            self.result.is_failure(\"No path configured for router path-selection.\")\n            return\n\n        # Check the state of each path\n        for peer, peer_data in command_output.items():\n            for group, group_data in peer_data[\"dpsGroups\"].items():\n                for path_data in group_data[\"dpsPaths\"].values():\n                    path_state = path_data[\"state\"]\n                    session = path_data[\"dpsSessions\"][\"0\"][\"active\"]\n\n                    # If the path state of any path is not 'ipsecEstablished' or 'routeResolved', the test fails\n                    if path_state not in [\"ipsecEstablished\", \"routeResolved\"]:\n                        self.result.is_failure(f\"Path state for peer {peer} in path-group {group} is `{path_state}`.\")\n\n                    # If the telemetry state of any path is inactive, the test fails\n                    elif not session:\n                        self.result.is_failure(f\"Telemetry state for peer {peer} in path-group {group} is `inactive`.\")\n
"},{"location":"api/tests.path_selection/#anta.tests.path_selection.VerifySpecificPath","title":"VerifySpecificPath","text":"

Verifies the path and telemetry state of a specific path for an IPv4 peer under router path-selection.

The expected states are \u2018IPsec established\u2019, \u2018Resolved\u2019 for path and \u2018active\u2019 for telemetry.

Expected Results
  • Success: The test will pass if the path state under router path-selection is either \u2018IPsec established\u2019 or \u2018Resolved\u2019 and telemetry state as \u2018active\u2019.
  • Failure: The test will fail if router path-selection is not configured or if the path state is not \u2018IPsec established\u2019 or \u2018Resolved\u2019, or if the telemetry state is \u2018inactive\u2019.
Examples
anta.tests.path_selection:\n  - VerifySpecificPath:\n      paths:\n        - peer: 10.255.0.1\n          path_group: internet\n          source_address: 100.64.3.2\n          destination_address: 100.64.1.2\n
Source code in anta/tests/path_selection.py
class VerifySpecificPath(AntaTest):\n    \"\"\"\n    Verifies the path and telemetry state of a specific path for an IPv4 peer under router path-selection.\n\n    The expected states are 'IPsec established', 'Resolved' for path and 'active' for telemetry.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the path state under router path-selection is either 'IPsec established' or 'Resolved'\n               and telemetry state as 'active'.\n    * Failure: The test will fail if router path-selection is not configured or if the path state is not 'IPsec established' or 'Resolved',\n               or if the telemetry state is 'inactive'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.path_selection:\n      - VerifySpecificPath:\n          paths:\n            - peer: 10.255.0.1\n              path_group: internet\n              source_address: 100.64.3.2\n              destination_address: 100.64.1.2\n    ```\n    \"\"\"\n\n    name = \"VerifySpecificPath\"\n    description = \"Verifies the path and telemetry state of a specific path under router path-selection.\"\n    categories: ClassVar[list[str]] = [\"path-selection\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaTemplate(template=\"show path-selection paths peer {peer} path-group {group} source {source} destination {destination}\", revision=1)\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySpecificPath test.\"\"\"\n\n        paths: list[RouterPath]\n        \"\"\"List of router paths to verify.\"\"\"\n\n        class RouterPath(BaseModel):\n            \"\"\"Detail of a router path.\"\"\"\n\n            peer: IPv4Address\n            \"\"\"Static peer IPv4 address.\"\"\"\n\n            path_group: str\n            \"\"\"Router path group name.\"\"\"\n\n            source_address: IPv4Address\n            \"\"\"Source IPv4 address of path.\"\"\"\n\n            destination_address: IPv4Address\n            \"\"\"Destination IPv4 address of path.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each router path.\"\"\"\n        return [\n            template.render(peer=path.peer, group=path.path_group, source=path.source_address, destination=path.destination_address) for path in self.inputs.paths\n        ]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySpecificPath.\"\"\"\n        self.result.is_success()\n\n        # Check the state of each path\n        for command in self.instance_commands:\n            peer = command.params.peer\n            path_group = command.params.group\n            source = command.params.source\n            destination = command.params.destination\n            command_output = command.json_output.get(\"dpsPeers\", [])\n\n            # If the peer is not configured for the path group, the test fails\n            if not command_output:\n                self.result.is_failure(f\"Path `peer: {peer} source: {source} destination: {destination}` is not configured for path-group `{path_group}`.\")\n                continue\n\n            # Extract the state of the path\n            path_output = get_value(command_output, f\"{peer}..dpsGroups..{path_group}..dpsPaths\", separator=\"..\")\n            path_state = next(iter(path_output.values())).get(\"state\")\n            session = get_value(next(iter(path_output.values())), \"dpsSessions.0.active\")\n\n            # If the state of the path is not 'ipsecEstablished' or 'routeResolved', or the telemetry state is 'inactive', the test fails\n            if path_state not in [\"ipsecEstablished\", \"routeResolved\"]:\n                self.result.is_failure(f\"Path state for `peer: {peer} source: {source} destination: {destination}` in path-group {path_group} is `{path_state}`.\")\n            elif not session:\n                self.result.is_failure(\n                    f\"Telemetry state for path `peer: {peer} source: {source} destination: {destination}` in path-group {path_group} is `inactive`.\"\n                )\n
"},{"location":"api/tests.path_selection/#anta.tests.path_selection.VerifySpecificPath-attributes","title":"Inputs","text":"Name Type Description Default paths list[RouterPath] List of router paths to verify. -"},{"location":"api/tests.path_selection/#anta.tests.path_selection.VerifySpecificPath-attributes","title":"RouterPath","text":"Name Type Description Default peer IPv4Address Static peer IPv4 address. - path_group str Router path group name. - source_address IPv4Address Source IPv4 address of path. - destination_address IPv4Address Destination IPv4 address of path. -"},{"location":"api/tests.profiles/","title":"Profiles","text":""},{"location":"api/tests.profiles/#anta.tests.profiles.VerifyTcamProfile","title":"VerifyTcamProfile","text":"

Verifies that the device is using the provided Ternary Content-Addressable Memory (TCAM) profile.

Expected Results
  • Success: The test will pass if the provided TCAM profile is actually running on the device.
  • Failure: The test will fail if the provided TCAM profile is not running on the device.
Examples
anta.tests.profiles:\n  - VerifyTcamProfile:\n      profile: vxlan-routing\n
Source code in anta/tests/profiles.py
class VerifyTcamProfile(AntaTest):\n    \"\"\"Verifies that the device is using the provided Ternary Content-Addressable Memory (TCAM) profile.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided TCAM profile is actually running on the device.\n    * Failure: The test will fail if the provided TCAM profile is not running on the device.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.profiles:\n      - VerifyTcamProfile:\n          profile: vxlan-routing\n    ```\n    \"\"\"\n\n    name = \"VerifyTcamProfile\"\n    description = \"Verifies the device TCAM profile.\"\n    categories: ClassVar[list[str]] = [\"profiles\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show hardware tcam profile\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyTcamProfile test.\"\"\"\n\n        profile: str\n        \"\"\"Expected TCAM profile.\"\"\"\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTcamProfile.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"pmfProfiles\"][\"FixedSystem\"][\"status\"] == command_output[\"pmfProfiles\"][\"FixedSystem\"][\"config\"] == self.inputs.profile:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Incorrect profile running on device: {command_output['pmfProfiles']['FixedSystem']['status']}\")\n
"},{"location":"api/tests.profiles/#anta.tests.profiles.VerifyTcamProfile-attributes","title":"Inputs","text":"Name Type Description Default profile str Expected TCAM profile. -"},{"location":"api/tests.profiles/#anta.tests.profiles.VerifyUnifiedForwardingTableMode","title":"VerifyUnifiedForwardingTableMode","text":"

Verifies the device is using the expected UFT (Unified Forwarding Table) mode.

Expected Results
  • Success: The test will pass if the device is using the expected UFT mode.
  • Failure: The test will fail if the device is not using the expected UFT mode.
Examples
anta.tests.profiles:\n  - VerifyUnifiedForwardingTableMode:\n      mode: 3\n
Source code in anta/tests/profiles.py
class VerifyUnifiedForwardingTableMode(AntaTest):\n    \"\"\"Verifies the device is using the expected UFT (Unified Forwarding Table) mode.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is using the expected UFT mode.\n    * Failure: The test will fail if the device is not using the expected UFT mode.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.profiles:\n      - VerifyUnifiedForwardingTableMode:\n          mode: 3\n    ```\n    \"\"\"\n\n    name = \"VerifyUnifiedForwardingTableMode\"\n    description = \"Verifies the device is using the expected UFT mode.\"\n    categories: ClassVar[list[str]] = [\"profiles\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show platform trident forwarding-table partition\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyUnifiedForwardingTableMode test.\"\"\"\n\n        mode: Literal[0, 1, 2, 3, 4, \"flexible\"]\n        \"\"\"Expected UFT mode. Valid values are 0, 1, 2, 3, 4, or \"flexible\".\"\"\"\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyUnifiedForwardingTableMode.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"uftMode\"] == str(self.inputs.mode):\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device is not running correct UFT mode (expected: {self.inputs.mode} / running: {command_output['uftMode']})\")\n
"},{"location":"api/tests.profiles/#anta.tests.profiles.VerifyUnifiedForwardingTableMode-attributes","title":"Inputs","text":"Name Type Description Default mode Literal[0, 1, 2, 3, 4, 'flexible'] Expected UFT mode. Valid values are 0, 1, 2, 3, 4, or \"flexible\". -"},{"location":"api/tests.ptp/","title":"PTP","text":""},{"location":"api/tests.ptp/#anta.tests.ptp.VerifyPtpGMStatus","title":"VerifyPtpGMStatus","text":"

Verifies that the device is locked to a valid Precision Time Protocol (PTP) Grandmaster (GM).

To test PTP failover, re-run the test with a secondary GMID configured.

Expected Results
  • Success: The test will pass if the device is locked to the provided Grandmaster.
  • Failure: The test will fail if the device is not locked to the provided Grandmaster.
  • Skipped: The test will be skipped if PTP is not configured on the device.
Examples
anta.tests.ptp:\n  - VerifyPtpGMStatus:\n      gmid: 0xec:46:70:ff:fe:00:ff:a9\n
Source code in anta/tests/ptp.py
class VerifyPtpGMStatus(AntaTest):\n    \"\"\"Verifies that the device is locked to a valid Precision Time Protocol (PTP) Grandmaster (GM).\n\n    To test PTP failover, re-run the test with a secondary GMID configured.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is locked to the provided Grandmaster.\n    * Failure: The test will fail if the device is not locked to the provided Grandmaster.\n    * Skipped: The test will be skipped if PTP is not configured on the device.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.ptp:\n      - VerifyPtpGMStatus:\n          gmid: 0xec:46:70:ff:fe:00:ff:a9\n    ```\n    \"\"\"\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyPtpGMStatus test.\"\"\"\n\n        gmid: str\n        \"\"\"Identifier of the Grandmaster to which the device should be locked.\"\"\"\n\n    name = \"VerifyPtpGMStatus\"\n    description = \"Verifies that the device is locked to a valid PTP Grandmaster.\"\n    categories: ClassVar[list[str]] = [\"ptp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ptp\", revision=2)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPtpGMStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        if (ptp_clock_summary := command_output.get(\"ptpClockSummary\")) is None:\n            self.result.is_skipped(\"PTP is not configured\")\n            return\n\n        if ptp_clock_summary[\"gmClockIdentity\"] != self.inputs.gmid:\n            self.result.is_failure(\n                f\"The device is locked to the following Grandmaster: '{ptp_clock_summary['gmClockIdentity']}', which differ from the expected one.\",\n            )\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.ptp/#anta.tests.ptp.VerifyPtpGMStatus-attributes","title":"Inputs","text":"Name Type Description Default gmid str Identifier of the Grandmaster to which the device should be locked. -"},{"location":"api/tests.ptp/#anta.tests.ptp.VerifyPtpLockStatus","title":"VerifyPtpLockStatus","text":"

Verifies that the device was locked to the upstream Precision Time Protocol (PTP) Grandmaster (GM) in the last minute.

Expected Results
  • Success: The test will pass if the device was locked to the upstream GM in the last minute.
  • Failure: The test will fail if the device was not locked to the upstream GM in the last minute.
  • Skipped: The test will be skipped if PTP is not configured on the device.
Examples
anta.tests.ptp:\n  - VerifyPtpLockStatus:\n
Source code in anta/tests/ptp.py
class VerifyPtpLockStatus(AntaTest):\n    \"\"\"Verifies that the device was locked to the upstream Precision Time Protocol (PTP) Grandmaster (GM) in the last minute.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device was locked to the upstream GM in the last minute.\n    * Failure: The test will fail if the device was not locked to the upstream GM in the last minute.\n    * Skipped: The test will be skipped if PTP is not configured on the device.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.ptp:\n      - VerifyPtpLockStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifyPtpLockStatus\"\n    description = \"Verifies that the device was locked to the upstream PTP GM in the last minute.\"\n    categories: ClassVar[list[str]] = [\"ptp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ptp\", revision=2)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPtpLockStatus.\"\"\"\n        threshold = 60\n        command_output = self.instance_commands[0].json_output\n\n        if (ptp_clock_summary := command_output.get(\"ptpClockSummary\")) is None:\n            self.result.is_skipped(\"PTP is not configured\")\n            return\n\n        time_difference = ptp_clock_summary[\"currentPtpSystemTime\"] - ptp_clock_summary[\"lastSyncTime\"]\n\n        if time_difference >= threshold:\n            self.result.is_failure(f\"The device lock is more than {threshold}s old: {time_difference}s\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.ptp/#anta.tests.ptp.VerifyPtpModeStatus","title":"VerifyPtpModeStatus","text":"

Verifies that the device is configured as a Precision Time Protocol (PTP) Boundary Clock (BC).

Expected Results
  • Success: The test will pass if the device is a BC.
  • Failure: The test will fail if the device is not a BC.
  • Skipped: The test will be skipped if PTP is not configured on the device.
Examples
anta.tests.ptp:\n  - VerifyPtpModeStatus:\n
Source code in anta/tests/ptp.py
class VerifyPtpModeStatus(AntaTest):\n    \"\"\"Verifies that the device is configured as a Precision Time Protocol (PTP) Boundary Clock (BC).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is a BC.\n    * Failure: The test will fail if the device is not a BC.\n    * Skipped: The test will be skipped if PTP is not configured on the device.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.ptp:\n      - VerifyPtpModeStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifyPtpModeStatus\"\n    description = \"Verifies that the device is configured as a PTP Boundary Clock.\"\n    categories: ClassVar[list[str]] = [\"ptp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ptp\", revision=2)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPtpModeStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        if (ptp_mode := command_output.get(\"ptpMode\")) is None:\n            self.result.is_skipped(\"PTP is not configured\")\n            return\n\n        if ptp_mode != \"ptpBoundaryClock\":\n            self.result.is_failure(f\"The device is not configured as a PTP Boundary Clock: '{ptp_mode}'\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.ptp/#anta.tests.ptp.VerifyPtpOffset","title":"VerifyPtpOffset","text":"

Verifies that the Precision Time Protocol (PTP) timing offset is within \u00b1 1000ns from the master clock.

Expected Results
  • Success: The test will pass if the PTP timing offset is within \u00b1 1000ns from the master clock.
  • Failure: The test will fail if the PTP timing offset is greater than \u00b1 1000ns from the master clock.
  • Skipped: The test will be skipped if PTP is not configured on the device.
Examples
anta.tests.ptp:\n  - VerifyPtpOffset:\n
Source code in anta/tests/ptp.py
class VerifyPtpOffset(AntaTest):\n    \"\"\"Verifies that the Precision Time Protocol (PTP) timing offset is within +/- 1000ns from the master clock.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the PTP timing offset is within +/- 1000ns from the master clock.\n    * Failure: The test will fail if the PTP timing offset is greater than +/- 1000ns from the master clock.\n    * Skipped: The test will be skipped if PTP is not configured on the device.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.ptp:\n      - VerifyPtpOffset:\n    ```\n    \"\"\"\n\n    name = \"VerifyPtpOffset\"\n    description = \"Verifies that the PTP timing offset is within +/- 1000ns from the master clock.\"\n    categories: ClassVar[list[str]] = [\"ptp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ptp monitor\", revision=1)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPtpOffset.\"\"\"\n        threshold = 1000\n        offset_interfaces: dict[str, list[int]] = {}\n        command_output = self.instance_commands[0].json_output\n\n        if not command_output[\"ptpMonitorData\"]:\n            self.result.is_skipped(\"PTP is not configured\")\n            return\n\n        for interface in command_output[\"ptpMonitorData\"]:\n            if abs(interface[\"offsetFromMaster\"]) > threshold:\n                offset_interfaces.setdefault(interface[\"intf\"], []).append(interface[\"offsetFromMaster\"])\n\n        if offset_interfaces:\n            self.result.is_failure(f\"The device timing offset from master is greater than +/- {threshold}ns: {offset_interfaces}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.ptp/#anta.tests.ptp.VerifyPtpPortModeStatus","title":"VerifyPtpPortModeStatus","text":"

Verifies that all interfaces are in a valid Precision Time Protocol (PTP) state.

The interfaces can be in one of the following state: Master, Slave, Passive, or Disabled.

Expected Results
  • Success: The test will pass if all PTP enabled interfaces are in a valid state.
  • Failure: The test will fail if there are no PTP enabled interfaces or if some interfaces are not in a valid state.
Examples
anta.tests.ptp:\n  - VerifyPtpPortModeStatus:\n
Source code in anta/tests/ptp.py
class VerifyPtpPortModeStatus(AntaTest):\n    \"\"\"Verifies that all interfaces are in a valid Precision Time Protocol (PTP) state.\n\n    The interfaces can be in one of the following state: Master, Slave, Passive, or Disabled.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all PTP enabled interfaces are in a valid state.\n    * Failure: The test will fail if there are no PTP enabled interfaces or if some interfaces are not in a valid state.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.ptp:\n      - VerifyPtpPortModeStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifyPtpPortModeStatus\"\n    description = \"Verifies the PTP interfaces state.\"\n    categories: ClassVar[list[str]] = [\"ptp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ptp\", revision=2)]\n\n    @skip_on_platforms([\"cEOSLab\", \"vEOS-lab\", \"cEOSCloudLab\"])\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyPtpPortModeStatus.\"\"\"\n        valid_state = (\"psMaster\", \"psSlave\", \"psPassive\", \"psDisabled\")\n        command_output = self.instance_commands[0].json_output\n\n        if not command_output[\"ptpIntfSummaries\"]:\n            self.result.is_failure(\"No interfaces are PTP enabled\")\n            return\n\n        invalid_interfaces = [\n            interface\n            for interface in command_output[\"ptpIntfSummaries\"]\n            for vlan in command_output[\"ptpIntfSummaries\"][interface][\"ptpIntfVlanSummaries\"]\n            if vlan[\"portState\"] not in valid_state\n        ]\n\n        if not invalid_interfaces:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following interface(s) are not in a valid PTP state: '{invalid_interfaces}'\")\n
"},{"location":"api/tests.routing.bgp/","title":"BGP","text":""},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPAdvCommunities","title":"VerifyBGPAdvCommunities","text":"

Verifies if the advertised communities of BGP peers are standard, extended, and large in the specified VRF.

Expected Results
  • Success: The test will pass if the advertised communities of BGP peers are standard, extended, and large in the specified VRF.
  • Failure: The test will fail if the advertised communities of BGP peers are not standard, extended, and large in the specified VRF.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPAdvCommunities:\n        bgp_peers:\n          - peer_address: 172.30.11.17\n            vrf: default\n          - peer_address: 172.30.11.21\n            vrf: default\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPAdvCommunities(AntaTest):\n    \"\"\"Verifies if the advertised communities of BGP peers are standard, extended, and large in the specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the advertised communities of BGP peers are standard, extended, and large in the specified VRF.\n    * Failure: The test will fail if the advertised communities of BGP peers are not standard, extended, and large in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPAdvCommunities:\n            bgp_peers:\n              - peer_address: 172.30.11.17\n                vrf: default\n              - peer_address: 172.30.11.21\n                vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPAdvCommunities\"\n    description = \"Verifies the advertised communities of a BGP peer.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bgp neighbors vrf all\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPAdvCommunities test.\"\"\"\n\n        bgp_peers: list[BgpPeer]\n        \"\"\"List of BGP peers.\"\"\"\n\n        class BgpPeer(BaseModel):\n            \"\"\"Model for a BGP peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPAdvCommunities.\"\"\"\n        failures: dict[str, Any] = {\"bgp_peers\": {}}\n\n        # Iterate over each bgp peer\n        for bgp_peer in self.inputs.bgp_peers:\n            peer = str(bgp_peer.peer_address)\n            vrf = bgp_peer.vrf\n            failure: dict[str, dict[str, dict[str, Any]]] = {\"bgp_peers\": {peer: {vrf: {}}}}\n\n            # Verify BGP peer\n            if (\n                not (bgp_output := get_value(self.instance_commands[0].json_output, f\"vrfs.{vrf}.peerList\"))\n                or (bgp_output := get_item(bgp_output, \"peerAddress\", peer)) is None\n            ):\n                failure[\"bgp_peers\"][peer][vrf] = {\"status\": \"Not configured\"}\n                failures = deep_update(failures, failure)\n                continue\n\n            # Verify BGP peer's advertised communities\n            bgp_output = bgp_output.get(\"advertisedCommunities\")\n            if not bgp_output[\"standard\"] or not bgp_output[\"extended\"] or not bgp_output[\"large\"]:\n                failure[\"bgp_peers\"][peer][vrf] = {\"advertised_communities\": bgp_output}\n                failures = deep_update(failures, failure)\n\n        if not failures[\"bgp_peers\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peers are not configured or advertised communities are not standard, extended, and large:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPAdvCommunities-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpPeer] List of BGP peers. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPAdvCommunities-attributes","title":"BgpPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default'"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPExchangedRoutes","title":"VerifyBGPExchangedRoutes","text":"

Verifies if the BGP peers have correctly advertised and received routes.

The route type should be \u2018valid\u2019 and \u2018active\u2019 for a specified VRF.

Expected Results
  • Success: If the BGP peers have correctly advertised and received routes of type \u2018valid\u2019 and \u2018active\u2019 for a specified VRF.
  • Failure: If a BGP peer is not found, the expected advertised/received routes are not found, or the routes are not \u2018valid\u2019 or \u2018active\u2019.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPExchangedRoutes:\n        bgp_peers:\n          - peer_address: 172.30.255.5\n            vrf: default\n            advertised_routes:\n              - 192.0.254.5/32\n            received_routes:\n              - 192.0.255.4/32\n          - peer_address: 172.30.255.1\n            vrf: default\n            advertised_routes:\n              - 192.0.255.1/32\n              - 192.0.254.5/32\n            received_routes:\n              - 192.0.254.3/32\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPExchangedRoutes(AntaTest):\n    \"\"\"Verifies if the BGP peers have correctly advertised and received routes.\n\n    The route type should be 'valid' and 'active' for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: If the BGP peers have correctly advertised and received routes of type 'valid' and 'active' for a specified VRF.\n    * Failure: If a BGP peer is not found, the expected advertised/received routes are not found, or the routes are not 'valid' or 'active'.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPExchangedRoutes:\n            bgp_peers:\n              - peer_address: 172.30.255.5\n                vrf: default\n                advertised_routes:\n                  - 192.0.254.5/32\n                received_routes:\n                  - 192.0.255.4/32\n              - peer_address: 172.30.255.1\n                vrf: default\n                advertised_routes:\n                  - 192.0.255.1/32\n                  - 192.0.254.5/32\n                received_routes:\n                  - 192.0.254.3/32\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPExchangedRoutes\"\n    description = \"Verifies the advertised and received routes of BGP peers.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaTemplate(template=\"show bgp neighbors {peer} advertised-routes vrf {vrf}\", revision=3),\n        AntaTemplate(template=\"show bgp neighbors {peer} routes vrf {vrf}\", revision=3),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPExchangedRoutes test.\"\"\"\n\n        bgp_peers: list[BgpNeighbor]\n        \"\"\"List of BGP neighbors.\"\"\"\n\n        class BgpNeighbor(BaseModel):\n            \"\"\"Model for a BGP neighbor.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n            advertised_routes: list[IPv4Network]\n            \"\"\"List of advertised routes in CIDR format.\"\"\"\n            received_routes: list[IPv4Network]\n            \"\"\"List of received routes in CIDR format.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each BGP neighbor in the input list.\"\"\"\n        return [template.render(peer=str(bgp_peer.peer_address), vrf=bgp_peer.vrf) for bgp_peer in self.inputs.bgp_peers]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPExchangedRoutes.\"\"\"\n        failures: dict[str, dict[str, Any]] = {\"bgp_peers\": {}}\n\n        # Iterating over command output for different peers\n        for command in self.instance_commands:\n            peer = command.params.peer\n            vrf = command.params.vrf\n            for input_entry in self.inputs.bgp_peers:\n                if str(input_entry.peer_address) == peer and input_entry.vrf == vrf:\n                    advertised_routes = input_entry.advertised_routes\n                    received_routes = input_entry.received_routes\n                    break\n            failure = {vrf: \"\"}\n\n            # Verify if a BGP peer is configured with the provided vrf\n            if not (bgp_routes := get_value(command.json_output, f\"vrfs.{vrf}.bgpRouteEntries\")):\n                failure[vrf] = \"Not configured\"\n                failures[\"bgp_peers\"][peer] = failure\n                continue\n\n            # Validate advertised routes\n            if \"advertised-routes\" in command.command:\n                failure_routes = _add_bgp_routes_failure(advertised_routes, bgp_routes, peer, vrf)\n\n            # Validate received routes\n            else:\n                failure_routes = _add_bgp_routes_failure(received_routes, bgp_routes, peer, vrf, route_type=\"received_routes\")\n            failures = deep_update(failures, failure_routes)\n\n        if not failures[\"bgp_peers\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peers are not found or routes are not exchanged properly:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPExchangedRoutes-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpNeighbor] List of BGP neighbors. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPExchangedRoutes-attributes","title":"BgpNeighbor","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default' advertised_routes list[IPv4Network] List of advertised routes in CIDR format. - received_routes list[IPv4Network] List of received routes in CIDR format. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerASNCap","title":"VerifyBGPPeerASNCap","text":"

Verifies the four octet asn capabilities of a BGP peer in a specified VRF.

Expected Results
  • Success: The test will pass if BGP peer\u2019s four octet asn capabilities are advertised, received, and enabled in the specified VRF.
  • Failure: The test will fail if BGP peers are not found or four octet asn capabilities are not advertised, received, and enabled in the specified VRF.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPPeerASNCap:\n        bgp_peers:\n          - peer_address: 172.30.11.1\n            vrf: default\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPPeerASNCap(AntaTest):\n    \"\"\"Verifies the four octet asn capabilities of a BGP peer in a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if BGP peer's four octet asn capabilities are advertised, received, and enabled in the specified VRF.\n    * Failure: The test will fail if BGP peers are not found or four octet asn capabilities are not advertised, received, and enabled in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPPeerASNCap:\n            bgp_peers:\n              - peer_address: 172.30.11.1\n                vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPPeerASNCap\"\n    description = \"Verifies the four octet asn capabilities of a BGP peer.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bgp neighbors vrf all\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPPeerASNCap test.\"\"\"\n\n        bgp_peers: list[BgpPeer]\n        \"\"\"List of BGP peers.\"\"\"\n\n        class BgpPeer(BaseModel):\n            \"\"\"Model for a BGP peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPPeerASNCap.\"\"\"\n        failures: dict[str, Any] = {\"bgp_peers\": {}}\n\n        # Iterate over each bgp peer\n        for bgp_peer in self.inputs.bgp_peers:\n            peer = str(bgp_peer.peer_address)\n            vrf = bgp_peer.vrf\n            failure: dict[str, dict[str, dict[str, Any]]] = {\"bgp_peers\": {peer: {vrf: {}}}}\n\n            # Check if BGP output exists\n            if (\n                not (bgp_output := get_value(self.instance_commands[0].json_output, f\"vrfs.{vrf}.peerList\"))\n                or (bgp_output := get_item(bgp_output, \"peerAddress\", peer)) is None\n            ):\n                failure[\"bgp_peers\"][peer][vrf] = {\"status\": \"Not configured\"}\n                failures = deep_update(failures, failure)\n                continue\n\n            bgp_output = get_value(bgp_output, \"neighborCapabilities.fourOctetAsnCap\")\n\n            # Check if  four octet asn capabilities are found\n            if not bgp_output:\n                failure[\"bgp_peers\"][peer][vrf] = {\"fourOctetAsnCap\": \"not found\"}\n                failures = deep_update(failures, failure)\n\n            # Check if capabilities are not advertised, received, or enabled\n            elif not all(bgp_output.get(prop, False) for prop in [\"advertised\", \"received\", \"enabled\"]):\n                failure[\"bgp_peers\"][peer][vrf] = {\"fourOctetAsnCap\": bgp_output}\n                failures = deep_update(failures, failure)\n\n        # Check if there are any failures\n        if not failures[\"bgp_peers\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peer four octet asn capabilities are not found or not ok:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerASNCap-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpPeer] List of BGP peers. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerASNCap-attributes","title":"BgpPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default'"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerCount","title":"VerifyBGPPeerCount","text":"

Verifies the count of BGP peers for a given address family.

It supports multiple types of Address Families Identifiers (AFI) and Subsequent Address Family Identifiers (SAFI).

For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6 (AFI) which is handled automatically in this test.

Please refer to the Input class attributes below for details.

Expected Results
  • Success: If the count of BGP peers matches the expected count for each address family and VRF.
  • Failure: If the count of BGP peers does not match the expected count, or if BGP is not configured for an expected VRF or address family.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPPeerCount:\n        address_families:\n          - afi: \"evpn\"\n            num_peers: 2\n          - afi: \"ipv4\"\n            safi: \"unicast\"\n            vrf: \"PROD\"\n            num_peers: 2\n          - afi: \"ipv4\"\n            safi: \"unicast\"\n            vrf: \"default\"\n            num_peers: 3\n          - afi: \"ipv4\"\n            safi: \"multicast\"\n            vrf: \"DEV\"\n            num_peers: 3\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPPeerCount(AntaTest):\n    \"\"\"Verifies the count of BGP peers for a given address family.\n\n    It supports multiple types of Address Families Identifiers (AFI) and Subsequent Address Family Identifiers (SAFI).\n\n    For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6 (AFI) which is handled automatically in this test.\n\n    Please refer to the Input class attributes below for details.\n\n    Expected Results\n    ----------------\n    * Success: If the count of BGP peers matches the expected count for each address family and VRF.\n    * Failure: If the count of BGP peers does not match the expected count, or if BGP is not configured for an expected VRF or address family.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPPeerCount:\n            address_families:\n              - afi: \"evpn\"\n                num_peers: 2\n              - afi: \"ipv4\"\n                safi: \"unicast\"\n                vrf: \"PROD\"\n                num_peers: 2\n              - afi: \"ipv4\"\n                safi: \"unicast\"\n                vrf: \"default\"\n                num_peers: 3\n              - afi: \"ipv4\"\n                safi: \"multicast\"\n                vrf: \"DEV\"\n                num_peers: 3\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPPeerCount\"\n    description = \"Verifies the count of BGP peers.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaTemplate(template=\"show bgp {afi} {safi} summary vrf {vrf}\", revision=3),\n        AntaTemplate(template=\"show bgp {afi} summary\", revision=3),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPPeerCount test.\"\"\"\n\n        address_families: list[BgpAfi]\n        \"\"\"List of BGP address families (BgpAfi).\"\"\"\n\n        class BgpAfi(BaseModel):\n            \"\"\"Model for a BGP address family (AFI) and subsequent address family (SAFI).\"\"\"\n\n            afi: Afi\n            \"\"\"BGP address family (AFI).\"\"\"\n            safi: Safi | None = None\n            \"\"\"Optional BGP subsequent service family (SAFI).\n\n            If the input `afi` is `ipv4` or `ipv6`, a valid `safi` must be provided.\n            \"\"\"\n            vrf: str = \"default\"\n            \"\"\"\n            Optional VRF for IPv4 and IPv6. If not provided, it defaults to `default`.\n\n            If the input `afi` is not `ipv4` or `ipv6`, e.g. `evpn`, `vrf` must be `default`.\n            \"\"\"\n            num_peers: PositiveInt\n            \"\"\"Number of expected BGP peer(s).\"\"\"\n\n            @model_validator(mode=\"after\")\n            def validate_inputs(self: BaseModel) -> BaseModel:\n                \"\"\"Validate the inputs provided to the BgpAfi class.\n\n                If afi is either ipv4 or ipv6, safi must be provided.\n\n                If afi is not ipv4 or ipv6, safi must not be provided and vrf must be default.\n                \"\"\"\n                if self.afi in [\"ipv4\", \"ipv6\"]:\n                    if self.safi is None:\n                        msg = \"'safi' must be provided when afi is ipv4 or ipv6\"\n                        raise ValueError(msg)\n                elif self.safi is not None:\n                    msg = \"'safi' must not be provided when afi is not ipv4 or ipv6\"\n                    raise ValueError(msg)\n                elif self.vrf != \"default\":\n                    msg = \"'vrf' must be default when afi is not ipv4 or ipv6\"\n                    raise ValueError(msg)\n                return self\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each BGP address family in the input list.\"\"\"\n        commands = []\n        for afi in self.inputs.address_families:\n            if template == VerifyBGPPeerCount.commands[0] and afi.afi in [\"ipv4\", \"ipv6\"] and afi.safi != \"sr-te\":\n                commands.append(template.render(afi=afi.afi, safi=afi.safi, vrf=afi.vrf))\n\n            # For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6\n            elif template == VerifyBGPPeerCount.commands[0] and afi.afi in [\"ipv4\", \"ipv6\"] and afi.safi == \"sr-te\":\n                commands.append(template.render(afi=afi.safi, safi=afi.afi, vrf=afi.vrf))\n            elif template == VerifyBGPPeerCount.commands[1] and afi.afi not in [\"ipv4\", \"ipv6\"]:\n                commands.append(template.render(afi=afi.afi))\n        return commands\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPPeerCount.\"\"\"\n        self.result.is_success()\n\n        failures: dict[tuple[str, Any], dict[str, Any]] = {}\n\n        for command in self.instance_commands:\n            num_peers = None\n            peer_count = 0\n            command_output = command.json_output\n\n            afi = command.params.afi\n            safi = command.params.safi if hasattr(command.params, \"safi\") else None\n            afi_vrf = command.params.vrf if hasattr(command.params, \"vrf\") else \"default\"\n\n            # Swapping AFI and SAFI in case of SR-TE\n            if afi == \"sr-te\":\n                afi, safi = safi, afi\n\n            for input_entry in self.inputs.address_families:\n                if input_entry.afi == afi and input_entry.safi == safi and input_entry.vrf == afi_vrf:\n                    num_peers = input_entry.num_peers\n                    break\n\n            if not (vrfs := command_output.get(\"vrfs\")):\n                _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=afi_vrf, issue=\"Not Configured\")\n                continue\n\n            if afi_vrf == \"all\":\n                for vrf_data in vrfs.values():\n                    peer_count += len(vrf_data[\"peers\"])\n            else:\n                peer_count += len(command_output[\"vrfs\"][afi_vrf][\"peers\"])\n\n            if peer_count != num_peers:\n                _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=afi_vrf, issue=f\"Expected: {num_peers}, Actual: {peer_count}\")\n\n        if failures:\n            self.result.is_failure(f\"Failures: {list(failures.values())}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerCount-attributes","title":"Inputs","text":"Name Type Description Default address_families list[BgpAfi] List of BGP address families (BgpAfi). -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerCount-attributes","title":"BgpAfi","text":"Name Type Description Default afi Afi BGP address family (AFI). - safi Safi | None Optional BGP subsequent service family (SAFI). If the input `afi` is `ipv4` or `ipv6`, a valid `safi` must be provided. None vrf str Optional VRF for IPv4 and IPv6. If not provided, it defaults to `default`. If the input `afi` is not `ipv4` or `ipv6`, e.g. `evpn`, `vrf` must be `default`. 'default' num_peers PositiveInt Number of expected BGP peer(s). -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerMD5Auth","title":"VerifyBGPPeerMD5Auth","text":"

Verifies the MD5 authentication and state of IPv4 BGP peers in a specified VRF.

Expected Results
  • Success: The test will pass if IPv4 BGP peers are configured with MD5 authentication and state as established in the specified VRF.
  • Failure: The test will fail if IPv4 BGP peers are not found, state is not as established or MD5 authentication is not enabled in the specified VRF.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPPeerMD5Auth:\n        bgp_peers:\n          - peer_address: 172.30.11.1\n            vrf: default\n          - peer_address: 172.30.11.5\n            vrf: default\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPPeerMD5Auth(AntaTest):\n    \"\"\"Verifies the MD5 authentication and state of IPv4 BGP peers in a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if IPv4 BGP peers are configured with MD5 authentication and state as established in the specified VRF.\n    * Failure: The test will fail if IPv4 BGP peers are not found, state is not as established or MD5 authentication is not enabled in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPPeerMD5Auth:\n            bgp_peers:\n              - peer_address: 172.30.11.1\n                vrf: default\n              - peer_address: 172.30.11.5\n                vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPPeerMD5Auth\"\n    description = \"Verifies the MD5 authentication and state of a BGP peer.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bgp neighbors vrf all\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPPeerMD5Auth test.\"\"\"\n\n        bgp_peers: list[BgpPeer]\n        \"\"\"List of IPv4 BGP peers.\"\"\"\n\n        class BgpPeer(BaseModel):\n            \"\"\"Model for a BGP peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPPeerMD5Auth.\"\"\"\n        failures: dict[str, Any] = {\"bgp_peers\": {}}\n\n        # Iterate over each command\n        for bgp_peer in self.inputs.bgp_peers:\n            peer = str(bgp_peer.peer_address)\n            vrf = bgp_peer.vrf\n            failure: dict[str, dict[str, dict[str, Any]]] = {\"bgp_peers\": {peer: {vrf: {}}}}\n\n            # Check if BGP output exists\n            if (\n                not (bgp_output := get_value(self.instance_commands[0].json_output, f\"vrfs.{vrf}.peerList\"))\n                or (bgp_output := get_item(bgp_output, \"peerAddress\", peer)) is None\n            ):\n                failure[\"bgp_peers\"][peer][vrf] = {\"status\": \"Not configured\"}\n                failures = deep_update(failures, failure)\n                continue\n\n            # Check if BGP peer state and authentication\n            state = bgp_output.get(\"state\")\n            md5_auth_enabled = bgp_output.get(\"md5AuthEnabled\")\n            if state != \"Established\" or not md5_auth_enabled:\n                failure[\"bgp_peers\"][peer][vrf] = {\"state\": state, \"md5_auth_enabled\": md5_auth_enabled}\n                failures = deep_update(failures, failure)\n\n        # Check if there are any failures\n        if not failures[\"bgp_peers\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peers are not configured, not established or MD5 authentication is not enabled:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerMD5Auth-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpPeer] List of IPv4 BGP peers. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerMD5Auth-attributes","title":"BgpPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default'"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerMPCaps","title":"VerifyBGPPeerMPCaps","text":"

Verifies the multiprotocol capabilities of a BGP peer in a specified VRF.

Expected Results
  • Success: The test will pass if the BGP peer\u2019s multiprotocol capabilities are advertised, received, and enabled in the specified VRF.
  • Failure: The test will fail if BGP peers are not found or multiprotocol capabilities are not advertised, received, and enabled in the specified VRF.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPPeerMPCaps:\n        bgp_peers:\n          - peer_address: 172.30.11.1\n            vrf: default\n            capabilities:\n              - ipv4Unicast\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPPeerMPCaps(AntaTest):\n    \"\"\"Verifies the multiprotocol capabilities of a BGP peer in a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the BGP peer's multiprotocol capabilities are advertised, received, and enabled in the specified VRF.\n    * Failure: The test will fail if BGP peers are not found or multiprotocol capabilities are not advertised, received, and enabled in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPPeerMPCaps:\n            bgp_peers:\n              - peer_address: 172.30.11.1\n                vrf: default\n                capabilities:\n                  - ipv4Unicast\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPPeerMPCaps\"\n    description = \"Verifies the multiprotocol capabilities of a BGP peer.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bgp neighbors vrf all\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPPeerMPCaps test.\"\"\"\n\n        bgp_peers: list[BgpPeer]\n        \"\"\"List of BGP peers\"\"\"\n\n        class BgpPeer(BaseModel):\n            \"\"\"Model for a BGP peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n            capabilities: list[MultiProtocolCaps]\n            \"\"\"List of multiprotocol capabilities to be verified.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPPeerMPCaps.\"\"\"\n        failures: dict[str, Any] = {\"bgp_peers\": {}}\n\n        # Iterate over each bgp peer\n        for bgp_peer in self.inputs.bgp_peers:\n            peer = str(bgp_peer.peer_address)\n            vrf = bgp_peer.vrf\n            capabilities = bgp_peer.capabilities\n            failure: dict[str, dict[str, dict[str, Any]]] = {\"bgp_peers\": {peer: {vrf: {}}}}\n\n            # Check if BGP output exists\n            if (\n                not (bgp_output := get_value(self.instance_commands[0].json_output, f\"vrfs.{vrf}.peerList\"))\n                or (bgp_output := get_item(bgp_output, \"peerAddress\", peer)) is None\n            ):\n                failure[\"bgp_peers\"][peer][vrf] = {\"status\": \"Not configured\"}\n                failures = deep_update(failures, failure)\n                continue\n\n            # Check each capability\n            bgp_output = get_value(bgp_output, \"neighborCapabilities.multiprotocolCaps\")\n            for capability in capabilities:\n                capability_output = bgp_output.get(capability)\n\n                # Check if capabilities are missing\n                if not capability_output:\n                    failure[\"bgp_peers\"][peer][vrf][capability] = \"not found\"\n                    failures = deep_update(failures, failure)\n\n                # Check if capabilities are not advertised, received, or enabled\n                elif not all(capability_output.get(prop, False) for prop in [\"advertised\", \"received\", \"enabled\"]):\n                    failure[\"bgp_peers\"][peer][vrf][capability] = capability_output\n                    failures = deep_update(failures, failure)\n\n        # Check if there are any failures\n        if not failures[\"bgp_peers\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peer multiprotocol capabilities are not found or not ok:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerMPCaps-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpPeer] List of BGP peers -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerMPCaps-attributes","title":"BgpPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default' capabilities list[MultiProtocolCaps] List of multiprotocol capabilities to be verified. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerRouteRefreshCap","title":"VerifyBGPPeerRouteRefreshCap","text":"

Verifies the route refresh capabilities of a BGP peer in a specified VRF.

Expected Results
  • Success: The test will pass if the BGP peer\u2019s route refresh capabilities are advertised, received, and enabled in the specified VRF.
  • Failure: The test will fail if BGP peers are not found or route refresh capabilities are not advertised, received, and enabled in the specified VRF.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPPeerRouteRefreshCap:\n        bgp_peers:\n          - peer_address: 172.30.11.1\n            vrf: default\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPPeerRouteRefreshCap(AntaTest):\n    \"\"\"Verifies the route refresh capabilities of a BGP peer in a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the BGP peer's route refresh capabilities are advertised, received, and enabled in the specified VRF.\n    * Failure: The test will fail if BGP peers are not found or route refresh capabilities are not advertised, received, and enabled in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPPeerRouteRefreshCap:\n            bgp_peers:\n              - peer_address: 172.30.11.1\n                vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPPeerRouteRefreshCap\"\n    description = \"Verifies the route refresh capabilities of a BGP peer.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bgp neighbors vrf all\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPPeerRouteRefreshCap test.\"\"\"\n\n        bgp_peers: list[BgpPeer]\n        \"\"\"List of BGP peers\"\"\"\n\n        class BgpPeer(BaseModel):\n            \"\"\"Model for a BGP peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPPeerRouteRefreshCap.\"\"\"\n        failures: dict[str, Any] = {\"bgp_peers\": {}}\n\n        # Iterate over each bgp peer\n        for bgp_peer in self.inputs.bgp_peers:\n            peer = str(bgp_peer.peer_address)\n            vrf = bgp_peer.vrf\n            failure: dict[str, dict[str, dict[str, Any]]] = {\"bgp_peers\": {peer: {vrf: {}}}}\n\n            # Check if BGP output exists\n            if (\n                not (bgp_output := get_value(self.instance_commands[0].json_output, f\"vrfs.{vrf}.peerList\"))\n                or (bgp_output := get_item(bgp_output, \"peerAddress\", peer)) is None\n            ):\n                failure[\"bgp_peers\"][peer][vrf] = {\"status\": \"Not configured\"}\n                failures = deep_update(failures, failure)\n                continue\n\n            bgp_output = get_value(bgp_output, \"neighborCapabilities.routeRefreshCap\")\n\n            # Check if route refresh capabilities are found\n            if not bgp_output:\n                failure[\"bgp_peers\"][peer][vrf] = {\"routeRefreshCap\": \"not found\"}\n                failures = deep_update(failures, failure)\n\n            # Check if capabilities are not advertised, received, or enabled\n            elif not all(bgp_output.get(prop, False) for prop in [\"advertised\", \"received\", \"enabled\"]):\n                failure[\"bgp_peers\"][peer][vrf] = {\"routeRefreshCap\": bgp_output}\n                failures = deep_update(failures, failure)\n\n        # Check if there are any failures\n        if not failures[\"bgp_peers\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peer route refresh capabilities are not found or not ok:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerRouteRefreshCap-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpPeer] List of BGP peers -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeerRouteRefreshCap-attributes","title":"BgpPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default'"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeersHealth","title":"VerifyBGPPeersHealth","text":"

Verifies the health of BGP peers.

It will validate that all BGP sessions are established and all message queues for these BGP sessions are empty for a given address family.

It supports multiple types of Address Families Identifiers (AFI) and Subsequent Address Family Identifiers (SAFI).

For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6 (AFI) which is handled automatically in this test.

Please refer to the Input class attributes below for details.

Expected Results
  • Success: If all BGP sessions are established and all messages queues are empty for each address family and VRF.
  • Failure: If there are issues with any of the BGP sessions, or if BGP is not configured for an expected VRF or address family.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPPeersHealth:\n        address_families:\n          - afi: \"evpn\"\n          - afi: \"ipv4\"\n            safi: \"unicast\"\n            vrf: \"default\"\n          - afi: \"ipv6\"\n            safi: \"unicast\"\n            vrf: \"DEV\"\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPPeersHealth(AntaTest):\n    \"\"\"Verifies the health of BGP peers.\n\n    It will validate that all BGP sessions are established and all message queues for these BGP sessions are empty for a given address family.\n\n    It supports multiple types of Address Families Identifiers (AFI) and Subsequent Address Family Identifiers (SAFI).\n\n    For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6 (AFI) which is handled automatically in this test.\n\n    Please refer to the Input class attributes below for details.\n\n    Expected Results\n    ----------------\n    * Success: If all BGP sessions are established and all messages queues are empty for each address family and VRF.\n    * Failure: If there are issues with any of the BGP sessions, or if BGP is not configured for an expected VRF or address family.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPPeersHealth:\n            address_families:\n              - afi: \"evpn\"\n              - afi: \"ipv4\"\n                safi: \"unicast\"\n                vrf: \"default\"\n              - afi: \"ipv6\"\n                safi: \"unicast\"\n                vrf: \"DEV\"\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPPeersHealth\"\n    description = \"Verifies the health of BGP peers\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaTemplate(template=\"show bgp {afi} {safi} summary vrf {vrf}\", revision=3),\n        AntaTemplate(template=\"show bgp {afi} summary\", revision=3),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPPeersHealth test.\"\"\"\n\n        address_families: list[BgpAfi]\n        \"\"\"List of BGP address families (BgpAfi).\"\"\"\n\n        class BgpAfi(BaseModel):\n            \"\"\"Model for a BGP address family (AFI) and subsequent address family (SAFI).\"\"\"\n\n            afi: Afi\n            \"\"\"BGP address family (AFI).\"\"\"\n            safi: Safi | None = None\n            \"\"\"Optional BGP subsequent service family (SAFI).\n\n            If the input `afi` is `ipv4` or `ipv6`, a valid `safi` must be provided.\n            \"\"\"\n            vrf: str = \"default\"\n            \"\"\"\n            Optional VRF for IPv4 and IPv6. If not provided, it defaults to `default`.\n\n            If the input `afi` is not `ipv4` or `ipv6`, e.g. `evpn`, `vrf` must be `default`.\n            \"\"\"\n\n            @model_validator(mode=\"after\")\n            def validate_inputs(self: BaseModel) -> BaseModel:\n                \"\"\"Validate the inputs provided to the BgpAfi class.\n\n                If afi is either ipv4 or ipv6, safi must be provided.\n\n                If afi is not ipv4 or ipv6, safi must not be provided and vrf must be default.\n                \"\"\"\n                if self.afi in [\"ipv4\", \"ipv6\"]:\n                    if self.safi is None:\n                        msg = \"'safi' must be provided when afi is ipv4 or ipv6\"\n                        raise ValueError(msg)\n                elif self.safi is not None:\n                    msg = \"'safi' must not be provided when afi is not ipv4 or ipv6\"\n                    raise ValueError(msg)\n                elif self.vrf != \"default\":\n                    msg = \"'vrf' must be default when afi is not ipv4 or ipv6\"\n                    raise ValueError(msg)\n                return self\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each BGP address family in the input list.\"\"\"\n        commands = []\n        for afi in self.inputs.address_families:\n            if template == VerifyBGPPeersHealth.commands[0] and afi.afi in [\"ipv4\", \"ipv6\"] and afi.safi != \"sr-te\":\n                commands.append(template.render(afi=afi.afi, safi=afi.safi, vrf=afi.vrf))\n\n            # For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6\n            elif template == VerifyBGPPeersHealth.commands[0] and afi.afi in [\"ipv4\", \"ipv6\"] and afi.safi == \"sr-te\":\n                commands.append(template.render(afi=afi.safi, safi=afi.afi, vrf=afi.vrf))\n            elif template == VerifyBGPPeersHealth.commands[1] and afi.afi not in [\"ipv4\", \"ipv6\"]:\n                commands.append(template.render(afi=afi.afi))\n        return commands\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPPeersHealth.\"\"\"\n        self.result.is_success()\n\n        failures: dict[tuple[str, Any], dict[str, Any]] = {}\n\n        for command in self.instance_commands:\n            command_output = command.json_output\n\n            afi = command.params.afi\n            safi = command.params.safi if hasattr(command.params, \"safi\") else None\n            afi_vrf = command.params.vrf if hasattr(command.params, \"vrf\") else \"default\"\n\n            # Swapping AFI and SAFI in case of SR-TE\n            if afi == \"sr-te\":\n                afi, safi = safi, afi\n\n            if not (vrfs := command_output.get(\"vrfs\")):\n                _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=afi_vrf, issue=\"Not Configured\")\n                continue\n\n            for vrf, vrf_data in vrfs.items():\n                if not (peers := vrf_data.get(\"peers\")):\n                    _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=afi_vrf, issue=\"No Peers\")\n                    continue\n\n                peer_issues = {}\n                for peer, peer_data in peers.items():\n                    issues = _check_peer_issues(peer_data)\n\n                    if issues:\n                        peer_issues[peer] = issues\n\n                if peer_issues:\n                    _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=vrf, issue=peer_issues)\n\n        if failures:\n            self.result.is_failure(f\"Failures: {list(failures.values())}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeersHealth-attributes","title":"Inputs","text":"Name Type Description Default address_families list[BgpAfi] List of BGP address families (BgpAfi). -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPPeersHealth-attributes","title":"BgpAfi","text":"Name Type Description Default afi Afi BGP address family (AFI). - safi Safi | None Optional BGP subsequent service family (SAFI). If the input `afi` is `ipv4` or `ipv6`, a valid `safi` must be provided. None vrf str Optional VRF for IPv4 and IPv6. If not provided, it defaults to `default`. If the input `afi` is not `ipv4` or `ipv6`, e.g. `evpn`, `vrf` must be `default`. 'default'"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPSpecificPeers","title":"VerifyBGPSpecificPeers","text":"

Verifies the health of specific BGP peer(s).

It will validate that the BGP session is established and all message queues for this BGP session are empty for the given peer(s).

It supports multiple types of Address Families Identifiers (AFI) and Subsequent Address Family Identifiers (SAFI).

For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6 (AFI) which is handled automatically in this test.

Please refer to the Input class attributes below for details.

Expected Results
  • Success: If the BGP session is established and all messages queues are empty for each given peer.
  • Failure: If the BGP session has issues or is not configured, or if BGP is not configured for an expected VRF or address family.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPSpecificPeers:\n        address_families:\n          - afi: \"evpn\"\n            peers:\n              - 10.1.0.1\n              - 10.1.0.2\n          - afi: \"ipv4\"\n            safi: \"unicast\"\n            peers:\n              - 10.1.254.1\n              - 10.1.255.0\n              - 10.1.255.2\n              - 10.1.255.4\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPSpecificPeers(AntaTest):\n    \"\"\"Verifies the health of specific BGP peer(s).\n\n    It will validate that the BGP session is established and all message queues for this BGP session are empty for the given peer(s).\n\n    It supports multiple types of Address Families Identifiers (AFI) and Subsequent Address Family Identifiers (SAFI).\n\n    For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6 (AFI) which is handled automatically in this test.\n\n    Please refer to the Input class attributes below for details.\n\n    Expected Results\n    ----------------\n    * Success: If the BGP session is established and all messages queues are empty for each given peer.\n    * Failure: If the BGP session has issues or is not configured, or if BGP is not configured for an expected VRF or address family.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPSpecificPeers:\n            address_families:\n              - afi: \"evpn\"\n                peers:\n                  - 10.1.0.1\n                  - 10.1.0.2\n              - afi: \"ipv4\"\n                safi: \"unicast\"\n                peers:\n                  - 10.1.254.1\n                  - 10.1.255.0\n                  - 10.1.255.2\n                  - 10.1.255.4\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPSpecificPeers\"\n    description = \"Verifies the health of specific BGP peer(s).\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaTemplate(template=\"show bgp {afi} {safi} summary vrf {vrf}\", revision=3),\n        AntaTemplate(template=\"show bgp {afi} summary\", revision=3),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPSpecificPeers test.\"\"\"\n\n        address_families: list[BgpAfi]\n        \"\"\"List of BGP address families (BgpAfi).\"\"\"\n\n        class BgpAfi(BaseModel):\n            \"\"\"Model for a BGP address family (AFI) and subsequent address family (SAFI).\"\"\"\n\n            afi: Afi\n            \"\"\"BGP address family (AFI).\"\"\"\n            safi: Safi | None = None\n            \"\"\"Optional BGP subsequent service family (SAFI).\n\n            If the input `afi` is `ipv4` or `ipv6`, a valid `safi` must be provided.\n            \"\"\"\n            vrf: str = \"default\"\n            \"\"\"\n            Optional VRF for IPv4 and IPv6. If not provided, it defaults to `default`.\n\n            `all` is NOT supported.\n\n            If the input `afi` is not `ipv4` or `ipv6`, e.g. `evpn`, `vrf` must be `default`.\n            \"\"\"\n            peers: list[IPv4Address | IPv6Address]\n            \"\"\"List of BGP IPv4 or IPv6 peer.\"\"\"\n\n            @model_validator(mode=\"after\")\n            def validate_inputs(self: BaseModel) -> BaseModel:\n                \"\"\"Validate the inputs provided to the BgpAfi class.\n\n                If afi is either ipv4 or ipv6, safi must be provided and vrf must NOT be all.\n\n                If afi is not ipv4 or ipv6, safi must not be provided and vrf must be default.\n                \"\"\"\n                if self.afi in [\"ipv4\", \"ipv6\"]:\n                    if self.safi is None:\n                        msg = \"'safi' must be provided when afi is ipv4 or ipv6\"\n                        raise ValueError(msg)\n                    if self.vrf == \"all\":\n                        msg = \"'all' is not supported in this test. Use VerifyBGPPeersHealth test instead.\"\n                        raise ValueError(msg)\n                elif self.safi is not None:\n                    msg = \"'safi' must not be provided when afi is not ipv4 or ipv6\"\n                    raise ValueError(msg)\n                elif self.vrf != \"default\":\n                    msg = \"'vrf' must be default when afi is not ipv4 or ipv6\"\n                    raise ValueError(msg)\n                return self\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each BGP address family in the input list.\"\"\"\n        commands = []\n\n        for afi in self.inputs.address_families:\n            if template == VerifyBGPSpecificPeers.commands[0] and afi.afi in [\"ipv4\", \"ipv6\"] and afi.safi != \"sr-te\":\n                commands.append(template.render(afi=afi.afi, safi=afi.safi, vrf=afi.vrf))\n\n            # For SR-TE SAFI, the EOS command supports sr-te first then ipv4/ipv6\n            elif template == VerifyBGPSpecificPeers.commands[0] and afi.afi in [\"ipv4\", \"ipv6\"] and afi.safi == \"sr-te\":\n                commands.append(template.render(afi=afi.safi, safi=afi.afi, vrf=afi.vrf))\n            elif template == VerifyBGPSpecificPeers.commands[1] and afi.afi not in [\"ipv4\", \"ipv6\"]:\n                commands.append(template.render(afi=afi.afi))\n        return commands\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPSpecificPeers.\"\"\"\n        self.result.is_success()\n\n        failures: dict[tuple[str, Any], dict[str, Any]] = {}\n\n        for command in self.instance_commands:\n            command_output = command.json_output\n\n            afi = command.params.afi\n            safi = command.params.safi if hasattr(command.params, \"safi\") else None\n            afi_vrf = command.params.vrf if hasattr(command.params, \"vrf\") else \"default\"\n\n            # Swapping AFI and SAFI in case of SR-TE\n            if afi == \"sr-te\":\n                afi, safi = safi, afi\n\n            for input_entry in self.inputs.address_families:\n                if input_entry.afi == afi and input_entry.safi == safi and input_entry.vrf == afi_vrf:\n                    afi_peers = input_entry.peers\n                    break\n\n            if not (vrfs := command_output.get(\"vrfs\")):\n                _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=afi_vrf, issue=\"Not Configured\")\n                continue\n\n            peer_issues = {}\n            for peer in afi_peers:\n                peer_ip = str(peer)\n                peer_data = get_value(dictionary=vrfs, key=f\"{afi_vrf}_peers_{peer_ip}\", separator=\"_\")\n                issues = _check_peer_issues(peer_data)\n                if issues:\n                    peer_issues[peer_ip] = issues\n\n            if peer_issues:\n                _add_bgp_failures(failures=failures, afi=afi, safi=safi, vrf=afi_vrf, issue=peer_issues)\n\n        if failures:\n            self.result.is_failure(f\"Failures: {list(failures.values())}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPSpecificPeers-attributes","title":"Inputs","text":"Name Type Description Default address_families list[BgpAfi] List of BGP address families (BgpAfi). -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPSpecificPeers-attributes","title":"BgpAfi","text":"Name Type Description Default afi Afi BGP address family (AFI). - safi Safi | None Optional BGP subsequent service family (SAFI). If the input `afi` is `ipv4` or `ipv6`, a valid `safi` must be provided. None vrf str Optional VRF for IPv4 and IPv6. If not provided, it defaults to `default`. `all` is NOT supported. If the input `afi` is not `ipv4` or `ipv6`, e.g. `evpn`, `vrf` must be `default`. 'default' peers list[IPv4Address | IPv6Address] List of BGP IPv4 or IPv6 peer. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPTimers","title":"VerifyBGPTimers","text":"

Verifies if the BGP peers are configured with the correct hold and keep-alive timers in the specified VRF.

Expected Results
  • Success: The test will pass if the hold and keep-alive timers are correct for BGP peers in the specified VRF.
  • Failure: The test will fail if BGP peers are not found or hold and keep-alive timers are not correct in the specified VRF.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyBGPTimers:\n        bgp_peers:\n          - peer_address: 172.30.11.1\n            vrf: default\n            hold_time: 180\n            keep_alive_time: 60\n          - peer_address: 172.30.11.5\n            vrf: default\n            hold_time: 180\n            keep_alive_time: 60\n
Source code in anta/tests/routing/bgp.py
class VerifyBGPTimers(AntaTest):\n    \"\"\"Verifies if the BGP peers are configured with the correct hold and keep-alive timers in the specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the hold and keep-alive timers are correct for BGP peers in the specified VRF.\n    * Failure: The test will fail if BGP peers are not found or hold and keep-alive timers are not correct in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyBGPTimers:\n            bgp_peers:\n              - peer_address: 172.30.11.1\n                vrf: default\n                hold_time: 180\n                keep_alive_time: 60\n              - peer_address: 172.30.11.5\n                vrf: default\n                hold_time: 180\n                keep_alive_time: 60\n    ```\n    \"\"\"\n\n    name = \"VerifyBGPTimers\"\n    description = \"Verifies the timers of a BGP peer.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show bgp neighbors vrf all\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBGPTimers test.\"\"\"\n\n        bgp_peers: list[BgpPeer]\n        \"\"\"List of BGP peers\"\"\"\n\n        class BgpPeer(BaseModel):\n            \"\"\"Model for a BGP peer.\"\"\"\n\n            peer_address: IPv4Address\n            \"\"\"IPv4 address of a BGP peer.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for BGP peer. If not provided, it defaults to `default`.\"\"\"\n            hold_time: int = Field(ge=3, le=7200)\n            \"\"\"BGP hold time in seconds.\"\"\"\n            keep_alive_time: int = Field(ge=0, le=3600)\n            \"\"\"BGP keep-alive time in seconds.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBGPTimers.\"\"\"\n        failures: dict[str, Any] = {}\n\n        # Iterate over each bgp peer\n        for bgp_peer in self.inputs.bgp_peers:\n            peer_address = str(bgp_peer.peer_address)\n            vrf = bgp_peer.vrf\n            hold_time = bgp_peer.hold_time\n            keep_alive_time = bgp_peer.keep_alive_time\n\n            # Verify BGP peer\n            if (\n                not (bgp_output := get_value(self.instance_commands[0].json_output, f\"vrfs.{vrf}.peerList\"))\n                or (bgp_output := get_item(bgp_output, \"peerAddress\", peer_address)) is None\n            ):\n                failures[peer_address] = {vrf: \"Not configured\"}\n                continue\n\n            # Verify BGP peer's hold and keep alive timers\n            if bgp_output.get(\"holdTime\") != hold_time or bgp_output.get(\"keepaliveTime\") != keep_alive_time:\n                failures[peer_address] = {vrf: {\"hold_time\": bgp_output.get(\"holdTime\"), \"keep_alive_time\": bgp_output.get(\"keepaliveTime\")}}\n\n        if not failures:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Following BGP peers are not configured or hold and keep-alive timers are not correct:\\n{failures}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPTimers-attributes","title":"Inputs","text":"Name Type Description Default bgp_peers list[BgpPeer] List of BGP peers -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyBGPTimers-attributes","title":"BgpPeer","text":"Name Type Description Default peer_address IPv4Address IPv4 address of a BGP peer. - vrf str Optional VRF for BGP peer. If not provided, it defaults to `default`. 'default' hold_time int BGP hold time in seconds. Field(ge=3, le=7200) keep_alive_time int BGP keep-alive time in seconds. Field(ge=0, le=3600)"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyEVPNType2Route","title":"VerifyEVPNType2Route","text":"

Verifies the EVPN Type-2 routes for a given IPv4 or MAC address and VNI.

Expected Results
  • Success: If all provided VXLAN endpoints have at least one valid and active path to their EVPN Type-2 routes.
  • Failure: If any of the provided VXLAN endpoints do not have at least one valid and active path to their EVPN Type-2 routes.
Examples
anta.tests.routing:\n  bgp:\n    - VerifyEVPNType2Route:\n        vxlan_endpoints:\n          - address: 192.168.20.102\n            vni: 10020\n          - address: aac1.ab5d.b41e\n            vni: 10010\n
Source code in anta/tests/routing/bgp.py
class VerifyEVPNType2Route(AntaTest):\n    \"\"\"Verifies the EVPN Type-2 routes for a given IPv4 or MAC address and VNI.\n\n    Expected Results\n    ----------------\n    * Success: If all provided VXLAN endpoints have at least one valid and active path to their EVPN Type-2 routes.\n    * Failure: If any of the provided VXLAN endpoints do not have at least one valid and active path to their EVPN Type-2 routes.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      bgp:\n        - VerifyEVPNType2Route:\n            vxlan_endpoints:\n              - address: 192.168.20.102\n                vni: 10020\n              - address: aac1.ab5d.b41e\n                vni: 10010\n    ```\n    \"\"\"\n\n    name = \"VerifyEVPNType2Route\"\n    description = \"Verifies the EVPN Type-2 routes for a given IPv4 or MAC address and VNI.\"\n    categories: ClassVar[list[str]] = [\"bgp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show bgp evpn route-type mac-ip {address} vni {vni}\", revision=2)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyEVPNType2Route test.\"\"\"\n\n        vxlan_endpoints: list[VxlanEndpoint]\n        \"\"\"List of VXLAN endpoints to verify.\"\"\"\n\n        class VxlanEndpoint(BaseModel):\n            \"\"\"Model for a VXLAN endpoint.\"\"\"\n\n            address: IPv4Address | MacAddress\n            \"\"\"IPv4 or MAC address of the VXLAN endpoint.\"\"\"\n            vni: Vni\n            \"\"\"VNI of the VXLAN endpoint.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each VXLAN endpoint in the input list.\"\"\"\n        return [template.render(address=str(endpoint.address), vni=endpoint.vni) for endpoint in self.inputs.vxlan_endpoints]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyEVPNType2Route.\"\"\"\n        self.result.is_success()\n        no_evpn_routes = []\n        bad_evpn_routes = []\n\n        for command in self.instance_commands:\n            address = command.params.address\n            vni = command.params.vni\n            # Verify that the VXLAN endpoint is in the BGP EVPN table\n            evpn_routes = command.json_output[\"evpnRoutes\"]\n            if not evpn_routes:\n                no_evpn_routes.append((address, vni))\n                continue\n            # Verify that each EVPN route has at least one valid and active path\n            for route, route_data in evpn_routes.items():\n                has_active_path = False\n                for path in route_data[\"evpnRoutePaths\"]:\n                    if path[\"routeType\"][\"valid\"] is True and path[\"routeType\"][\"active\"] is True:\n                        # At least one path is valid and active, no need to check the other paths\n                        has_active_path = True\n                        break\n                if not has_active_path:\n                    bad_evpn_routes.append(route)\n\n        if no_evpn_routes:\n            self.result.is_failure(f\"The following VXLAN endpoint do not have any EVPN Type-2 route: {no_evpn_routes}\")\n        if bad_evpn_routes:\n            self.result.is_failure(f\"The following EVPN Type-2 routes do not have at least one valid and active path: {bad_evpn_routes}\")\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyEVPNType2Route-attributes","title":"Inputs","text":"Name Type Description Default vxlan_endpoints list[VxlanEndpoint] List of VXLAN endpoints to verify. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp.VerifyEVPNType2Route-attributes","title":"VxlanEndpoint","text":"Name Type Description Default address IPv4Address | MacAddress IPv4 or MAC address of the VXLAN endpoint. - vni Vni VNI of the VXLAN endpoint. -"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp._add_bgp_failures","title":"_add_bgp_failures","text":"
_add_bgp_failures(failures: dict[tuple[str, str | None], dict[str, Any]], afi: Afi, safi: Safi | None, vrf: str, issue: str | dict[str, Any]) -> None\n

Add a BGP failure entry to the given failures dictionary.

Note: This function modifies failures in-place.

Example:

The failures dictionary will have the following structure: { (\u2018afi1\u2019, \u2018safi1\u2019): { \u2018afi\u2019: \u2018afi1\u2019, \u2018safi\u2019: \u2018safi1\u2019, \u2018vrfs\u2019: { \u2018vrf1\u2019: issue1, \u2018vrf2\u2019: issue2 } }, (\u2018afi2\u2019, None): { \u2018afi\u2019: \u2018afi2\u2019, \u2018vrfs\u2019: { \u2018vrf1\u2019: issue3 } } }

Source code in anta/tests/routing/bgp.py
def _add_bgp_failures(failures: dict[tuple[str, str | None], dict[str, Any]], afi: Afi, safi: Safi | None, vrf: str, issue: str | dict[str, Any]) -> None:\n    \"\"\"Add a BGP failure entry to the given `failures` dictionary.\n\n    Note: This function modifies `failures` in-place.\n\n    Parameters\n    ----------\n        failures: The dictionary to which the failure will be added.\n        afi: The address family identifier.\n        vrf: The VRF name.\n        safi: The subsequent address family identifier.\n        issue: A description of the issue. Can be of any type.\n\n    Example:\n    -------\n    The `failures` dictionary will have the following structure:\n        {\n            ('afi1', 'safi1'): {\n                'afi': 'afi1',\n                'safi': 'safi1',\n                'vrfs': {\n                    'vrf1': issue1,\n                    'vrf2': issue2\n                }\n            },\n            ('afi2', None): {\n                'afi': 'afi2',\n                'vrfs': {\n                    'vrf1': issue3\n                }\n            }\n        }\n\n    \"\"\"\n    key = (afi, safi)\n\n    failure_entry = failures.setdefault(key, {\"afi\": afi, \"safi\": safi, \"vrfs\": {}}) if safi else failures.setdefault(key, {\"afi\": afi, \"vrfs\": {}})\n\n    failure_entry[\"vrfs\"][vrf] = issue\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp._add_bgp_routes_failure","title":"_add_bgp_routes_failure","text":"
_add_bgp_routes_failure(bgp_routes: list[str], bgp_output: dict[str, Any], peer: str, vrf: str, route_type: str = 'advertised_routes') -> dict[str, dict[str, dict[str, dict[str, list[str]]]]]\n

Identify missing BGP routes and invalid or inactive route entries.

This function checks the BGP output from the device against the expected routes.

It identifies any missing routes as well as any routes that are invalid or inactive. The results are returned in a dictionary.

Returns:

Type Description dict[str, dict[str, dict[str, dict[str, list[str]]]]]: A dictionary containing the missing routes and invalid or inactive routes. Source code in anta/tests/routing/bgp.py
def _add_bgp_routes_failure(\n    bgp_routes: list[str], bgp_output: dict[str, Any], peer: str, vrf: str, route_type: str = \"advertised_routes\"\n) -> dict[str, dict[str, dict[str, dict[str, list[str]]]]]:\n    \"\"\"Identify missing BGP routes and invalid or inactive route entries.\n\n    This function checks the BGP output from the device against the expected routes.\n\n    It identifies any missing routes as well as any routes that are invalid or inactive. The results are returned in a dictionary.\n\n    Parameters\n    ----------\n        bgp_routes: The list of expected routes.\n        bgp_output: The BGP output from the device.\n        peer: The IP address of the BGP peer.\n        vrf: The name of the VRF for which the routes need to be verified.\n        route_type: The type of BGP routes. Defaults to 'advertised_routes'.\n\n    Returns\n    -------\n        dict[str, dict[str, dict[str, dict[str, list[str]]]]]: A dictionary containing the missing routes and invalid or inactive routes.\n\n    \"\"\"\n    # Prepare the failure routes dictionary\n    failure_routes: dict[str, dict[str, Any]] = {}\n\n    # Iterate over the expected BGP routes\n    for route in bgp_routes:\n        str_route = str(route)\n        failure = {\"bgp_peers\": {peer: {vrf: {route_type: {str_route: Any}}}}}\n\n        # Check if the route is missing in the BGP output\n        if str_route not in bgp_output:\n            # If missing, add it to the failure routes dictionary\n            failure[\"bgp_peers\"][peer][vrf][route_type][str_route] = \"Not found\"\n            failure_routes = deep_update(failure_routes, failure)\n            continue\n\n        # Check if the route is active and valid\n        is_active = bgp_output[str_route][\"bgpRoutePaths\"][0][\"routeType\"][\"valid\"]\n        is_valid = bgp_output[str_route][\"bgpRoutePaths\"][0][\"routeType\"][\"active\"]\n\n        # If the route is either inactive or invalid, add it to the failure routes dictionary\n        if not is_active or not is_valid:\n            failure[\"bgp_peers\"][peer][vrf][route_type][str_route] = {\"valid\": is_valid, \"active\": is_active}\n            failure_routes = deep_update(failure_routes, failure)\n\n    return failure_routes\n
"},{"location":"api/tests.routing.bgp/#anta.tests.routing.bgp._check_peer_issues","title":"_check_peer_issues","text":"
_check_peer_issues(peer_data: dict[str, Any] | None) -> dict[str, Any]\n

Check for issues in BGP peer data.

Returns:

Type Description dict: Dictionary with keys indicating issues or an empty dictionary if no issues.

Raises:

Type Description ValueError: If any of the required keys (\"peerState\", \"inMsgQueue\", \"outMsgQueue\") are missing in `peer_data`, i.e. invalid BGP peer data. Example:
{\"peerNotFound\": True}\n{\"peerState\": \"Idle\", \"inMsgQueue\": 2, \"outMsgQueue\": 0}\n{}\n
Source code in anta/tests/routing/bgp.py
def _check_peer_issues(peer_data: dict[str, Any] | None) -> dict[str, Any]:\n    \"\"\"Check for issues in BGP peer data.\n\n    Parameters\n    ----------\n        peer_data: The BGP peer data dictionary nested in the `show bgp <afi> <safi> summary` command.\n\n    Returns\n    -------\n        dict: Dictionary with keys indicating issues or an empty dictionary if no issues.\n\n    Raises\n    ------\n        ValueError: If any of the required keys (\"peerState\", \"inMsgQueue\", \"outMsgQueue\") are missing in `peer_data`, i.e. invalid BGP peer data.\n\n    Example:\n    -------\n        {\"peerNotFound\": True}\n        {\"peerState\": \"Idle\", \"inMsgQueue\": 2, \"outMsgQueue\": 0}\n        {}\n\n    \"\"\"\n    if peer_data is None:\n        return {\"peerNotFound\": True}\n\n    if any(key not in peer_data for key in [\"peerState\", \"inMsgQueue\", \"outMsgQueue\"]):\n        msg = \"Provided BGP peer data is invalid.\"\n        raise ValueError(msg)\n\n    if peer_data[\"peerState\"] != \"Established\" or peer_data[\"inMsgQueue\"] != 0 or peer_data[\"outMsgQueue\"] != 0:\n        return {\"peerState\": peer_data[\"peerState\"], \"inMsgQueue\": peer_data[\"inMsgQueue\"], \"outMsgQueue\": peer_data[\"outMsgQueue\"]}\n\n    return {}\n
"},{"location":"api/tests.routing.generic/","title":"Generic","text":""},{"location":"api/tests.routing.generic/#anta.tests.routing.generic.VerifyRoutingProtocolModel","title":"VerifyRoutingProtocolModel","text":"

Verifies the configured routing protocol model is the one we expect.

Expected Results
  • Success: The test will pass if the configured routing protocol model is the one we expect.
  • Failure: The test will fail if the configured routing protocol model is not the one we expect.
Examples
anta.tests.routing:\n  generic:\n    - VerifyRoutingProtocolModel:\n        model: multi-agent\n
Source code in anta/tests/routing/generic.py
class VerifyRoutingProtocolModel(AntaTest):\n    \"\"\"Verifies the configured routing protocol model is the one we expect.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the configured routing protocol model is the one we expect.\n    * Failure: The test will fail if the configured routing protocol model is not the one we expect.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      generic:\n        - VerifyRoutingProtocolModel:\n            model: multi-agent\n    ```\n    \"\"\"\n\n    name = \"VerifyRoutingProtocolModel\"\n    description = \"Verifies the configured routing protocol model.\"\n    categories: ClassVar[list[str]] = [\"routing\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip route summary\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyRoutingProtocolModel test.\"\"\"\n\n        model: Literal[\"multi-agent\", \"ribd\"] = \"multi-agent\"\n        \"\"\"Expected routing protocol model. Defaults to `multi-agent`.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyRoutingProtocolModel.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        configured_model = command_output[\"protoModelStatus\"][\"configuredProtoModel\"]\n        operating_model = command_output[\"protoModelStatus\"][\"operatingProtoModel\"]\n        if configured_model == operating_model == self.inputs.model:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"routing model is misconfigured: configured: {configured_model} - operating: {operating_model} - expected: {self.inputs.model}\")\n
"},{"location":"api/tests.routing.generic/#anta.tests.routing.generic.VerifyRoutingProtocolModel-attributes","title":"Inputs","text":"Name Type Description Default model Literal['multi-agent', 'ribd'] Expected routing protocol model. Defaults to `multi-agent`. 'multi-agent'"},{"location":"api/tests.routing.generic/#anta.tests.routing.generic.VerifyRoutingTableEntry","title":"VerifyRoutingTableEntry","text":"

Verifies that the provided routes are present in the routing table of a specified VRF.

Expected Results
  • Success: The test will pass if the provided routes are present in the routing table.
  • Failure: The test will fail if one or many provided routes are missing from the routing table.
Examples
anta.tests.routing:\n  generic:\n    - VerifyRoutingTableEntry:\n        vrf: default\n        routes:\n          - 10.1.0.1\n          - 10.1.0.2\n
Source code in anta/tests/routing/generic.py
class VerifyRoutingTableEntry(AntaTest):\n    \"\"\"Verifies that the provided routes are present in the routing table of a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the provided routes are present in the routing table.\n    * Failure: The test will fail if one or many provided routes are missing from the routing table.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      generic:\n        - VerifyRoutingTableEntry:\n            vrf: default\n            routes:\n              - 10.1.0.1\n              - 10.1.0.2\n    ```\n    \"\"\"\n\n    name = \"VerifyRoutingTableEntry\"\n    description = \"Verifies that the provided routes are present in the routing table of a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"routing\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show ip route vrf {vrf} {route}\", revision=4)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyRoutingTableEntry test.\"\"\"\n\n        vrf: str = \"default\"\n        \"\"\"VRF context. Defaults to `default` VRF.\"\"\"\n        routes: list[IPv4Address]\n        \"\"\"List of routes to verify.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each route in the input list.\"\"\"\n        return [template.render(vrf=self.inputs.vrf, route=route) for route in self.inputs.routes]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyRoutingTableEntry.\"\"\"\n        missing_routes = []\n\n        for command in self.instance_commands:\n            vrf, route = command.params.vrf, command.params.route\n            if len(routes := command.json_output[\"vrfs\"][vrf][\"routes\"]) == 0 or route != ip_interface(next(iter(routes))).ip:\n                missing_routes.append(str(route))\n\n        if not missing_routes:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"The following route(s) are missing from the routing table of VRF {self.inputs.vrf}: {missing_routes}\")\n
"},{"location":"api/tests.routing.generic/#anta.tests.routing.generic.VerifyRoutingTableEntry-attributes","title":"Inputs","text":"Name Type Description Default vrf str VRF context. Defaults to `default` VRF. 'default' routes list[IPv4Address] List of routes to verify. -"},{"location":"api/tests.routing.generic/#anta.tests.routing.generic.VerifyRoutingTableSize","title":"VerifyRoutingTableSize","text":"

Verifies the size of the IP routing table of the default VRF.

Expected Results
  • Success: The test will pass if the routing table size is between the provided minimum and maximum values.
  • Failure: The test will fail if the routing table size is not between the provided minimum and maximum values.
Examples
anta.tests.routing:\n  generic:\n    - VerifyRoutingTableSize:\n        minimum: 2\n        maximum: 20\n
Source code in anta/tests/routing/generic.py
class VerifyRoutingTableSize(AntaTest):\n    \"\"\"Verifies the size of the IP routing table of the default VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the routing table size is between the provided minimum and maximum values.\n    * Failure: The test will fail if the routing table size is not between the provided minimum and maximum values.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      generic:\n        - VerifyRoutingTableSize:\n            minimum: 2\n            maximum: 20\n    ```\n    \"\"\"\n\n    name = \"VerifyRoutingTableSize\"\n    description = \"Verifies the size of the IP routing table of the default VRF.\"\n    categories: ClassVar[list[str]] = [\"routing\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip route summary\", revision=3)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyRoutingTableSize test.\"\"\"\n\n        minimum: int\n        \"\"\"Expected minimum routing table size.\"\"\"\n        maximum: int\n        \"\"\"Expected maximum routing table size.\"\"\"\n\n        @model_validator(mode=\"after\")  # type: ignore[misc]\n        def check_min_max(self) -> AntaTest.Input:\n            \"\"\"Validate that maximum is greater than minimum.\"\"\"\n            if self.minimum > self.maximum:\n                msg = f\"Minimum {self.minimum} is greater than maximum {self.maximum}\"\n                raise ValueError(msg)\n            return self\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyRoutingTableSize.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        total_routes = int(command_output[\"vrfs\"][\"default\"][\"totalRoutes\"])\n        if self.inputs.minimum <= total_routes <= self.inputs.maximum:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"routing-table has {total_routes} routes and not between min ({self.inputs.minimum}) and maximum ({self.inputs.maximum})\")\n
"},{"location":"api/tests.routing.generic/#anta.tests.routing.generic.VerifyRoutingTableSize-attributes","title":"Inputs","text":"Name Type Description Default minimum int Expected minimum routing table size. - maximum int Expected maximum routing table size. -"},{"location":"api/tests.routing.isis/","title":"ISIS","text":""},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISInterfaceMode","title":"VerifyISISInterfaceMode","text":"

Verifies ISIS Interfaces are running in correct mode.

Expected Results
  • Success: The test will pass if all listed interfaces are running in correct mode.
  • Failure: The test will fail if any of the listed interfaces is not running in correct mode.
  • Skipped: The test will be skipped if no ISIS neighbor is found.
Examples
anta.tests.routing:\n  isis:\n    - VerifyISISInterfaceMode:\n        interfaces:\n          - name: Loopback0\n            mode: passive\n            # vrf is set to default by default\n          - name: Ethernet2\n            mode: passive\n            level: 2\n            # vrf is set to default by default\n          - name: Ethernet1\n            mode: point-to-point\n            vrf: default\n            # level is set to 2 by default\n
Source code in anta/tests/routing/isis.py
class VerifyISISInterfaceMode(AntaTest):\n    \"\"\"Verifies ISIS Interfaces are running in correct mode.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all listed interfaces are running in correct mode.\n    * Failure: The test will fail if any of the listed interfaces is not running in correct mode.\n    * Skipped: The test will be skipped if no ISIS neighbor is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      isis:\n        - VerifyISISInterfaceMode:\n            interfaces:\n              - name: Loopback0\n                mode: passive\n                # vrf is set to default by default\n              - name: Ethernet2\n                mode: passive\n                level: 2\n                # vrf is set to default by default\n              - name: Ethernet1\n                mode: point-to-point\n                vrf: default\n                # level is set to 2 by default\n    ```\n    \"\"\"\n\n    name = \"VerifyISISInterfaceMode\"\n    description = \"Verifies interface mode for IS-IS\"\n    categories: ClassVar[list[str]] = [\"isis\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show isis interface brief\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyISISNeighborCount test.\"\"\"\n\n        interfaces: list[InterfaceState]\n        \"\"\"list of interfaces with their information.\"\"\"\n\n        class InterfaceState(BaseModel):\n            \"\"\"Input model for the VerifyISISNeighborCount test.\"\"\"\n\n            name: Interface\n            \"\"\"Interface name to check.\"\"\"\n            level: Literal[1, 2] = 2\n            \"\"\"ISIS level configured for interface. Default is 2.\"\"\"\n            mode: Literal[\"point-to-point\", \"broadcast\", \"passive\"]\n            \"\"\"Number of IS-IS neighbors.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"VRF where the interface should be configured\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyISISInterfaceMode.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n\n        if len(command_output[\"vrfs\"]) == 0:\n            self.result.is_skipped(\"IS-IS is not configured on device\")\n            return\n\n        # Check for p2p interfaces\n        for interface in self.inputs.interfaces:\n            interface_data = _get_interface_data(\n                interface=interface.name,\n                vrf=interface.vrf,\n                command_output=command_output,\n            )\n            # Check for correct VRF\n            if interface_data is not None:\n                interface_type = get_value(dictionary=interface_data, key=\"interfaceType\", default=\"unset\")\n                # Check for interfaceType\n                if interface.mode == \"point-to-point\" and interface.mode != interface_type:\n                    self.result.is_failure(f\"Interface {interface.name} in VRF {interface.vrf} is not running in {interface.mode} reporting {interface_type}\")\n                # Check for passive\n                elif interface.mode == \"passive\":\n                    json_path = f\"intfLevels.{interface.level}.passive\"\n                    if interface_data is None or get_value(dictionary=interface_data, key=json_path, default=False) is False:\n                        self.result.is_failure(f\"Interface {interface.name} in VRF {interface.vrf} is not running in passive mode\")\n            else:\n                self.result.is_failure(f\"Interface {interface.name} not found in VRF {interface.vrf}\")\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISInterfaceMode-attributes","title":"Inputs","text":"Name Type Description Default interfaces list[InterfaceState] list of interfaces with their information. -"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISInterfaceMode-attributes","title":"InterfaceState","text":"Name Type Description Default name Interface Interface name to check. - level Literal[1, 2] ISIS level configured for interface. Default is 2. 2 mode Literal['point-to-point', 'broadcast', 'passive'] Number of IS-IS neighbors. - vrf str VRF where the interface should be configured 'default'"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISNeighborCount","title":"VerifyISISNeighborCount","text":"

Verifies number of IS-IS neighbors per level and per interface.

Expected Results
  • Success: The test will pass if the number of neighbors is correct.
  • Failure: The test will fail if the number of neighbors is incorrect.
  • Skipped: The test will be skipped if no IS-IS neighbor is found.
Examples
anta.tests.routing:\n  isis:\n    - VerifyISISNeighborCount:\n        interfaces:\n          - name: Ethernet1\n            level: 1\n            count: 2\n          - name: Ethernet2\n            level: 2\n            count: 1\n          - name: Ethernet3\n            count: 2\n            # level is set to 2 by default\n
Source code in anta/tests/routing/isis.py
class VerifyISISNeighborCount(AntaTest):\n    \"\"\"Verifies number of IS-IS neighbors per level and per interface.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the number of neighbors is correct.\n    * Failure: The test will fail if the number of neighbors is incorrect.\n    * Skipped: The test will be skipped if no IS-IS neighbor is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      isis:\n        - VerifyISISNeighborCount:\n            interfaces:\n              - name: Ethernet1\n                level: 1\n                count: 2\n              - name: Ethernet2\n                level: 2\n                count: 1\n              - name: Ethernet3\n                count: 2\n                # level is set to 2 by default\n    ```\n    \"\"\"\n\n    name = \"VerifyISISNeighborCount\"\n    description = \"Verifies count of IS-IS interface per level\"\n    categories: ClassVar[list[str]] = [\"isis\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show isis interface brief\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyISISNeighborCount test.\"\"\"\n\n        interfaces: list[InterfaceCount]\n        \"\"\"list of interfaces with their information.\"\"\"\n\n        class InterfaceCount(BaseModel):\n            \"\"\"Input model for the VerifyISISNeighborCount test.\"\"\"\n\n            name: Interface\n            \"\"\"Interface name to check.\"\"\"\n            level: int = 2\n            \"\"\"IS-IS level to check.\"\"\"\n            count: int\n            \"\"\"Number of IS-IS neighbors.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyISISNeighborCount.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n        isis_neighbor_count = _get_isis_neighbors_count(command_output)\n        if len(isis_neighbor_count) == 0:\n            self.result.is_skipped(\"No IS-IS neighbor detected\")\n            return\n        for interface in self.inputs.interfaces:\n            eos_data = [ifl_data for ifl_data in isis_neighbor_count if ifl_data[\"interface\"] == interface.name and ifl_data[\"level\"] == interface.level]\n            if not eos_data:\n                self.result.is_failure(f\"No neighbor detected for interface {interface.name}\")\n                continue\n            if eos_data[0][\"count\"] != interface.count:\n                self.result.is_failure(\n                    f\"Interface {interface.name}: \"\n                    f\"expected Level {interface.level}: count {interface.count}, \"\n                    f\"got Level {eos_data[0]['level']}: count {eos_data[0]['count']}\"\n                )\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISNeighborCount-attributes","title":"Inputs","text":"Name Type Description Default interfaces list[InterfaceCount] list of interfaces with their information. -"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISNeighborCount-attributes","title":"InterfaceCount","text":"Name Type Description Default name Interface Interface name to check. - level int IS-IS level to check. 2 count int Number of IS-IS neighbors. -"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISNeighborState","title":"VerifyISISNeighborState","text":"

Verifies all IS-IS neighbors are in UP state.

Expected Results
  • Success: The test will pass if all IS-IS neighbors are in UP state.
  • Failure: The test will fail if some IS-IS neighbors are not in UP state.
  • Skipped: The test will be skipped if no IS-IS neighbor is found.
Examples
anta.tests.routing:\n  isis:\n    - VerifyISISNeighborState:\n
Source code in anta/tests/routing/isis.py
class VerifyISISNeighborState(AntaTest):\n    \"\"\"Verifies all IS-IS neighbors are in UP state.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all IS-IS neighbors are in UP state.\n    * Failure: The test will fail if some IS-IS neighbors are not in UP state.\n    * Skipped: The test will be skipped if no IS-IS neighbor is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      isis:\n        - VerifyISISNeighborState:\n    ```\n    \"\"\"\n\n    name = \"VerifyISISNeighborState\"\n    description = \"Verifies all IS-IS neighbors are in UP state.\"\n    categories: ClassVar[list[str]] = [\"isis\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show isis neighbors\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyISISNeighborState.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if _count_isis_neighbor(command_output) == 0:\n            self.result.is_skipped(\"No IS-IS neighbor detected\")\n            return\n        self.result.is_success()\n        not_full_neighbors = _get_not_full_isis_neighbors(command_output)\n        if not_full_neighbors:\n            self.result.is_failure(f\"Some neighbors are not in the correct state (UP): {not_full_neighbors}.\")\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingAdjacencySegments","title":"VerifyISISSegmentRoutingAdjacencySegments","text":"

Verifies ISIS Segment Routing Adjacency Segments.

Verify that all expected Adjacency segments are correctly visible for each interface.

Expected Results
  • Success: The test will pass if all listed interfaces have correct adjacencies.
  • Failure: The test will fail if any of the listed interfaces has not expected list of adjacencies.
  • Skipped: The test will be skipped if no ISIS SR Adjacency is found.
Examples
anta.tests.routing:\n  isis:\n    - VerifyISISSegmentRoutingAdjacencySegments:\n        instances:\n          - name: CORE-ISIS\n            vrf: default\n            segments:\n              - interface: Ethernet2\n                address: 10.0.1.3\n                sid_origin: dynamic\n
Source code in anta/tests/routing/isis.py
class VerifyISISSegmentRoutingAdjacencySegments(AntaTest):\n    \"\"\"Verifies ISIS Segment Routing Adjacency Segments.\n\n    Verify that all expected Adjacency segments are correctly visible for each interface.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all listed interfaces have correct adjacencies.\n    * Failure: The test will fail if any of the listed interfaces has not expected list of adjacencies.\n    * Skipped: The test will be skipped if no ISIS SR Adjacency is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      isis:\n        - VerifyISISSegmentRoutingAdjacencySegments:\n            instances:\n              - name: CORE-ISIS\n                vrf: default\n                segments:\n                  - interface: Ethernet2\n                    address: 10.0.1.3\n                    sid_origin: dynamic\n\n    ```\n    \"\"\"\n\n    name = \"VerifyISISSegmentRoutingAdjacencySegments\"\n    description = \"Verify expected Adjacency segments are correctly visible for each interface.\"\n    categories: ClassVar[list[str]] = [\"isis\", \"segment-routing\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show isis segment-routing adjacency-segments\", ofmt=\"json\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyISISSegmentRoutingAdjacencySegments test.\"\"\"\n\n        instances: list[IsisInstance]\n\n        class IsisInstance(BaseModel):\n            \"\"\"ISIS Instance model definition.\"\"\"\n\n            name: str\n            \"\"\"ISIS instance name.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"VRF name where ISIS instance is configured.\"\"\"\n            segments: list[Segment]\n            \"\"\"List of Adjacency segments configured in this instance.\"\"\"\n\n            class Segment(BaseModel):\n                \"\"\"Segment model definition.\"\"\"\n\n                interface: Interface\n                \"\"\"Interface name to check.\"\"\"\n                level: Literal[1, 2] = 2\n                \"\"\"ISIS level configured for interface. Default is 2.\"\"\"\n                sid_origin: Literal[\"dynamic\"] = \"dynamic\"\n                \"\"\"Adjacency type\"\"\"\n                address: IPv4Address\n                \"\"\"IP address of remote end of segment.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyISISSegmentRoutingAdjacencySegments.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n\n        if len(command_output[\"vrfs\"]) == 0:\n            self.result.is_skipped(\"IS-IS is not configured on device\")\n            return\n\n        # initiate defaults\n        failure_message = []\n        skip_vrfs = []\n        skip_instances = []\n\n        # Check if VRFs and instances are present in output.\n        for instance in self.inputs.instances:\n            vrf_data = get_value(\n                dictionary=command_output,\n                key=f\"vrfs.{instance.vrf}\",\n                default=None,\n            )\n            if vrf_data is None:\n                skip_vrfs.append(instance.vrf)\n                failure_message.append(f\"VRF {instance.vrf} is not configured to run segment routging.\")\n\n            elif get_value(dictionary=vrf_data, key=f\"isisInstances.{instance.name}\", default=None) is None:\n                skip_instances.append(instance.name)\n                failure_message.append(f\"Instance {instance.name} is not found in vrf {instance.vrf}.\")\n\n        # Check Adjacency segments\n        for instance in self.inputs.instances:\n            if instance.vrf not in skip_vrfs and instance.name not in skip_instances:\n                for input_segment in instance.segments:\n                    eos_segment = _get_adjacency_segment_data_by_neighbor(\n                        neighbor=str(input_segment.address),\n                        instance=instance.name,\n                        vrf=instance.vrf,\n                        command_output=command_output,\n                    )\n                    if eos_segment is None:\n                        failure_message.append(f\"Your segment has not been found: {input_segment}.\")\n\n                    elif (\n                        eos_segment[\"localIntf\"] != input_segment.interface\n                        or eos_segment[\"level\"] != input_segment.level\n                        or eos_segment[\"sidOrigin\"] != input_segment.sid_origin\n                    ):\n                        failure_message.append(f\"Your segment is not correct: Expected: {input_segment} - Found: {eos_segment}.\")\n        if failure_message:\n            self.result.is_failure(\"\\n\".join(failure_message))\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingAdjacencySegments-attributes","title":"Inputs","text":"Name Type Description Default"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingAdjacencySegments-attributes","title":"IsisInstance","text":"Name Type Description Default name str ISIS instance name. - vrf str VRF name where ISIS instance is configured. 'default' segments list[Segment] List of Adjacency segments configured in this instance. -"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingAdjacencySegments-attributes","title":"Segment","text":"Name Type Description Default interface Interface Interface name to check. - level Literal[1, 2] ISIS level configured for interface. Default is 2. 2 sid_origin Literal['dynamic'] Adjacency type 'dynamic' address IPv4Address IP address of remote end of segment. -"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingDataplane","title":"VerifyISISSegmentRoutingDataplane","text":"

Verify dataplane of a list of ISIS-SR instances.

Expected Results
  • Success: The test will pass if all instances have correct dataplane configured
  • Failure: The test will fail if one of the instances has incorrect dataplane configured
  • Skipped: The test will be skipped if ISIS is not running
Examples
anta.tests.routing:\n  isis:\n    - VerifyISISSegmentRoutingDataplane:\n        instances:\n          - name: CORE-ISIS\n            vrf: default\n            dataplane: MPLS\n
Source code in anta/tests/routing/isis.py
class VerifyISISSegmentRoutingDataplane(AntaTest):\n    \"\"\"\n    Verify dataplane of a list of ISIS-SR instances.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all instances have correct dataplane configured\n    * Failure: The test will fail if one of the instances has incorrect dataplane configured\n    * Skipped: The test will be skipped if ISIS is not running\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      isis:\n        - VerifyISISSegmentRoutingDataplane:\n            instances:\n              - name: CORE-ISIS\n                vrf: default\n                dataplane: MPLS\n    ```\n    \"\"\"\n\n    name = \"VerifyISISSegmentRoutingDataplane\"\n    description = \"Verify dataplane of a list of ISIS-SR instances\"\n    categories: ClassVar[list[str]] = [\"isis\", \"segment-routing\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show isis segment-routing\", ofmt=\"json\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyISISSegmentRoutingDataplane test.\"\"\"\n\n        instances: list[IsisInstance]\n\n        class IsisInstance(BaseModel):\n            \"\"\"ISIS Instance model definition.\"\"\"\n\n            name: str\n            \"\"\"ISIS instance name.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"VRF name where ISIS instance is configured.\"\"\"\n            dataplane: Literal[\"MPLS\", \"mpls\", \"unset\"] = \"MPLS\"\n            \"\"\"Configured dataplane for the instance.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyISISSegmentRoutingDataplane.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n\n        if len(command_output[\"vrfs\"]) == 0:\n            self.result.is_skipped(\"IS-IS-SR is not running on device.\")\n            return\n\n        # initiate defaults\n        failure_message = []\n        skip_vrfs = []\n        skip_instances = []\n\n        # Check if VRFs and instances are present in output.\n        for instance in self.inputs.instances:\n            vrf_data = get_value(\n                dictionary=command_output,\n                key=f\"vrfs.{instance.vrf}\",\n                default=None,\n            )\n            if vrf_data is None:\n                skip_vrfs.append(instance.vrf)\n                failure_message.append(f\"VRF {instance.vrf} is not configured to run segment routing.\")\n\n            elif get_value(dictionary=vrf_data, key=f\"isisInstances.{instance.name}\", default=None) is None:\n                skip_instances.append(instance.name)\n                failure_message.append(f\"Instance {instance.name} is not found in vrf {instance.vrf}.\")\n\n        # Check Adjacency segments\n        for instance in self.inputs.instances:\n            if instance.vrf not in skip_vrfs and instance.name not in skip_instances:\n                eos_dataplane = get_value(dictionary=command_output, key=f\"vrfs.{instance.vrf}.isisInstances.{instance.name}.dataPlane\", default=None)\n                if instance.dataplane.upper() != eos_dataplane:\n                    failure_message.append(f\"ISIS instance {instance.name} is not running dataplane {instance.dataplane} ({eos_dataplane})\")\n\n        if failure_message:\n            self.result.is_failure(\"\\n\".join(failure_message))\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingDataplane-attributes","title":"Inputs","text":"Name Type Description Default"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingDataplane-attributes","title":"IsisInstance","text":"Name Type Description Default name str ISIS instance name. - vrf str VRF name where ISIS instance is configured. 'default' dataplane Literal['MPLS', 'mpls', 'unset'] Configured dataplane for the instance. 'MPLS'"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingTunnels","title":"VerifyISISSegmentRoutingTunnels","text":"

Verify ISIS-SR tunnels computed by device.

Expected Results
  • Success: The test will pass if all listed tunnels are computed on device.
  • Failure: The test will fail if one of the listed tunnels is missing.
  • Skipped: The test will be skipped if ISIS-SR is not configured.
Examples
anta.tests.routing:\nisis:\n    - VerifyISISSegmentRoutingTunnels:\n        entries:\n        # Check only endpoint\n        - endpoint: 1.0.0.122/32\n        # Check endpoint and via TI-LFA\n        - endpoint: 1.0.0.13/32\n          vias:\n            - type: tunnel\n              tunnel_id: ti-lfa\n        # Check endpoint and via IP routers\n        - endpoint: 1.0.0.14/32\n          vias:\n            - type: ip\n              nexthop: 1.1.1.1\n
Source code in anta/tests/routing/isis.py
class VerifyISISSegmentRoutingTunnels(AntaTest):\n    \"\"\"\n    Verify ISIS-SR tunnels computed by device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all listed tunnels are computed on device.\n    * Failure: The test will fail if one of the listed tunnels is missing.\n    * Skipped: The test will be skipped if ISIS-SR is not configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n    isis:\n        - VerifyISISSegmentRoutingTunnels:\n            entries:\n            # Check only endpoint\n            - endpoint: 1.0.0.122/32\n            # Check endpoint and via TI-LFA\n            - endpoint: 1.0.0.13/32\n              vias:\n                - type: tunnel\n                  tunnel_id: ti-lfa\n            # Check endpoint and via IP routers\n            - endpoint: 1.0.0.14/32\n              vias:\n                - type: ip\n                  nexthop: 1.1.1.1\n    ```\n    \"\"\"\n\n    name = \"VerifyISISSegmentRoutingTunnels\"\n    description = \"Verify ISIS-SR tunnels computed by device\"\n    categories: ClassVar[list[str]] = [\"isis\", \"segment-routing\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show isis segment-routing tunnel\", ofmt=\"json\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyISISSegmentRoutingTunnels test.\"\"\"\n\n        entries: list[Entry]\n        \"\"\"List of tunnels to check on device.\"\"\"\n\n        class Entry(BaseModel):\n            \"\"\"Definition of a tunnel entry.\"\"\"\n\n            endpoint: IPv4Network\n            \"\"\"Endpoint IP of the tunnel.\"\"\"\n            vias: list[Vias] | None = None\n            \"\"\"Optional list of path to reach endpoint.\"\"\"\n\n            class Vias(BaseModel):\n                \"\"\"Definition of a tunnel path.\"\"\"\n\n                nexthop: IPv4Address | None = None\n                \"\"\"Nexthop of the tunnel. If None, then it is not tested. Default: None\"\"\"\n                type: Literal[\"ip\", \"tunnel\"] | None = None\n                \"\"\"Type of the tunnel. If None, then it is not tested. Default: None\"\"\"\n                interface: Interface | None = None\n                \"\"\"Interface of the tunnel. If None, then it is not tested. Default: None\"\"\"\n                tunnel_id: Literal[\"TI-LFA\", \"ti-lfa\", \"unset\"] | None = None\n                \"\"\"Computation method of the tunnel. If None, then it is not tested. Default: None\"\"\"\n\n    def _eos_entry_lookup(self, search_value: IPv4Network, entries: dict[str, Any], search_key: str = \"endpoint\") -> dict[str, Any] | None:\n        return next(\n            (entry_value for entry_id, entry_value in entries.items() if str(entry_value[search_key]) == str(search_value)),\n            None,\n        )\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyISISSegmentRoutingTunnels.\n\n        This method performs the main test logic for verifying ISIS Segment Routing tunnels.\n        It checks the command output, initiates defaults, and performs various checks on the tunnels.\n\n        Returns\n        -------\n            None\n        \"\"\"\n        command_output = self.instance_commands[0].json_output\n        self.result.is_success()\n\n        # initiate defaults\n        failure_message = []\n\n        if len(command_output[\"entries\"]) == 0:\n            self.result.is_skipped(\"IS-IS-SR is not running on device.\")\n            return\n\n        for input_entry in self.inputs.entries:\n            eos_entry = self._eos_entry_lookup(search_value=input_entry.endpoint, entries=command_output[\"entries\"])\n            if eos_entry is None:\n                failure_message.append(f\"Tunnel to {input_entry} is not found.\")\n            elif input_entry.vias is not None:\n                failure_src = []\n                for via_input in input_entry.vias:\n                    if not self._check_tunnel_type(via_input, eos_entry):\n                        failure_src.append(\"incorrect tunnel type\")\n                    if not self._check_tunnel_nexthop(via_input, eos_entry):\n                        failure_src.append(\"incorrect nexthop\")\n                    if not self._check_tunnel_interface(via_input, eos_entry):\n                        failure_src.append(\"incorrect interface\")\n                    if not self._check_tunnel_id(via_input, eos_entry):\n                        failure_src.append(\"incorrect tunnel ID\")\n\n                if failure_src:\n                    failure_message.append(f\"Tunnel to {input_entry.endpoint!s} is incorrect: {', '.join(failure_src)}\")\n\n        if failure_message:\n            self.result.is_failure(\"\\n\".join(failure_message))\n\n    def _check_tunnel_type(self, via_input: VerifyISISSegmentRoutingTunnels.Input.Entry.Vias, eos_entry: dict[str, Any]) -> bool:\n        \"\"\"\n        Check if the tunnel type specified in `via_input` matches any of the tunnel types in `eos_entry`.\n\n        Parameters\n        ----------\n            via_input (VerifyISISSegmentRoutingTunnels.Input.Entry.Vias): The input tunnel type to check.\n            eos_entry (dict[str, Any]): The EOS entry containing the tunnel types.\n\n        Returns\n        -------\n            bool: True if the tunnel type matches any of the tunnel types in `eos_entry`, False otherwise.\n        \"\"\"\n        if via_input.type is not None:\n            return any(\n                via_input.type\n                == get_value(\n                    dictionary=eos_via,\n                    key=\"type\",\n                    default=\"undefined\",\n                )\n                for eos_via in eos_entry[\"vias\"]\n            )\n        return True\n\n    def _check_tunnel_nexthop(self, via_input: VerifyISISSegmentRoutingTunnels.Input.Entry.Vias, eos_entry: dict[str, Any]) -> bool:\n        \"\"\"\n        Check if the tunnel nexthop matches the given input.\n\n        Parameters\n        ----------\n            via_input (VerifyISISSegmentRoutingTunnels.Input.Entry.Vias): The input via object.\n            eos_entry (dict[str, Any]): The EOS entry dictionary.\n\n        Returns\n        -------\n            bool: True if the tunnel nexthop matches, False otherwise.\n        \"\"\"\n        if via_input.nexthop is not None:\n            return any(\n                str(via_input.nexthop)\n                == get_value(\n                    dictionary=eos_via,\n                    key=\"nexthop\",\n                    default=\"undefined\",\n                )\n                for eos_via in eos_entry[\"vias\"]\n            )\n        return True\n\n    def _check_tunnel_interface(self, via_input: VerifyISISSegmentRoutingTunnels.Input.Entry.Vias, eos_entry: dict[str, Any]) -> bool:\n        \"\"\"\n        Check if the tunnel interface exists in the given EOS entry.\n\n        Parameters\n        ----------\n            via_input (VerifyISISSegmentRoutingTunnels.Input.Entry.Vias): The input via object.\n            eos_entry (dict[str, Any]): The EOS entry dictionary.\n\n        Returns\n        -------\n            bool: True if the tunnel interface exists, False otherwise.\n        \"\"\"\n        if via_input.interface is not None:\n            return any(\n                via_input.interface\n                == get_value(\n                    dictionary=eos_via,\n                    key=\"interface\",\n                    default=\"undefined\",\n                )\n                for eos_via in eos_entry[\"vias\"]\n            )\n        return True\n\n    def _check_tunnel_id(self, via_input: VerifyISISSegmentRoutingTunnels.Input.Entry.Vias, eos_entry: dict[str, Any]) -> bool:\n        \"\"\"\n        Check if the tunnel ID matches any of the tunnel IDs in the EOS entry's vias.\n\n        Parameters\n        ----------\n            via_input (VerifyISISSegmentRoutingTunnels.Input.Entry.Vias): The input vias to check.\n            eos_entry (dict[str, Any]): The EOS entry to compare against.\n\n        Returns\n        -------\n            bool: True if the tunnel ID matches any of the tunnel IDs in the EOS entry's vias, False otherwise.\n        \"\"\"\n        if via_input.tunnel_id is not None:\n            return any(\n                via_input.tunnel_id.upper()\n                == get_value(\n                    dictionary=eos_via,\n                    key=\"tunnelId.type\",\n                    default=\"undefined\",\n                ).upper()\n                for eos_via in eos_entry[\"vias\"]\n            )\n        return True\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingTunnels-attributes","title":"Inputs","text":"Name Type Description Default entries list[Entry] List of tunnels to check on device. -"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingTunnels-attributes","title":"Entry","text":"Name Type Description Default endpoint IPv4Network Endpoint IP of the tunnel. - vias list[Vias] | None Optional list of path to reach endpoint. None"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis.VerifyISISSegmentRoutingTunnels-attributes","title":"Vias","text":"Name Type Description Default nexthop IPv4Address | None Nexthop of the tunnel. If None, then it is not tested. Default: None None type Literal['ip', 'tunnel'] | None Type of the tunnel. If None, then it is not tested. Default: None None interface Interface | None Interface of the tunnel. If None, then it is not tested. Default: None None tunnel_id Literal['TI-LFA', 'ti-lfa', 'unset'] | None Computation method of the tunnel. If None, then it is not tested. Default: None None"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis._count_isis_neighbor","title":"_count_isis_neighbor","text":"
_count_isis_neighbor(isis_neighbor_json: dict[str, Any]) -> int\n

Count the number of isis neighbors.

Args

isis_neighbor_json: The JSON output of the show isis neighbors command.

Returns:

Type Description int: The number of isis neighbors. Source code in anta/tests/routing/isis.py
def _count_isis_neighbor(isis_neighbor_json: dict[str, Any]) -> int:\n    \"\"\"Count the number of isis neighbors.\n\n    Args\n    ----\n      isis_neighbor_json: The JSON output of the `show isis neighbors` command.\n\n    Returns\n    -------\n      int: The number of isis neighbors.\n\n    \"\"\"\n    count = 0\n    for vrf_data in isis_neighbor_json[\"vrfs\"].values():\n        for instance_data in vrf_data[\"isisInstances\"].values():\n            count += len(instance_data.get(\"neighbors\", {}))\n    return count\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis._get_adjacency_segment_data_by_neighbor","title":"_get_adjacency_segment_data_by_neighbor","text":"
_get_adjacency_segment_data_by_neighbor(neighbor: str, instance: str, vrf: str, command_output: dict[str, Any]) -> dict[str, Any] | None\n

Extract data related to an IS-IS interface for testing.

Source code in anta/tests/routing/isis.py
def _get_adjacency_segment_data_by_neighbor(neighbor: str, instance: str, vrf: str, command_output: dict[str, Any]) -> dict[str, Any] | None:\n    \"\"\"Extract data related to an IS-IS interface for testing.\"\"\"\n    search_path = f\"vrfs.{vrf}.isisInstances.{instance}.adjacencySegments\"\n    if get_value(dictionary=command_output, key=search_path, default=None) is None:\n        return None\n\n    isis_instance = get_value(dictionary=command_output, key=search_path, default=None)\n\n    return next(\n        (segment_data for segment_data in isis_instance if neighbor == segment_data[\"ipAddress\"]),\n        None,\n    )\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis._get_full_isis_neighbors","title":"_get_full_isis_neighbors","text":"
_get_full_isis_neighbors(isis_neighbor_json: dict[str, Any], neighbor_state: Literal['up', 'down'] = 'up') -> list[dict[str, Any]]\n

Return the isis neighbors whose adjacency state is up.

Args

isis_neighbor_json: The JSON output of the show isis neighbors command. neighbor_state: Value of the neihbor state we are looking for. Default up

Returns:

Type Description list[dict[str, Any]]: A list of isis neighbors whose adjacency state is not `UP`. Source code in anta/tests/routing/isis.py
def _get_full_isis_neighbors(isis_neighbor_json: dict[str, Any], neighbor_state: Literal[\"up\", \"down\"] = \"up\") -> list[dict[str, Any]]:\n    \"\"\"Return the isis neighbors whose adjacency state is `up`.\n\n    Args\n    ----\n      isis_neighbor_json: The JSON output of the `show isis neighbors` command.\n      neighbor_state: Value of the neihbor state we are looking for. Default up\n\n    Returns\n    -------\n      list[dict[str, Any]]: A list of isis neighbors whose adjacency state is not `UP`.\n\n    \"\"\"\n    return [\n        {\n            \"vrf\": vrf,\n            \"instance\": instance,\n            \"neighbor\": adjacency[\"hostname\"],\n            \"neighbor_address\": adjacency[\"routerIdV4\"],\n            \"interface\": adjacency[\"interfaceName\"],\n            \"state\": state,\n        }\n        for vrf, vrf_data in isis_neighbor_json[\"vrfs\"].items()\n        for instance, instance_data in vrf_data.get(\"isisInstances\").items()\n        for neighbor, neighbor_data in instance_data.get(\"neighbors\").items()\n        for adjacency in neighbor_data.get(\"adjacencies\")\n        if (state := adjacency[\"state\"]) == neighbor_state\n    ]\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis._get_interface_data","title":"_get_interface_data","text":"
_get_interface_data(interface: str, vrf: str, command_output: dict[str, Any]) -> dict[str, Any] | None\n

Extract data related to an IS-IS interface for testing.

Source code in anta/tests/routing/isis.py
def _get_interface_data(interface: str, vrf: str, command_output: dict[str, Any]) -> dict[str, Any] | None:\n    \"\"\"Extract data related to an IS-IS interface for testing.\"\"\"\n    if (vrf_data := get_value(command_output, f\"vrfs.{vrf}\")) is None:\n        return None\n\n    for instance_data in vrf_data.get(\"isisInstances\").values():\n        if (intf_dict := get_value(dictionary=instance_data, key=\"interfaces\")) is not None:\n            try:\n                return next(ifl_data for ifl, ifl_data in intf_dict.items() if ifl == interface)\n            except StopIteration:\n                return None\n    return None\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis._get_isis_neighbors_count","title":"_get_isis_neighbors_count","text":"
_get_isis_neighbors_count(isis_neighbor_json: dict[str, Any]) -> list[dict[str, Any]]\n

Count number of IS-IS neighbor of the device.

Source code in anta/tests/routing/isis.py
def _get_isis_neighbors_count(isis_neighbor_json: dict[str, Any]) -> list[dict[str, Any]]:\n    \"\"\"Count number of IS-IS neighbor of the device.\"\"\"\n    return [\n        {\"vrf\": vrf, \"interface\": interface, \"mode\": mode, \"count\": int(level_data[\"numAdjacencies\"]), \"level\": int(level)}\n        for vrf, vrf_data in isis_neighbor_json[\"vrfs\"].items()\n        for instance, instance_data in vrf_data.get(\"isisInstances\").items()\n        for interface, interface_data in instance_data.get(\"interfaces\").items()\n        for level, level_data in interface_data.get(\"intfLevels\").items()\n        if (mode := level_data[\"passive\"]) is not True\n    ]\n
"},{"location":"api/tests.routing.isis/#anta.tests.routing.isis._get_not_full_isis_neighbors","title":"_get_not_full_isis_neighbors","text":"
_get_not_full_isis_neighbors(isis_neighbor_json: dict[str, Any]) -> list[dict[str, Any]]\n

Return the isis neighbors whose adjacency state is not up.

Args

isis_neighbor_json: The JSON output of the show isis neighbors command.

Returns:

Type Description list[dict[str, Any]]: A list of isis neighbors whose adjacency state is not `UP`. Source code in anta/tests/routing/isis.py
def _get_not_full_isis_neighbors(isis_neighbor_json: dict[str, Any]) -> list[dict[str, Any]]:\n    \"\"\"Return the isis neighbors whose adjacency state is not `up`.\n\n    Args\n    ----\n      isis_neighbor_json: The JSON output of the `show isis neighbors` command.\n\n    Returns\n    -------\n      list[dict[str, Any]]: A list of isis neighbors whose adjacency state is not `UP`.\n\n    \"\"\"\n    return [\n        {\n            \"vrf\": vrf,\n            \"instance\": instance,\n            \"neighbor\": adjacency[\"hostname\"],\n            \"state\": state,\n        }\n        for vrf, vrf_data in isis_neighbor_json[\"vrfs\"].items()\n        for instance, instance_data in vrf_data.get(\"isisInstances\").items()\n        for neighbor, neighbor_data in instance_data.get(\"neighbors\").items()\n        for adjacency in neighbor_data.get(\"adjacencies\")\n        if (state := adjacency[\"state\"]) != \"up\"\n    ]\n
"},{"location":"api/tests.routing.ospf/","title":"OSPF","text":""},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf.VerifyOSPFMaxLSA","title":"VerifyOSPFMaxLSA","text":"

Verifies LSAs present in the OSPF link state database did not cross the maximum LSA Threshold.

Expected Results
  • Success: The test will pass if all OSPF instances did not cross the maximum LSA Threshold.
  • Failure: The test will fail if some OSPF instances crossed the maximum LSA Threshold.
  • Skipped: The test will be skipped if no OSPF instance is found.
Examples
anta.tests.routing:\n  ospf:\n    - VerifyOSPFMaxLSA:\n
Source code in anta/tests/routing/ospf.py
class VerifyOSPFMaxLSA(AntaTest):\n    \"\"\"Verifies LSAs present in the OSPF link state database did not cross the maximum LSA Threshold.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all OSPF instances did not cross the maximum LSA Threshold.\n    * Failure: The test will fail if some OSPF instances crossed the maximum LSA Threshold.\n    * Skipped: The test will be skipped if no OSPF instance is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      ospf:\n        - VerifyOSPFMaxLSA:\n    ```\n    \"\"\"\n\n    name = \"VerifyOSPFMaxLSA\"\n    description = \"Verifies all OSPF instances did not cross the maximum LSA threshold.\"\n    categories: ClassVar[list[str]] = [\"ospf\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip ospf\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyOSPFMaxLSA.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ospf_instance_info = _get_ospf_max_lsa_info(command_output)\n        if not ospf_instance_info:\n            self.result.is_skipped(\"No OSPF instance found.\")\n            return\n        all_instances_within_threshold = all(instance[\"numLsa\"] <= instance[\"maxLsa\"] * (instance[\"maxLsaThreshold\"] / 100) for instance in ospf_instance_info)\n        if all_instances_within_threshold:\n            self.result.is_success()\n        else:\n            exceeded_instances = [\n                instance[\"instance\"] for instance in ospf_instance_info if instance[\"numLsa\"] > instance[\"maxLsa\"] * (instance[\"maxLsaThreshold\"] / 100)\n            ]\n            self.result.is_failure(f\"OSPF Instances {exceeded_instances} crossed the maximum LSA threshold.\")\n
"},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf.VerifyOSPFNeighborCount","title":"VerifyOSPFNeighborCount","text":"

Verifies the number of OSPF neighbors in FULL state is the one we expect.

Expected Results
  • Success: The test will pass if the number of OSPF neighbors in FULL state is the one we expect.
  • Failure: The test will fail if the number of OSPF neighbors in FULL state is not the one we expect.
  • Skipped: The test will be skipped if no OSPF neighbor is found.
Examples
anta.tests.routing:\n  ospf:\n    - VerifyOSPFNeighborCount:\n        number: 3\n
Source code in anta/tests/routing/ospf.py
class VerifyOSPFNeighborCount(AntaTest):\n    \"\"\"Verifies the number of OSPF neighbors in FULL state is the one we expect.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the number of OSPF neighbors in FULL state is the one we expect.\n    * Failure: The test will fail if the number of OSPF neighbors in FULL state is not the one we expect.\n    * Skipped: The test will be skipped if no OSPF neighbor is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      ospf:\n        - VerifyOSPFNeighborCount:\n            number: 3\n    ```\n    \"\"\"\n\n    name = \"VerifyOSPFNeighborCount\"\n    description = \"Verifies the number of OSPF neighbors in FULL state is the one we expect.\"\n    categories: ClassVar[list[str]] = [\"ospf\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip ospf neighbor\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyOSPFNeighborCount test.\"\"\"\n\n        number: int\n        \"\"\"The expected number of OSPF neighbors in FULL state.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyOSPFNeighborCount.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if (neighbor_count := _count_ospf_neighbor(command_output)) == 0:\n            self.result.is_skipped(\"no OSPF neighbor found\")\n            return\n        self.result.is_success()\n        if neighbor_count != self.inputs.number:\n            self.result.is_failure(f\"device has {neighbor_count} neighbors (expected {self.inputs.number})\")\n        not_full_neighbors = _get_not_full_ospf_neighbors(command_output)\n        if not_full_neighbors:\n            self.result.is_failure(f\"Some neighbors are not correctly configured: {not_full_neighbors}.\")\n
"},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf.VerifyOSPFNeighborCount-attributes","title":"Inputs","text":"Name Type Description Default number int The expected number of OSPF neighbors in FULL state. -"},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf.VerifyOSPFNeighborState","title":"VerifyOSPFNeighborState","text":"

Verifies all OSPF neighbors are in FULL state.

Expected Results
  • Success: The test will pass if all OSPF neighbors are in FULL state.
  • Failure: The test will fail if some OSPF neighbors are not in FULL state.
  • Skipped: The test will be skipped if no OSPF neighbor is found.
Examples
anta.tests.routing:\n  ospf:\n    - VerifyOSPFNeighborState:\n
Source code in anta/tests/routing/ospf.py
class VerifyOSPFNeighborState(AntaTest):\n    \"\"\"Verifies all OSPF neighbors are in FULL state.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all OSPF neighbors are in FULL state.\n    * Failure: The test will fail if some OSPF neighbors are not in FULL state.\n    * Skipped: The test will be skipped if no OSPF neighbor is found.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.routing:\n      ospf:\n        - VerifyOSPFNeighborState:\n    ```\n    \"\"\"\n\n    name = \"VerifyOSPFNeighborState\"\n    description = \"Verifies all OSPF neighbors are in FULL state.\"\n    categories: ClassVar[list[str]] = [\"ospf\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip ospf neighbor\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyOSPFNeighborState.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if _count_ospf_neighbor(command_output) == 0:\n            self.result.is_skipped(\"no OSPF neighbor found\")\n            return\n        self.result.is_success()\n        not_full_neighbors = _get_not_full_ospf_neighbors(command_output)\n        if not_full_neighbors:\n            self.result.is_failure(f\"Some neighbors are not correctly configured: {not_full_neighbors}.\")\n
"},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf._count_ospf_neighbor","title":"_count_ospf_neighbor","text":"
_count_ospf_neighbor(ospf_neighbor_json: dict[str, Any]) -> int\n

Count the number of OSPF neighbors.

Returns:

Type Description int: The number of OSPF neighbors. Source code in anta/tests/routing/ospf.py
def _count_ospf_neighbor(ospf_neighbor_json: dict[str, Any]) -> int:\n    \"\"\"Count the number of OSPF neighbors.\n\n    Parameters\n    ----------\n      ospf_neighbor_json: The JSON output of the `show ip ospf neighbor` command.\n\n    Returns\n    -------\n      int: The number of OSPF neighbors.\n\n    \"\"\"\n    count = 0\n    for vrf_data in ospf_neighbor_json[\"vrfs\"].values():\n        for instance_data in vrf_data[\"instList\"].values():\n            count += len(instance_data.get(\"ospfNeighborEntries\", []))\n    return count\n
"},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf._get_not_full_ospf_neighbors","title":"_get_not_full_ospf_neighbors","text":"
_get_not_full_ospf_neighbors(ospf_neighbor_json: dict[str, Any]) -> list[dict[str, Any]]\n

Return the OSPF neighbors whose adjacency state is not full.

Returns:

Type Description list[dict[str, Any]]: A list of OSPF neighbors whose adjacency state is not `full`. Source code in anta/tests/routing/ospf.py
def _get_not_full_ospf_neighbors(ospf_neighbor_json: dict[str, Any]) -> list[dict[str, Any]]:\n    \"\"\"Return the OSPF neighbors whose adjacency state is not `full`.\n\n    Parameters\n    ----------\n      ospf_neighbor_json: The JSON output of the `show ip ospf neighbor` command.\n\n    Returns\n    -------\n      list[dict[str, Any]]: A list of OSPF neighbors whose adjacency state is not `full`.\n\n    \"\"\"\n    return [\n        {\n            \"vrf\": vrf,\n            \"instance\": instance,\n            \"neighbor\": neighbor_data[\"routerId\"],\n            \"state\": state,\n        }\n        for vrf, vrf_data in ospf_neighbor_json[\"vrfs\"].items()\n        for instance, instance_data in vrf_data[\"instList\"].items()\n        for neighbor_data in instance_data.get(\"ospfNeighborEntries\", [])\n        if (state := neighbor_data[\"adjacencyState\"]) != \"full\"\n    ]\n
"},{"location":"api/tests.routing.ospf/#anta.tests.routing.ospf._get_ospf_max_lsa_info","title":"_get_ospf_max_lsa_info","text":"
_get_ospf_max_lsa_info(ospf_process_json: dict[str, Any]) -> list[dict[str, Any]]\n

Return information about OSPF instances and their LSAs.

Returns:

Type Description list[dict[str, Any]]: A list of dictionaries containing OSPF LSAs information. Source code in anta/tests/routing/ospf.py
def _get_ospf_max_lsa_info(ospf_process_json: dict[str, Any]) -> list[dict[str, Any]]:\n    \"\"\"Return information about OSPF instances and their LSAs.\n\n    Parameters\n    ----------\n      ospf_process_json: OSPF process information in JSON format.\n\n    Returns\n    -------\n      list[dict[str, Any]]: A list of dictionaries containing OSPF LSAs information.\n\n    \"\"\"\n    return [\n        {\n            \"vrf\": vrf,\n            \"instance\": instance,\n            \"maxLsa\": instance_data.get(\"maxLsaInformation\", {}).get(\"maxLsa\"),\n            \"maxLsaThreshold\": instance_data.get(\"maxLsaInformation\", {}).get(\"maxLsaThreshold\"),\n            \"numLsa\": instance_data.get(\"lsaInformation\", {}).get(\"numLsa\"),\n        }\n        for vrf, vrf_data in ospf_process_json.get(\"vrfs\", {}).items()\n        for instance, instance_data in vrf_data.get(\"instList\", {}).items()\n    ]\n
"},{"location":"api/tests.security/","title":"Security","text":""},{"location":"api/tests.security/#anta.tests.security.VerifyAPIHttpStatus","title":"VerifyAPIHttpStatus","text":"

Verifies if eAPI HTTP server is disabled globally.

Expected Results
  • Success: The test will pass if eAPI HTTP server is disabled globally.
  • Failure: The test will fail if eAPI HTTP server is NOT disabled globally.
Examples
anta.tests.security:\n  - VerifyAPIHttpStatus:\n
Source code in anta/tests/security.py
class VerifyAPIHttpStatus(AntaTest):\n    \"\"\"Verifies if eAPI HTTP server is disabled globally.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if eAPI HTTP server is disabled globally.\n    * Failure: The test will fail if eAPI HTTP server is NOT disabled globally.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyAPIHttpStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifyAPIHttpStatus\"\n    description = \"Verifies if eAPI HTTP server is disabled globally.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management api http-commands\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAPIHttpStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"enabled\"] and not command_output[\"httpServer\"][\"running\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"eAPI HTTP server is enabled globally\")\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyAPIHttpsSSL","title":"VerifyAPIHttpsSSL","text":"

Verifies if eAPI HTTPS server SSL profile is configured and valid.

Expected Results
  • Success: The test will pass if the eAPI HTTPS server SSL profile is configured and valid.
  • Failure: The test will fail if the eAPI HTTPS server SSL profile is NOT configured, misconfigured or invalid.
Examples
anta.tests.security:\n  - VerifyAPIHttpsSSL:\n      profile: default\n
Source code in anta/tests/security.py
class VerifyAPIHttpsSSL(AntaTest):\n    \"\"\"Verifies if eAPI HTTPS server SSL profile is configured and valid.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the eAPI HTTPS server SSL profile is configured and valid.\n    * Failure: The test will fail if the eAPI HTTPS server SSL profile is NOT configured, misconfigured or invalid.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyAPIHttpsSSL:\n          profile: default\n    ```\n    \"\"\"\n\n    name = \"VerifyAPIHttpsSSL\"\n    description = \"Verifies if the eAPI has a valid SSL profile.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management api http-commands\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyAPIHttpsSSL test.\"\"\"\n\n        profile: str\n        \"\"\"SSL profile to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAPIHttpsSSL.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        try:\n            if command_output[\"sslProfile\"][\"name\"] == self.inputs.profile and command_output[\"sslProfile\"][\"state\"] == \"valid\":\n                self.result.is_success()\n            else:\n                self.result.is_failure(f\"eAPI HTTPS server SSL profile ({self.inputs.profile}) is misconfigured or invalid\")\n\n        except KeyError:\n            self.result.is_failure(f\"eAPI HTTPS server SSL profile ({self.inputs.profile}) is not configured\")\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyAPIHttpsSSL-attributes","title":"Inputs","text":"Name Type Description Default profile str SSL profile to verify. -"},{"location":"api/tests.security/#anta.tests.security.VerifyAPIIPv4Acl","title":"VerifyAPIIPv4Acl","text":"

Verifies if eAPI has the right number IPv4 ACL(s) configured for a specified VRF.

Expected Results
  • Success: The test will pass if eAPI has the provided number of IPv4 ACL(s) in the specified VRF.
  • Failure: The test will fail if eAPI has not the right number of IPv4 ACL(s) in the specified VRF.
Examples
anta.tests.security:\n  - VerifyAPIIPv4Acl:\n      number: 3\n      vrf: default\n
Source code in anta/tests/security.py
class VerifyAPIIPv4Acl(AntaTest):\n    \"\"\"Verifies if eAPI has the right number IPv4 ACL(s) configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if eAPI has the provided number of IPv4 ACL(s) in the specified VRF.\n    * Failure: The test will fail if eAPI has not the right number of IPv4 ACL(s) in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyAPIIPv4Acl:\n          number: 3\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyAPIIPv4Acl\"\n    description = \"Verifies if eAPI has the right number IPv4 ACL(s) configured for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management api http-commands ip access-list summary\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input parameters for the VerifyAPIIPv4Acl test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"The number of expected IPv4 ACL(s).\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for eAPI. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAPIIPv4Acl.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ipv4_acl_list = command_output[\"ipAclList\"][\"aclList\"]\n        ipv4_acl_number = len(ipv4_acl_list)\n        if ipv4_acl_number != self.inputs.number:\n            self.result.is_failure(f\"Expected {self.inputs.number} eAPI IPv4 ACL(s) in vrf {self.inputs.vrf} but got {ipv4_acl_number}\")\n            return\n\n        not_configured_acl = [acl[\"name\"] for acl in ipv4_acl_list if self.inputs.vrf not in acl[\"configuredVrfs\"] or self.inputs.vrf not in acl[\"activeVrfs\"]]\n\n        if not_configured_acl:\n            self.result.is_failure(f\"eAPI IPv4 ACL(s) not configured or active in vrf {self.inputs.vrf}: {not_configured_acl}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyAPIIPv4Acl-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger The number of expected IPv4 ACL(s). - vrf str The name of the VRF in which to check for eAPI. Defaults to `default` VRF. 'default'"},{"location":"api/tests.security/#anta.tests.security.VerifyAPIIPv6Acl","title":"VerifyAPIIPv6Acl","text":"

Verifies if eAPI has the right number IPv6 ACL(s) configured for a specified VRF.

Expected Results
  • Success: The test will pass if eAPI has the provided number of IPv6 ACL(s) in the specified VRF.
  • Failure: The test will fail if eAPI has not the right number of IPv6 ACL(s) in the specified VRF.
  • Skipped: The test will be skipped if the number of IPv6 ACL(s) or VRF parameter is not provided.
Examples
anta.tests.security:\n  - VerifyAPIIPv6Acl:\n      number: 3\n      vrf: default\n
Source code in anta/tests/security.py
class VerifyAPIIPv6Acl(AntaTest):\n    \"\"\"Verifies if eAPI has the right number IPv6 ACL(s) configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if eAPI has the provided number of IPv6 ACL(s) in the specified VRF.\n    * Failure: The test will fail if eAPI has not the right number of IPv6 ACL(s) in the specified VRF.\n    * Skipped: The test will be skipped if the number of IPv6 ACL(s) or VRF parameter is not provided.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyAPIIPv6Acl:\n          number: 3\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifyAPIIPv6Acl\"\n    description = \"Verifies if eAPI has the right number IPv6 ACL(s) configured for a specified VRF.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management api http-commands ipv6 access-list summary\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input parameters for the VerifyAPIIPv6Acl test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"The number of expected IPv6 ACL(s).\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for eAPI. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAPIIPv6Acl.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ipv6_acl_list = command_output[\"ipv6AclList\"][\"aclList\"]\n        ipv6_acl_number = len(ipv6_acl_list)\n        if ipv6_acl_number != self.inputs.number:\n            self.result.is_failure(f\"Expected {self.inputs.number} eAPI IPv6 ACL(s) in vrf {self.inputs.vrf} but got {ipv6_acl_number}\")\n            return\n\n        not_configured_acl = [acl[\"name\"] for acl in ipv6_acl_list if self.inputs.vrf not in acl[\"configuredVrfs\"] or self.inputs.vrf not in acl[\"activeVrfs\"]]\n\n        if not_configured_acl:\n            self.result.is_failure(f\"eAPI IPv6 ACL(s) not configured or active in vrf {self.inputs.vrf}: {not_configured_acl}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyAPIIPv6Acl-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger The number of expected IPv6 ACL(s). - vrf str The name of the VRF in which to check for eAPI. Defaults to `default` VRF. 'default'"},{"location":"api/tests.security/#anta.tests.security.VerifyAPISSLCertificate","title":"VerifyAPISSLCertificate","text":"

Verifies the eAPI SSL certificate expiry, common subject name, encryption algorithm and key size.

Expected Results
  • Success: The test will pass if the certificate\u2019s expiry date is greater than the threshold, and the certificate has the correct name, encryption algorithm, and key size.
  • Failure: The test will fail if the certificate is expired or is going to expire, or if the certificate has an incorrect name, encryption algorithm, or key size.
Examples
anta.tests.security:\n  - VerifyAPISSLCertificate:\n      certificates:\n        - certificate_name: ARISTA_SIGNING_CA.crt\n          expiry_threshold: 30\n          common_name: AristaIT-ICA ECDSA Issuing Cert Authority\n          encryption_algorithm: ECDSA\n          key_size: 256\n        - certificate_name: ARISTA_ROOT_CA.crt\n          expiry_threshold: 30\n          common_name: Arista Networks Internal IT Root Cert Authority\n          encryption_algorithm: RSA\n          key_size: 4096\n
Source code in anta/tests/security.py
class VerifyAPISSLCertificate(AntaTest):\n    \"\"\"Verifies the eAPI SSL certificate expiry, common subject name, encryption algorithm and key size.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the certificate's expiry date is greater than the threshold,\n                   and the certificate has the correct name, encryption algorithm, and key size.\n    * Failure: The test will fail if the certificate is expired or is going to expire,\n                   or if the certificate has an incorrect name, encryption algorithm, or key size.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyAPISSLCertificate:\n          certificates:\n            - certificate_name: ARISTA_SIGNING_CA.crt\n              expiry_threshold: 30\n              common_name: AristaIT-ICA ECDSA Issuing Cert Authority\n              encryption_algorithm: ECDSA\n              key_size: 256\n            - certificate_name: ARISTA_ROOT_CA.crt\n              expiry_threshold: 30\n              common_name: Arista Networks Internal IT Root Cert Authority\n              encryption_algorithm: RSA\n              key_size: 4096\n    ```\n    \"\"\"\n\n    name = \"VerifyAPISSLCertificate\"\n    description = \"Verifies the eAPI SSL certificate expiry, common subject name, encryption algorithm and key size.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"show management security ssl certificate\", revision=1),\n        AntaCommand(command=\"show clock\", revision=1),\n    ]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input parameters for the VerifyAPISSLCertificate test.\"\"\"\n\n        certificates: list[APISSLCertificate]\n        \"\"\"List of API SSL certificates.\"\"\"\n\n        class APISSLCertificate(BaseModel):\n            \"\"\"Model for an API SSL certificate.\"\"\"\n\n            certificate_name: str\n            \"\"\"The name of the certificate to be verified.\"\"\"\n            expiry_threshold: int\n            \"\"\"The expiry threshold of the certificate in days.\"\"\"\n            common_name: str\n            \"\"\"The common subject name of the certificate.\"\"\"\n            encryption_algorithm: EncryptionAlgorithm\n            \"\"\"The encryption algorithm of the certificate.\"\"\"\n            key_size: RsaKeySize | EcdsaKeySize\n            \"\"\"The encryption algorithm key size of the certificate.\"\"\"\n\n            @model_validator(mode=\"after\")\n            def validate_inputs(self: BaseModel) -> BaseModel:\n                \"\"\"Validate the key size provided to the APISSLCertificates class.\n\n                If encryption_algorithm is RSA then key_size should be in {2048, 3072, 4096}.\n\n                If encryption_algorithm is ECDSA then key_size should be in {256, 384, 521}.\n                \"\"\"\n                if self.encryption_algorithm == \"RSA\" and self.key_size not in RsaKeySize.__args__:\n                    msg = f\"`{self.certificate_name}` key size {self.key_size} is invalid for RSA encryption. Allowed sizes are {RsaKeySize.__args__}.\"\n                    raise ValueError(msg)\n\n                if self.encryption_algorithm == \"ECDSA\" and self.key_size not in EcdsaKeySize.__args__:\n                    msg = f\"`{self.certificate_name}` key size {self.key_size} is invalid for ECDSA encryption. Allowed sizes are {EcdsaKeySize.__args__}.\"\n                    raise ValueError(msg)\n\n                return self\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAPISSLCertificate.\"\"\"\n        # Mark the result as success by default\n        self.result.is_success()\n\n        # Extract certificate and clock output\n        certificate_output = self.instance_commands[0].json_output\n        clock_output = self.instance_commands[1].json_output\n        current_timestamp = clock_output[\"utcTime\"]\n\n        # Iterate over each API SSL certificate\n        for certificate in self.inputs.certificates:\n            # Collecting certificate expiry time and current EOS time.\n            # These times are used to calculate the number of days until the certificate expires.\n            if not (certificate_data := get_value(certificate_output, f\"certificates..{certificate.certificate_name}\", separator=\"..\")):\n                self.result.is_failure(f\"SSL certificate '{certificate.certificate_name}', is not configured.\\n\")\n                continue\n\n            expiry_time = certificate_data[\"notAfter\"]\n            day_difference = (datetime.fromtimestamp(expiry_time, tz=timezone.utc) - datetime.fromtimestamp(current_timestamp, tz=timezone.utc)).days\n\n            # Verify certificate expiry\n            if 0 < day_difference < certificate.expiry_threshold:\n                self.result.is_failure(f\"SSL certificate `{certificate.certificate_name}` is about to expire in {day_difference} days.\\n\")\n            elif day_difference < 0:\n                self.result.is_failure(f\"SSL certificate `{certificate.certificate_name}` is expired.\\n\")\n\n            # Verify certificate common subject name, encryption algorithm and key size\n            keys_to_verify = [\"subject.commonName\", \"publicKey.encryptionAlgorithm\", \"publicKey.size\"]\n            actual_certificate_details = {key: get_value(certificate_data, key) for key in keys_to_verify}\n\n            expected_certificate_details = {\n                \"subject.commonName\": certificate.common_name,\n                \"publicKey.encryptionAlgorithm\": certificate.encryption_algorithm,\n                \"publicKey.size\": certificate.key_size,\n            }\n\n            if actual_certificate_details != expected_certificate_details:\n                failed_log = f\"SSL certificate `{certificate.certificate_name}` is not configured properly:\"\n                failed_log += get_failed_logs(expected_certificate_details, actual_certificate_details)\n                self.result.is_failure(f\"{failed_log}\\n\")\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyAPISSLCertificate-attributes","title":"Inputs","text":"Name Type Description Default certificates list[APISSLCertificate] List of API SSL certificates. -"},{"location":"api/tests.security/#anta.tests.security.VerifyAPISSLCertificate-attributes","title":"APISSLCertificate","text":"Name Type Description Default certificate_name str The name of the certificate to be verified. - expiry_threshold int The expiry threshold of the certificate in days. - common_name str The common subject name of the certificate. - encryption_algorithm EncryptionAlgorithm The encryption algorithm of the certificate. - key_size RsaKeySize | EcdsaKeySize The encryption algorithm key size of the certificate. -"},{"location":"api/tests.security/#anta.tests.security.VerifyBannerLogin","title":"VerifyBannerLogin","text":"

Verifies the login banner of a device.

Expected Results
  • Success: The test will pass if the login banner matches the provided input.
  • Failure: The test will fail if the login banner does not match the provided input.
Examples
anta.tests.security:\n  - VerifyBannerLogin:\n        login_banner: |\n            # Copyright (c) 2023-2024 Arista Networks, Inc.\n            # Use of this source code is governed by the Apache License 2.0\n            # that can be found in the LICENSE file.\n
Source code in anta/tests/security.py
class VerifyBannerLogin(AntaTest):\n    \"\"\"Verifies the login banner of a device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the login banner matches the provided input.\n    * Failure: The test will fail if the login banner does not match the provided input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyBannerLogin:\n            login_banner: |\n                # Copyright (c) 2023-2024 Arista Networks, Inc.\n                # Use of this source code is governed by the Apache License 2.0\n                # that can be found in the LICENSE file.\n    ```\n    \"\"\"\n\n    name = \"VerifyBannerLogin\"\n    description = \"Verifies the login banner of a device.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show banner login\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBannerLogin test.\"\"\"\n\n        login_banner: str\n        \"\"\"Expected login banner of the device.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBannerLogin.\"\"\"\n        login_banner = self.instance_commands[0].json_output[\"loginBanner\"]\n\n        # Remove leading and trailing whitespaces from each line\n        cleaned_banner = \"\\n\".join(line.strip() for line in self.inputs.login_banner.split(\"\\n\"))\n        if login_banner != cleaned_banner:\n            self.result.is_failure(f\"Expected `{cleaned_banner}` as the login banner, but found `{login_banner}` instead.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyBannerLogin-attributes","title":"Inputs","text":"Name Type Description Default login_banner str Expected login banner of the device. -"},{"location":"api/tests.security/#anta.tests.security.VerifyBannerMotd","title":"VerifyBannerMotd","text":"

Verifies the motd banner of a device.

Expected Results
  • Success: The test will pass if the motd banner matches the provided input.
  • Failure: The test will fail if the motd banner does not match the provided input.
Examples
anta.tests.security:\n  - VerifyBannerMotd:\n        motd_banner: |\n            # Copyright (c) 2023-2024 Arista Networks, Inc.\n            # Use of this source code is governed by the Apache License 2.0\n            # that can be found in the LICENSE file.\n
Source code in anta/tests/security.py
class VerifyBannerMotd(AntaTest):\n    \"\"\"Verifies the motd banner of a device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the motd banner matches the provided input.\n    * Failure: The test will fail if the motd banner does not match the provided input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyBannerMotd:\n            motd_banner: |\n                # Copyright (c) 2023-2024 Arista Networks, Inc.\n                # Use of this source code is governed by the Apache License 2.0\n                # that can be found in the LICENSE file.\n    ```\n    \"\"\"\n\n    name = \"VerifyBannerMotd\"\n    description = \"Verifies the motd banner of a device.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show banner motd\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyBannerMotd test.\"\"\"\n\n        motd_banner: str\n        \"\"\"Expected motd banner of the device.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyBannerMotd.\"\"\"\n        motd_banner = self.instance_commands[0].json_output[\"motd\"]\n\n        # Remove leading and trailing whitespaces from each line\n        cleaned_banner = \"\\n\".join(line.strip() for line in self.inputs.motd_banner.split(\"\\n\"))\n        if motd_banner != cleaned_banner:\n            self.result.is_failure(f\"Expected `{cleaned_banner}` as the motd banner, but found `{motd_banner}` instead.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyBannerMotd-attributes","title":"Inputs","text":"Name Type Description Default motd_banner str Expected motd banner of the device. -"},{"location":"api/tests.security/#anta.tests.security.VerifyIPSecConnHealth","title":"VerifyIPSecConnHealth","text":"

Verifies all IPv4 security connections.

Expected Results
  • Success: The test will pass if all the IPv4 security connections are established in all vrf.
  • Failure: The test will fail if IPv4 security is not configured or any of IPv4 security connections are not established in any vrf.
Examples
anta.tests.security:\n  - VerifyIPSecConnHealth:\n
Source code in anta/tests/security.py
class VerifyIPSecConnHealth(AntaTest):\n    \"\"\"\n    Verifies all IPv4 security connections.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all the IPv4 security connections are established in all vrf.\n    * Failure: The test will fail if IPv4 security is not configured or any of IPv4 security connections are not established in any vrf.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyIPSecConnHealth:\n    ```\n    \"\"\"\n\n    name = \"VerifyIPSecConnHealth\"\n    description = \"Verifies all IPv4 security connections.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip security connection vrf all\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIPSecConnHealth.\"\"\"\n        self.result.is_success()\n        failure_conn = []\n        command_output = self.instance_commands[0].json_output[\"connections\"]\n\n        # Check if IP security connection is configured\n        if not command_output:\n            self.result.is_failure(\"No IPv4 security connection configured.\")\n            return\n\n        # Iterate over all ipsec connections\n        for conn_data in command_output.values():\n            state = next(iter(conn_data[\"pathDict\"].values()))\n            if state != \"Established\":\n                source = conn_data.get(\"saddr\")\n                destination = conn_data.get(\"daddr\")\n                vrf = conn_data.get(\"tunnelNs\")\n                failure_conn.append(f\"source:{source} destination:{destination} vrf:{vrf}\")\n        if failure_conn:\n            failure_msg = \"\\n\".join(failure_conn)\n            self.result.is_failure(f\"The following IPv4 security connections are not established:\\n{failure_msg}.\")\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyIPv4ACL","title":"VerifyIPv4ACL","text":"

Verifies the configuration of IPv4 ACLs.

Expected Results
  • Success: The test will pass if an IPv4 ACL is configured with the correct sequence entries.
  • Failure: The test will fail if an IPv4 ACL is not configured or entries are not in sequence.
Examples
anta.tests.security:\n  - VerifyIPv4ACL:\n      ipv4_access_lists:\n        - name: default-control-plane-acl\n          entries:\n            - sequence: 10\n              action: permit icmp any any\n            - sequence: 20\n              action: permit ip any any tracked\n            - sequence: 30\n              action: permit udp any any eq bfd ttl eq 255\n        - name: LabTest\n          entries:\n            - sequence: 10\n              action: permit icmp any any\n            - sequence: 20\n              action: permit tcp any any range 5900 5910\n
Source code in anta/tests/security.py
class VerifyIPv4ACL(AntaTest):\n    \"\"\"Verifies the configuration of IPv4 ACLs.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if an IPv4 ACL is configured with the correct sequence entries.\n    * Failure: The test will fail if an IPv4 ACL is not configured or entries are not in sequence.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyIPv4ACL:\n          ipv4_access_lists:\n            - name: default-control-plane-acl\n              entries:\n                - sequence: 10\n                  action: permit icmp any any\n                - sequence: 20\n                  action: permit ip any any tracked\n                - sequence: 30\n                  action: permit udp any any eq bfd ttl eq 255\n            - name: LabTest\n              entries:\n                - sequence: 10\n                  action: permit icmp any any\n                - sequence: 20\n                  action: permit tcp any any range 5900 5910\n    ```\n    \"\"\"\n\n    name = \"VerifyIPv4ACL\"\n    description = \"Verifies the configuration of IPv4 ACLs.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show ip access-lists {acl}\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyIPv4ACL test.\"\"\"\n\n        ipv4_access_lists: list[IPv4ACL]\n        \"\"\"List of IPv4 ACLs to verify.\"\"\"\n\n        class IPv4ACL(BaseModel):\n            \"\"\"Model for an IPv4 ACL.\"\"\"\n\n            name: str\n            \"\"\"Name of IPv4 ACL.\"\"\"\n\n            entries: list[IPv4ACLEntry]\n            \"\"\"List of IPv4 ACL entries.\"\"\"\n\n            class IPv4ACLEntry(BaseModel):\n                \"\"\"Model for an IPv4 ACL entry.\"\"\"\n\n                sequence: int = Field(ge=1, le=4294967295)\n                \"\"\"Sequence number of an ACL entry.\"\"\"\n                action: str\n                \"\"\"Action of an ACL entry.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each input ACL.\"\"\"\n        return [template.render(acl=acl.name) for acl in self.inputs.ipv4_access_lists]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyIPv4ACL.\"\"\"\n        self.result.is_success()\n        for command_output, acl in zip(self.instance_commands, self.inputs.ipv4_access_lists):\n            # Collecting input ACL details\n            acl_name = command_output.params.acl\n            # Retrieve the expected entries from the inputs\n            acl_entries = acl.entries\n\n            # Check if ACL is configured\n            ipv4_acl_list = command_output.json_output[\"aclList\"]\n            if not ipv4_acl_list:\n                self.result.is_failure(f\"{acl_name}: Not found\")\n                continue\n\n            # Check if the sequence number is configured and has the correct action applied\n            failed_log = f\"{acl_name}:\\n\"\n            for acl_entry in acl_entries:\n                acl_seq = acl_entry.sequence\n                acl_action = acl_entry.action\n                if (actual_entry := get_item(ipv4_acl_list[0][\"sequence\"], \"sequenceNumber\", acl_seq)) is None:\n                    failed_log += f\"Sequence number `{acl_seq}` is not found.\\n\"\n                    continue\n\n                if actual_entry[\"text\"] != acl_action:\n                    failed_log += f\"Expected `{acl_action}` as sequence number {acl_seq} action but found `{actual_entry['text']}` instead.\\n\"\n\n            if failed_log != f\"{acl_name}:\\n\":\n                self.result.is_failure(f\"{failed_log}\")\n
"},{"location":"api/tests.security/#anta.tests.security.VerifyIPv4ACL-attributes","title":"Inputs","text":"Name Type Description Default ipv4_access_lists list[IPv4ACL] List of IPv4 ACLs to verify. -"},{"location":"api/tests.security/#anta.tests.security.VerifyIPv4ACL-attributes","title":"IPv4ACL","text":"Name Type Description Default name str Name of IPv4 ACL. - entries list[IPv4ACLEntry] List of IPv4 ACL entries. -"},{"location":"api/tests.security/#anta.tests.security.VerifyIPv4ACL-attributes","title":"IPv4ACLEntry","text":"Name Type Description Default sequence int Sequence number of an ACL entry. Field(ge=1, le=4294967295) action str Action of an ACL entry. -"},{"location":"api/tests.security/#anta.tests.security.VerifySSHIPv4Acl","title":"VerifySSHIPv4Acl","text":"

Verifies if the SSHD agent has the right number IPv4 ACL(s) configured for a specified VRF.

Expected Results
  • Success: The test will pass if the SSHD agent has the provided number of IPv4 ACL(s) in the specified VRF.
  • Failure: The test will fail if the SSHD agent has not the right number of IPv4 ACL(s) in the specified VRF.
Examples
anta.tests.security:\n  - VerifySSHIPv4Acl:\n      number: 3\n      vrf: default\n
Source code in anta/tests/security.py
class VerifySSHIPv4Acl(AntaTest):\n    \"\"\"Verifies if the SSHD agent has the right number IPv4 ACL(s) configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SSHD agent has the provided number of IPv4 ACL(s) in the specified VRF.\n    * Failure: The test will fail if the SSHD agent has not the right number of IPv4 ACL(s) in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifySSHIPv4Acl:\n          number: 3\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifySSHIPv4Acl\"\n    description = \"Verifies if the SSHD agent has IPv4 ACL(s) configured.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management ssh ip access-list summary\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySSHIPv4Acl test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"The number of expected IPv4 ACL(s).\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for the SSHD agent. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySSHIPv4Acl.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ipv4_acl_list = command_output[\"ipAclList\"][\"aclList\"]\n        ipv4_acl_number = len(ipv4_acl_list)\n        if ipv4_acl_number != self.inputs.number:\n            self.result.is_failure(f\"Expected {self.inputs.number} SSH IPv4 ACL(s) in vrf {self.inputs.vrf} but got {ipv4_acl_number}\")\n            return\n\n        not_configured_acl = [acl[\"name\"] for acl in ipv4_acl_list if self.inputs.vrf not in acl[\"configuredVrfs\"] or self.inputs.vrf not in acl[\"activeVrfs\"]]\n\n        if not_configured_acl:\n            self.result.is_failure(f\"SSH IPv4 ACL(s) not configured or active in vrf {self.inputs.vrf}: {not_configured_acl}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.security/#anta.tests.security.VerifySSHIPv4Acl-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger The number of expected IPv4 ACL(s). - vrf str The name of the VRF in which to check for the SSHD agent. Defaults to `default` VRF. 'default'"},{"location":"api/tests.security/#anta.tests.security.VerifySSHIPv6Acl","title":"VerifySSHIPv6Acl","text":"

Verifies if the SSHD agent has the right number IPv6 ACL(s) configured for a specified VRF.

Expected Results
  • Success: The test will pass if the SSHD agent has the provided number of IPv6 ACL(s) in the specified VRF.
  • Failure: The test will fail if the SSHD agent has not the right number of IPv6 ACL(s) in the specified VRF.
Examples
anta.tests.security:\n  - VerifySSHIPv6Acl:\n      number: 3\n      vrf: default\n
Source code in anta/tests/security.py
class VerifySSHIPv6Acl(AntaTest):\n    \"\"\"Verifies if the SSHD agent has the right number IPv6 ACL(s) configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SSHD agent has the provided number of IPv6 ACL(s) in the specified VRF.\n    * Failure: The test will fail if the SSHD agent has not the right number of IPv6 ACL(s) in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifySSHIPv6Acl:\n          number: 3\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifySSHIPv6Acl\"\n    description = \"Verifies if the SSHD agent has IPv6 ACL(s) configured.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management ssh ipv6 access-list summary\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySSHIPv6Acl test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"The number of expected IPv6 ACL(s).\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for the SSHD agent. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySSHIPv6Acl.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ipv6_acl_list = command_output[\"ipv6AclList\"][\"aclList\"]\n        ipv6_acl_number = len(ipv6_acl_list)\n        if ipv6_acl_number != self.inputs.number:\n            self.result.is_failure(f\"Expected {self.inputs.number} SSH IPv6 ACL(s) in vrf {self.inputs.vrf} but got {ipv6_acl_number}\")\n            return\n\n        not_configured_acl = [acl[\"name\"] for acl in ipv6_acl_list if self.inputs.vrf not in acl[\"configuredVrfs\"] or self.inputs.vrf not in acl[\"activeVrfs\"]]\n\n        if not_configured_acl:\n            self.result.is_failure(f\"SSH IPv6 ACL(s) not configured or active in vrf {self.inputs.vrf}: {not_configured_acl}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.security/#anta.tests.security.VerifySSHIPv6Acl-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger The number of expected IPv6 ACL(s). - vrf str The name of the VRF in which to check for the SSHD agent. Defaults to `default` VRF. 'default'"},{"location":"api/tests.security/#anta.tests.security.VerifySSHStatus","title":"VerifySSHStatus","text":"

Verifies if the SSHD agent is disabled in the default VRF.

Expected Results
  • Success: The test will pass if the SSHD agent is disabled in the default VRF.
  • Failure: The test will fail if the SSHD agent is NOT disabled in the default VRF.
Examples
anta.tests.security:\n  - VerifySSHStatus:\n
Source code in anta/tests/security.py
class VerifySSHStatus(AntaTest):\n    \"\"\"Verifies if the SSHD agent is disabled in the default VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SSHD agent is disabled in the default VRF.\n    * Failure: The test will fail if the SSHD agent is NOT disabled in the default VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifySSHStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifySSHStatus\"\n    description = \"Verifies if the SSHD agent is disabled in the default VRF.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management ssh\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySSHStatus.\"\"\"\n        command_output = self.instance_commands[0].text_output\n\n        try:\n            line = next(line for line in command_output.split(\"\\n\") if line.startswith(\"SSHD status\"))\n        except StopIteration:\n            self.result.is_error(\"Could not find SSH status in returned output.\")\n            return\n        status = line.split(\"is \")[1]\n\n        if status == \"disabled\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(line)\n
"},{"location":"api/tests.security/#anta.tests.security.VerifySpecificIPSecConn","title":"VerifySpecificIPSecConn","text":"

Verifies the state of IPv4 security connections for a specified peer.

It optionally allows for the verification of a specific path for a peer by providing source and destination addresses. If these addresses are not provided, it will verify all paths for the specified peer.

Expected Results
  • Success: The test passes if the IPv4 security connection for a peer is established in the specified VRF.
  • Failure: The test fails if IPv4 security is not configured, a connection is not found for a peer, or the connection is not established in the specified VRF.
Examples
anta.tests.security:\n  - VerifySpecificIPSecConn:\n      ip_security_connections:\n        - peer: 10.255.0.1\n        - peer: 10.255.0.2\n          vrf: default\n          connections:\n            - source_address: 100.64.3.2\n              destination_address: 100.64.2.2\n            - source_address: 172.18.3.2\n              destination_address: 172.18.2.2\n
Source code in anta/tests/security.py
class VerifySpecificIPSecConn(AntaTest):\n    \"\"\"\n    Verifies the state of IPv4 security connections for a specified peer.\n\n    It optionally allows for the verification of a specific path for a peer by providing source and destination addresses.\n    If these addresses are not provided, it will verify all paths for the specified peer.\n\n    Expected Results\n    ----------------\n    * Success: The test passes if the IPv4 security connection for a peer is established in the specified VRF.\n    * Failure: The test fails if IPv4 security is not configured, a connection is not found for a peer, or the connection is not established in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifySpecificIPSecConn:\n          ip_security_connections:\n            - peer: 10.255.0.1\n            - peer: 10.255.0.2\n              vrf: default\n              connections:\n                - source_address: 100.64.3.2\n                  destination_address: 100.64.2.2\n                - source_address: 172.18.3.2\n                  destination_address: 172.18.2.2\n    ```\n    \"\"\"\n\n    name = \"VerifySpecificIPSecConn\"\n    description = \"Verifies IPv4 security connections for a peer.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show ip security connection vrf {vrf} path peer {peer}\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySpecificIPSecConn test.\"\"\"\n\n        ip_security_connections: list[IPSecPeers]\n        \"\"\"List of IP4v security peers.\"\"\"\n\n        class IPSecPeers(BaseModel):\n            \"\"\"Details of IPv4 security peers.\"\"\"\n\n            peer: IPv4Address\n            \"\"\"IPv4 address of the peer.\"\"\"\n\n            vrf: str = \"default\"\n            \"\"\"Optional VRF for the IP security peer.\"\"\"\n\n            connections: list[IPSecConn] | None = None\n            \"\"\"Optional list of IPv4 security connections of a peer.\"\"\"\n\n            class IPSecConn(BaseModel):\n                \"\"\"Details of IPv4 security connections for a peer.\"\"\"\n\n                source_address: IPv4Address\n                \"\"\"Source IPv4 address of the connection.\"\"\"\n                destination_address: IPv4Address\n                \"\"\"Destination IPv4 address of the connection.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each input IP Sec connection.\"\"\"\n        return [template.render(peer=conn.peer, vrf=conn.vrf) for conn in self.inputs.ip_security_connections]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySpecificIPSecConn.\"\"\"\n        self.result.is_success()\n        for command_output, input_peer in zip(self.instance_commands, self.inputs.ip_security_connections):\n            conn_output = command_output.json_output[\"connections\"]\n            peer = command_output.params.peer\n            vrf = command_output.params.vrf\n            conn_input = input_peer.connections\n\n            # Check if IPv4 security connection is configured\n            if not conn_output:\n                self.result.is_failure(f\"No IPv4 security connection configured for peer `{peer}`.\")\n                continue\n\n            # If connection details are not provided then check all connections of a peer\n            if conn_input is None:\n                for conn_data in conn_output.values():\n                    state = next(iter(conn_data[\"pathDict\"].values()))\n                    if state != \"Established\":\n                        source = conn_data.get(\"saddr\")\n                        destination = conn_data.get(\"daddr\")\n                        vrf = conn_data.get(\"tunnelNs\")\n                        self.result.is_failure(\n                            f\"Expected state of IPv4 security connection `source:{source} destination:{destination} vrf:{vrf}` for peer `{peer}` is `Established` \"\n                            f\"but found `{state}` instead.\"\n                        )\n                continue\n\n            # Create a dictionary of existing connections for faster lookup\n            existing_connections = {\n                (conn_data.get(\"saddr\"), conn_data.get(\"daddr\"), conn_data.get(\"tunnelNs\")): next(iter(conn_data[\"pathDict\"].values()))\n                for conn_data in conn_output.values()\n            }\n            for connection in conn_input:\n                source_input = str(connection.source_address)\n                destination_input = str(connection.destination_address)\n\n                if (source_input, destination_input, vrf) in existing_connections:\n                    existing_state = existing_connections[(source_input, destination_input, vrf)]\n                    if existing_state != \"Established\":\n                        self.result.is_failure(\n                            f\"Expected state of IPv4 security connection `source:{source_input} destination:{destination_input} vrf:{vrf}` \"\n                            f\"for peer `{peer}` is `Established` but found `{existing_state}` instead.\"\n                        )\n                else:\n                    self.result.is_failure(\n                        f\"IPv4 security connection `source:{source_input} destination:{destination_input} vrf:{vrf}` for peer `{peer}` is not found.\"\n                    )\n
"},{"location":"api/tests.security/#anta.tests.security.VerifySpecificIPSecConn-attributes","title":"Inputs","text":"Name Type Description Default ip_security_connections list[IPSecPeers] List of IP4v security peers. -"},{"location":"api/tests.security/#anta.tests.security.VerifySpecificIPSecConn-attributes","title":"IPSecPeers","text":"Name Type Description Default peer IPv4Address IPv4 address of the peer. - vrf str Optional VRF for the IP security peer. 'default' connections list[IPSecConn] | None Optional list of IPv4 security connections of a peer. None"},{"location":"api/tests.security/#anta.tests.security.VerifySpecificIPSecConn-attributes","title":"IPSecConn","text":"Name Type Description Default source_address IPv4Address Source IPv4 address of the connection. - destination_address IPv4Address Destination IPv4 address of the connection. -"},{"location":"api/tests.security/#anta.tests.security.VerifyTelnetStatus","title":"VerifyTelnetStatus","text":"

Verifies if Telnet is disabled in the default VRF.

Expected Results
  • Success: The test will pass if Telnet is disabled in the default VRF.
  • Failure: The test will fail if Telnet is NOT disabled in the default VRF.
Examples
anta.tests.security:\n  - VerifyTelnetStatus:\n
Source code in anta/tests/security.py
class VerifyTelnetStatus(AntaTest):\n    \"\"\"Verifies if Telnet is disabled in the default VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if Telnet is disabled in the default VRF.\n    * Failure: The test will fail if Telnet is NOT disabled in the default VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.security:\n      - VerifyTelnetStatus:\n    ```\n    \"\"\"\n\n    name = \"VerifyTelnetStatus\"\n    description = \"Verifies if Telnet is disabled in the default VRF.\"\n    categories: ClassVar[list[str]] = [\"security\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show management telnet\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTelnetStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"serverState\"] == \"disabled\":\n            self.result.is_success()\n        else:\n            self.result.is_failure(\"Telnet status for Default VRF is enabled\")\n
"},{"location":"api/tests.services/","title":"Services","text":""},{"location":"api/tests.services/#anta.tests.services.VerifyDNSLookup","title":"VerifyDNSLookup","text":"

Verifies the DNS (Domain Name Service) name to IP address resolution.

Expected Results
  • Success: The test will pass if a domain name is resolved to an IP address.
  • Failure: The test will fail if a domain name does not resolve to an IP address.
  • Error: This test will error out if a domain name is invalid.
Examples
anta.tests.services:\n  - VerifyDNSLookup:\n      domain_names:\n        - arista.com\n        - www.google.com\n        - arista.ca\n
Source code in anta/tests/services.py
class VerifyDNSLookup(AntaTest):\n    \"\"\"Verifies the DNS (Domain Name Service) name to IP address resolution.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if a domain name is resolved to an IP address.\n    * Failure: The test will fail if a domain name does not resolve to an IP address.\n    * Error: This test will error out if a domain name is invalid.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.services:\n      - VerifyDNSLookup:\n          domain_names:\n            - arista.com\n            - www.google.com\n            - arista.ca\n    ```\n    \"\"\"\n\n    name = \"VerifyDNSLookup\"\n    description = \"Verifies the DNS name to IP address resolution.\"\n    categories: ClassVar[list[str]] = [\"services\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"bash timeout 10 nslookup {domain}\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyDNSLookup test.\"\"\"\n\n        domain_names: list[str]\n        \"\"\"List of domain names.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each domain name in the input list.\"\"\"\n        return [template.render(domain=domain_name) for domain_name in self.inputs.domain_names]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyDNSLookup.\"\"\"\n        self.result.is_success()\n        failed_domains = []\n        for command in self.instance_commands:\n            domain = command.params.domain\n            output = command.json_output[\"messages\"][0]\n            if f\"Can't find {domain}: No answer\" in output:\n                failed_domains.append(domain)\n        if failed_domains:\n            self.result.is_failure(f\"The following domain(s) are not resolved to an IP address: {', '.join(failed_domains)}\")\n
"},{"location":"api/tests.services/#anta.tests.services.VerifyDNSLookup-attributes","title":"Inputs","text":"Name Type Description Default domain_names list[str] List of domain names. -"},{"location":"api/tests.services/#anta.tests.services.VerifyDNSServers","title":"VerifyDNSServers","text":"

Verifies if the DNS (Domain Name Service) servers are correctly configured.

Expected Results
  • Success: The test will pass if the DNS server specified in the input is configured with the correct VRF and priority.
  • Failure: The test will fail if the DNS server is not configured or if the VRF and priority of the DNS server do not match the input.
Examples
anta.tests.services:\n  - VerifyDNSServers:\n      dns_servers:\n        - server_address: 10.14.0.1\n          vrf: default\n          priority: 1\n        - server_address: 10.14.0.11\n          vrf: MGMT\n          priority: 0\n
Source code in anta/tests/services.py
class VerifyDNSServers(AntaTest):\n    \"\"\"Verifies if the DNS (Domain Name Service) servers are correctly configured.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the DNS server specified in the input is configured with the correct VRF and priority.\n    * Failure: The test will fail if the DNS server is not configured or if the VRF and priority of the DNS server do not match the input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.services:\n      - VerifyDNSServers:\n          dns_servers:\n            - server_address: 10.14.0.1\n              vrf: default\n              priority: 1\n            - server_address: 10.14.0.11\n              vrf: MGMT\n              priority: 0\n    ```\n    \"\"\"\n\n    name = \"VerifyDNSServers\"\n    description = \"Verifies if the DNS servers are correctly configured.\"\n    categories: ClassVar[list[str]] = [\"services\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ip name-server\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyDNSServers test.\"\"\"\n\n        dns_servers: list[DnsServer]\n        \"\"\"List of DNS servers to verify.\"\"\"\n\n        class DnsServer(BaseModel):\n            \"\"\"Model for a DNS server.\"\"\"\n\n            server_address: IPv4Address | IPv6Address\n            \"\"\"The IPv4/IPv6 address of the DNS server.\"\"\"\n            vrf: str = \"default\"\n            \"\"\"The VRF for the DNS server. Defaults to 'default' if not provided.\"\"\"\n            priority: int = Field(ge=0, le=4)\n            \"\"\"The priority of the DNS server from 0 to 4, lower is first.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyDNSServers.\"\"\"\n        command_output = self.instance_commands[0].json_output[\"nameServerConfigs\"]\n        self.result.is_success()\n        for server in self.inputs.dns_servers:\n            address = str(server.server_address)\n            vrf = server.vrf\n            priority = server.priority\n            input_dict = {\"ipAddr\": address, \"vrf\": vrf}\n\n            if get_item(command_output, \"ipAddr\", address) is None:\n                self.result.is_failure(f\"DNS server `{address}` is not configured with any VRF.\")\n                continue\n\n            if (output := get_dict_superset(command_output, input_dict)) is None:\n                self.result.is_failure(f\"DNS server `{address}` is not configured with VRF `{vrf}`.\")\n                continue\n\n            if output[\"priority\"] != priority:\n                self.result.is_failure(f\"For DNS server `{address}`, the expected priority is `{priority}`, but `{output['priority']}` was found instead.\")\n
"},{"location":"api/tests.services/#anta.tests.services.VerifyDNSServers-attributes","title":"Inputs","text":"Name Type Description Default dns_servers list[DnsServer] List of DNS servers to verify. -"},{"location":"api/tests.services/#anta.tests.services.VerifyDNSServers-attributes","title":"DnsServer","text":"Name Type Description Default server_address IPv4Address | IPv6Address The IPv4/IPv6 address of the DNS server. - vrf str The VRF for the DNS server. Defaults to 'default' if not provided. 'default' priority int The priority of the DNS server from 0 to 4, lower is first. Field(ge=0, le=4)"},{"location":"api/tests.services/#anta.tests.services.VerifyErrdisableRecovery","title":"VerifyErrdisableRecovery","text":"

Verifies the errdisable recovery reason, status, and interval.

Expected Results
  • Success: The test will pass if the errdisable recovery reason status is enabled and the interval matches the input.
  • Failure: The test will fail if the errdisable recovery reason is not found, the status is not enabled, or the interval does not match the input.
Examples
anta.tests.services:\n  - VerifyErrdisableRecovery:\n      reasons:\n        - reason: acl\n          interval: 30\n        - reason: bpduguard\n          interval: 30\n
Source code in anta/tests/services.py
class VerifyErrdisableRecovery(AntaTest):\n    \"\"\"Verifies the errdisable recovery reason, status, and interval.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the errdisable recovery reason status is enabled and the interval matches the input.\n    * Failure: The test will fail if the errdisable recovery reason is not found, the status is not enabled, or the interval does not match the input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.services:\n      - VerifyErrdisableRecovery:\n          reasons:\n            - reason: acl\n              interval: 30\n            - reason: bpduguard\n              interval: 30\n    ```\n    \"\"\"\n\n    name = \"VerifyErrdisableRecovery\"\n    description = \"Verifies the errdisable recovery reason, status, and interval.\"\n    categories: ClassVar[list[str]] = [\"services\"]\n    # NOTE: Only `text` output format is supported for this command\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show errdisable recovery\", ofmt=\"text\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyErrdisableRecovery test.\"\"\"\n\n        reasons: list[ErrDisableReason]\n        \"\"\"List of errdisable reasons.\"\"\"\n\n        class ErrDisableReason(BaseModel):\n            \"\"\"Model for an errdisable reason.\"\"\"\n\n            reason: ErrDisableReasons\n            \"\"\"Type or name of the errdisable reason.\"\"\"\n            interval: ErrDisableInterval\n            \"\"\"Interval of the reason in seconds.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyErrdisableRecovery.\"\"\"\n        command_output = self.instance_commands[0].text_output\n        self.result.is_success()\n        for error_reason in self.inputs.reasons:\n            input_reason = error_reason.reason\n            input_interval = error_reason.interval\n            reason_found = False\n\n            # Skip header and last empty line\n            lines = command_output.split(\"\\n\")[2:-1]\n            for line in lines:\n                # Skip empty lines\n                if not line.strip():\n                    continue\n                # Split by first two whitespaces\n                reason, status, interval = line.split(None, 2)\n                if reason != input_reason:\n                    continue\n                reason_found = True\n                actual_reason_data = {\"interval\": interval, \"status\": status}\n                expected_reason_data = {\"interval\": str(input_interval), \"status\": \"Enabled\"}\n                if actual_reason_data != expected_reason_data:\n                    failed_log = get_failed_logs(expected_reason_data, actual_reason_data)\n                    self.result.is_failure(f\"`{input_reason}`:{failed_log}\\n\")\n                break\n\n            if not reason_found:\n                self.result.is_failure(f\"`{input_reason}`: Not found.\\n\")\n
"},{"location":"api/tests.services/#anta.tests.services.VerifyErrdisableRecovery-attributes","title":"Inputs","text":"Name Type Description Default reasons list[ErrDisableReason] List of errdisable reasons. -"},{"location":"api/tests.services/#anta.tests.services.VerifyErrdisableRecovery-attributes","title":"ErrDisableReason","text":"Name Type Description Default reason ErrDisableReasons Type or name of the errdisable reason. - interval ErrDisableInterval Interval of the reason in seconds. -"},{"location":"api/tests.services/#anta.tests.services.VerifyHostname","title":"VerifyHostname","text":"

Verifies the hostname of a device.

Expected Results
  • Success: The test will pass if the hostname matches the provided input.
  • Failure: The test will fail if the hostname does not match the provided input.
Examples
anta.tests.services:\n  - VerifyHostname:\n      hostname: s1-spine1\n
Source code in anta/tests/services.py
class VerifyHostname(AntaTest):\n    \"\"\"Verifies the hostname of a device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the hostname matches the provided input.\n    * Failure: The test will fail if the hostname does not match the provided input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.services:\n      - VerifyHostname:\n          hostname: s1-spine1\n    ```\n    \"\"\"\n\n    name = \"VerifyHostname\"\n    description = \"Verifies the hostname of a device.\"\n    categories: ClassVar[list[str]] = [\"services\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show hostname\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyHostname test.\"\"\"\n\n        hostname: str\n        \"\"\"Expected hostname of the device.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyHostname.\"\"\"\n        hostname = self.instance_commands[0].json_output[\"hostname\"]\n\n        if hostname != self.inputs.hostname:\n            self.result.is_failure(f\"Expected `{self.inputs.hostname}` as the hostname, but found `{hostname}` instead.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.services/#anta.tests.services.VerifyHostname-attributes","title":"Inputs","text":"Name Type Description Default hostname str Expected hostname of the device. -"},{"location":"api/tests.snmp/","title":"SNMP","text":""},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpContact","title":"VerifySnmpContact","text":"

Verifies the SNMP contact of a device.

Expected Results
  • Success: The test will pass if the SNMP contact matches the provided input.
  • Failure: The test will fail if the SNMP contact does not match the provided input.
Examples
anta.tests.snmp:\n  - VerifySnmpContact:\n      contact: Jon@example.com\n
Source code in anta/tests/snmp.py
class VerifySnmpContact(AntaTest):\n    \"\"\"Verifies the SNMP contact of a device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SNMP contact matches the provided input.\n    * Failure: The test will fail if the SNMP contact does not match the provided input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.snmp:\n      - VerifySnmpContact:\n          contact: Jon@example.com\n    ```\n    \"\"\"\n\n    name = \"VerifySnmpContact\"\n    description = \"Verifies the SNMP contact of a device.\"\n    categories: ClassVar[list[str]] = [\"snmp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show snmp\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySnmpContact test.\"\"\"\n\n        contact: str\n        \"\"\"Expected SNMP contact details of the device.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySnmpContact.\"\"\"\n        contact = self.instance_commands[0].json_output[\"contact\"][\"contact\"]\n\n        if contact != self.inputs.contact:\n            self.result.is_failure(f\"Expected `{self.inputs.contact}` as the contact, but found `{contact}` instead.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpContact-attributes","title":"Inputs","text":"Name Type Description Default contact str Expected SNMP contact details of the device. -"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpIPv4Acl","title":"VerifySnmpIPv4Acl","text":"

Verifies if the SNMP agent has the right number IPv4 ACL(s) configured for a specified VRF.

Expected Results
  • Success: The test will pass if the SNMP agent has the provided number of IPv4 ACL(s) in the specified VRF.
  • Failure: The test will fail if the SNMP agent has not the right number of IPv4 ACL(s) in the specified VRF.
Examples
anta.tests.snmp:\n  - VerifySnmpIPv4Acl:\n      number: 3\n      vrf: default\n
Source code in anta/tests/snmp.py
class VerifySnmpIPv4Acl(AntaTest):\n    \"\"\"Verifies if the SNMP agent has the right number IPv4 ACL(s) configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SNMP agent has the provided number of IPv4 ACL(s) in the specified VRF.\n    * Failure: The test will fail if the SNMP agent has not the right number of IPv4 ACL(s) in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.snmp:\n      - VerifySnmpIPv4Acl:\n          number: 3\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifySnmpIPv4Acl\"\n    description = \"Verifies if the SNMP agent has IPv4 ACL(s) configured.\"\n    categories: ClassVar[list[str]] = [\"snmp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show snmp ipv4 access-list summary\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySnmpIPv4Acl test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"The number of expected IPv4 ACL(s).\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for the SNMP agent. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySnmpIPv4Acl.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ipv4_acl_list = command_output[\"ipAclList\"][\"aclList\"]\n        ipv4_acl_number = len(ipv4_acl_list)\n        if ipv4_acl_number != self.inputs.number:\n            self.result.is_failure(f\"Expected {self.inputs.number} SNMP IPv4 ACL(s) in vrf {self.inputs.vrf} but got {ipv4_acl_number}\")\n            return\n\n        not_configured_acl = [acl[\"name\"] for acl in ipv4_acl_list if self.inputs.vrf not in acl[\"configuredVrfs\"] or self.inputs.vrf not in acl[\"activeVrfs\"]]\n\n        if not_configured_acl:\n            self.result.is_failure(f\"SNMP IPv4 ACL(s) not configured or active in vrf {self.inputs.vrf}: {not_configured_acl}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpIPv4Acl-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger The number of expected IPv4 ACL(s). - vrf str The name of the VRF in which to check for the SNMP agent. Defaults to `default` VRF. 'default'"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpIPv6Acl","title":"VerifySnmpIPv6Acl","text":"

Verifies if the SNMP agent has the right number IPv6 ACL(s) configured for a specified VRF.

Expected Results
  • Success: The test will pass if the SNMP agent has the provided number of IPv6 ACL(s) in the specified VRF.
  • Failure: The test will fail if the SNMP agent has not the right number of IPv6 ACL(s) in the specified VRF.
Examples
anta.tests.snmp:\n  - VerifySnmpIPv6Acl:\n      number: 3\n      vrf: default\n
Source code in anta/tests/snmp.py
class VerifySnmpIPv6Acl(AntaTest):\n    \"\"\"Verifies if the SNMP agent has the right number IPv6 ACL(s) configured for a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SNMP agent has the provided number of IPv6 ACL(s) in the specified VRF.\n    * Failure: The test will fail if the SNMP agent has not the right number of IPv6 ACL(s) in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.snmp:\n      - VerifySnmpIPv6Acl:\n          number: 3\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifySnmpIPv6Acl\"\n    description = \"Verifies if the SNMP agent has IPv6 ACL(s) configured.\"\n    categories: ClassVar[list[str]] = [\"snmp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show snmp ipv6 access-list summary\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySnmpIPv6Acl test.\"\"\"\n\n        number: PositiveInteger\n        \"\"\"The number of expected IPv6 ACL(s).\"\"\"\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for the SNMP agent. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySnmpIPv6Acl.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        ipv6_acl_list = command_output[\"ipv6AclList\"][\"aclList\"]\n        ipv6_acl_number = len(ipv6_acl_list)\n        if ipv6_acl_number != self.inputs.number:\n            self.result.is_failure(f\"Expected {self.inputs.number} SNMP IPv6 ACL(s) in vrf {self.inputs.vrf} but got {ipv6_acl_number}\")\n            return\n\n        acl_not_configured = [acl[\"name\"] for acl in ipv6_acl_list if self.inputs.vrf not in acl[\"configuredVrfs\"] or self.inputs.vrf not in acl[\"activeVrfs\"]]\n\n        if acl_not_configured:\n            self.result.is_failure(f\"SNMP IPv6 ACL(s) not configured or active in vrf {self.inputs.vrf}: {acl_not_configured}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpIPv6Acl-attributes","title":"Inputs","text":"Name Type Description Default number PositiveInteger The number of expected IPv6 ACL(s). - vrf str The name of the VRF in which to check for the SNMP agent. Defaults to `default` VRF. 'default'"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpLocation","title":"VerifySnmpLocation","text":"

Verifies the SNMP location of a device.

Expected Results
  • Success: The test will pass if the SNMP location matches the provided input.
  • Failure: The test will fail if the SNMP location does not match the provided input.
Examples
anta.tests.snmp:\n  - VerifySnmpLocation:\n      location: New York\n
Source code in anta/tests/snmp.py
class VerifySnmpLocation(AntaTest):\n    \"\"\"Verifies the SNMP location of a device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SNMP location matches the provided input.\n    * Failure: The test will fail if the SNMP location does not match the provided input.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.snmp:\n      - VerifySnmpLocation:\n          location: New York\n    ```\n    \"\"\"\n\n    name = \"VerifySnmpLocation\"\n    description = \"Verifies the SNMP location of a device.\"\n    categories: ClassVar[list[str]] = [\"snmp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show snmp\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySnmpLocation test.\"\"\"\n\n        location: str\n        \"\"\"Expected SNMP location of the device.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySnmpLocation.\"\"\"\n        location = self.instance_commands[0].json_output[\"location\"][\"location\"]\n\n        if location != self.inputs.location:\n            self.result.is_failure(f\"Expected `{self.inputs.location}` as the location, but found `{location}` instead.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpLocation-attributes","title":"Inputs","text":"Name Type Description Default location str Expected SNMP location of the device. -"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpStatus","title":"VerifySnmpStatus","text":"

Verifies whether the SNMP agent is enabled in a specified VRF.

Expected Results
  • Success: The test will pass if the SNMP agent is enabled in the specified VRF.
  • Failure: The test will fail if the SNMP agent is disabled in the specified VRF.
Examples
anta.tests.snmp:\n  - VerifySnmpStatus:\n      vrf: default\n
Source code in anta/tests/snmp.py
class VerifySnmpStatus(AntaTest):\n    \"\"\"Verifies whether the SNMP agent is enabled in a specified VRF.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the SNMP agent is enabled in the specified VRF.\n    * Failure: The test will fail if the SNMP agent is disabled in the specified VRF.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.snmp:\n      - VerifySnmpStatus:\n          vrf: default\n    ```\n    \"\"\"\n\n    name = \"VerifySnmpStatus\"\n    description = \"Verifies if the SNMP agent is enabled.\"\n    categories: ClassVar[list[str]] = [\"snmp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show snmp\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySnmpStatus test.\"\"\"\n\n        vrf: str = \"default\"\n        \"\"\"The name of the VRF in which to check for the SNMP agent. Defaults to `default` VRF.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySnmpStatus.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"enabled\"] and self.inputs.vrf in command_output[\"vrfs\"][\"snmpVrfs\"]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"SNMP agent disabled in vrf {self.inputs.vrf}\")\n
"},{"location":"api/tests.snmp/#anta.tests.snmp.VerifySnmpStatus-attributes","title":"Inputs","text":"Name Type Description Default vrf str The name of the VRF in which to check for the SNMP agent. Defaults to `default` VRF. 'default'"},{"location":"api/tests.software/","title":"Software","text":""},{"location":"api/tests.software/#anta.tests.software.VerifyEOSExtensions","title":"VerifyEOSExtensions","text":"

Verifies that all EOS extensions installed on the device are enabled for boot persistence.

Expected Results
  • Success: The test will pass if all EOS extensions installed on the device are enabled for boot persistence.
  • Failure: The test will fail if some EOS extensions installed on the device are not enabled for boot persistence.
Examples
anta.tests.software:\n  - VerifyEOSExtensions:\n
Source code in anta/tests/software.py
class VerifyEOSExtensions(AntaTest):\n    \"\"\"Verifies that all EOS extensions installed on the device are enabled for boot persistence.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all EOS extensions installed on the device are enabled for boot persistence.\n    * Failure: The test will fail if some EOS extensions installed on the device are not enabled for boot persistence.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.software:\n      - VerifyEOSExtensions:\n    ```\n    \"\"\"\n\n    name = \"VerifyEOSExtensions\"\n    description = \"Verifies that all EOS extensions installed on the device are enabled for boot persistence.\"\n    categories: ClassVar[list[str]] = [\"software\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [\n        AntaCommand(command=\"show extensions\", revision=2),\n        AntaCommand(command=\"show boot-extensions\", revision=1),\n    ]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyEOSExtensions.\"\"\"\n        boot_extensions = []\n        show_extensions_command_output = self.instance_commands[0].json_output\n        show_boot_extensions_command_output = self.instance_commands[1].json_output\n        installed_extensions = [\n            extension for extension, extension_data in show_extensions_command_output[\"extensions\"].items() if extension_data[\"status\"] == \"installed\"\n        ]\n        for extension in show_boot_extensions_command_output[\"extensions\"]:\n            formatted_extension = extension.strip(\"\\n\")\n            if formatted_extension != \"\":\n                boot_extensions.append(formatted_extension)\n        installed_extensions.sort()\n        boot_extensions.sort()\n        if installed_extensions == boot_extensions:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Missing EOS extensions: installed {installed_extensions} / configured: {boot_extensions}\")\n
"},{"location":"api/tests.software/#anta.tests.software.VerifyEOSVersion","title":"VerifyEOSVersion","text":"

Verifies that the device is running one of the allowed EOS version.

Expected Results
  • Success: The test will pass if the device is running one of the allowed EOS version.
  • Failure: The test will fail if the device is not running one of the allowed EOS version.
Examples
anta.tests.software:\n  - VerifyEOSVersion:\n      versions:\n        - 4.25.4M\n        - 4.26.1F\n
Source code in anta/tests/software.py
class VerifyEOSVersion(AntaTest):\n    \"\"\"Verifies that the device is running one of the allowed EOS version.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is running one of the allowed EOS version.\n    * Failure: The test will fail if the device is not running one of the allowed EOS version.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.software:\n      - VerifyEOSVersion:\n          versions:\n            - 4.25.4M\n            - 4.26.1F\n    ```\n    \"\"\"\n\n    name = \"VerifyEOSVersion\"\n    description = \"Verifies the EOS version of the device.\"\n    categories: ClassVar[list[str]] = [\"software\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show version\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyEOSVersion test.\"\"\"\n\n        versions: list[str]\n        \"\"\"List of allowed EOS versions.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyEOSVersion.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"version\"] in self.inputs.versions:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f'device is running version \"{command_output[\"version\"]}\" not in expected versions: {self.inputs.versions}')\n
"},{"location":"api/tests.software/#anta.tests.software.VerifyEOSVersion-attributes","title":"Inputs","text":"Name Type Description Default versions list[str] List of allowed EOS versions. -"},{"location":"api/tests.software/#anta.tests.software.VerifyTerminAttrVersion","title":"VerifyTerminAttrVersion","text":"

Verifies that he device is running one of the allowed TerminAttr version.

Expected Results
  • Success: The test will pass if the device is running one of the allowed TerminAttr version.
  • Failure: The test will fail if the device is not running one of the allowed TerminAttr version.
Examples
anta.tests.software:\n  - VerifyTerminAttrVersion:\n      versions:\n        - v1.13.6\n        - v1.8.0\n
Source code in anta/tests/software.py
class VerifyTerminAttrVersion(AntaTest):\n    \"\"\"Verifies that he device is running one of the allowed TerminAttr version.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device is running one of the allowed TerminAttr version.\n    * Failure: The test will fail if the device is not running one of the allowed TerminAttr version.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.software:\n      - VerifyTerminAttrVersion:\n          versions:\n            - v1.13.6\n            - v1.8.0\n    ```\n    \"\"\"\n\n    name = \"VerifyTerminAttrVersion\"\n    description = \"Verifies the TerminAttr version of the device.\"\n    categories: ClassVar[list[str]] = [\"software\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show version detail\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyTerminAttrVersion test.\"\"\"\n\n        versions: list[str]\n        \"\"\"List of allowed TerminAttr versions.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyTerminAttrVersion.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        command_output_data = command_output[\"details\"][\"packages\"][\"TerminAttr-core\"][\"version\"]\n        if command_output_data in self.inputs.versions:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"device is running TerminAttr version {command_output_data} and is not in the allowed list: {self.inputs.versions}\")\n
"},{"location":"api/tests.software/#anta.tests.software.VerifyTerminAttrVersion-attributes","title":"Inputs","text":"Name Type Description Default versions list[str] List of allowed TerminAttr versions. -"},{"location":"api/tests.stp/","title":"STP","text":""},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPBlockedPorts","title":"VerifySTPBlockedPorts","text":"

Verifies there is no STP blocked ports.

Expected Results
  • Success: The test will pass if there are NO ports blocked by STP.
  • Failure: The test will fail if there are ports blocked by STP.
Examples
anta.tests.stp:\n  - VerifySTPBlockedPorts:\n
Source code in anta/tests/stp.py
class VerifySTPBlockedPorts(AntaTest):\n    \"\"\"Verifies there is no STP blocked ports.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are NO ports blocked by STP.\n    * Failure: The test will fail if there are ports blocked by STP.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stp:\n      - VerifySTPBlockedPorts:\n    ```\n    \"\"\"\n\n    name = \"VerifySTPBlockedPorts\"\n    description = \"Verifies there is no STP blocked ports.\"\n    categories: ClassVar[list[str]] = [\"stp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show spanning-tree blockedports\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySTPBlockedPorts.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if not (stp_instances := command_output[\"spanningTreeInstances\"]):\n            self.result.is_success()\n        else:\n            for key, value in stp_instances.items():\n                stp_instances[key] = value.pop(\"spanningTreeBlockedPorts\")\n            self.result.is_failure(f\"The following ports are blocked by STP: {stp_instances}\")\n
"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPCounters","title":"VerifySTPCounters","text":"

Verifies there is no errors in STP BPDU packets.

Expected Results
  • Success: The test will pass if there are NO STP BPDU packet errors under all interfaces participating in STP.
  • Failure: The test will fail if there are STP BPDU packet errors on one or many interface(s).
Examples
anta.tests.stp:\n  - VerifySTPCounters:\n
Source code in anta/tests/stp.py
class VerifySTPCounters(AntaTest):\n    \"\"\"Verifies there is no errors in STP BPDU packets.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are NO STP BPDU packet errors under all interfaces participating in STP.\n    * Failure: The test will fail if there are STP BPDU packet errors on one or many interface(s).\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stp:\n      - VerifySTPCounters:\n    ```\n    \"\"\"\n\n    name = \"VerifySTPCounters\"\n    description = \"Verifies there is no errors in STP BPDU packets.\"\n    categories: ClassVar[list[str]] = [\"stp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show spanning-tree counters\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySTPCounters.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        interfaces_with_errors = [\n            interface for interface, counters in command_output[\"interfaces\"].items() if counters[\"bpduTaggedError\"] or counters[\"bpduOtherError\"] != 0\n        ]\n        if interfaces_with_errors:\n            self.result.is_failure(f\"The following interfaces have STP BPDU packet errors: {interfaces_with_errors}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPForwardingPorts","title":"VerifySTPForwardingPorts","text":"

Verifies that all interfaces are in a forwarding state for a provided list of VLAN(s).

Expected Results
  • Success: The test will pass if all interfaces are in a forwarding state for the specified VLAN(s).
  • Failure: The test will fail if one or many interfaces are NOT in a forwarding state in the specified VLAN(s).
Examples
anta.tests.stp:\n  - VerifySTPForwardingPorts:\n      vlans:\n        - 10\n        - 20\n
Source code in anta/tests/stp.py
class VerifySTPForwardingPorts(AntaTest):\n    \"\"\"Verifies that all interfaces are in a forwarding state for a provided list of VLAN(s).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all interfaces are in a forwarding state for the specified VLAN(s).\n    * Failure: The test will fail if one or many interfaces are NOT in a forwarding state in the specified VLAN(s).\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stp:\n      - VerifySTPForwardingPorts:\n          vlans:\n            - 10\n            - 20\n    ```\n    \"\"\"\n\n    name = \"VerifySTPForwardingPorts\"\n    description = \"Verifies that all interfaces are forwarding for a provided list of VLAN(s).\"\n    categories: ClassVar[list[str]] = [\"stp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show spanning-tree topology vlan {vlan} status\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySTPForwardingPorts test.\"\"\"\n\n        vlans: list[Vlan]\n        \"\"\"List of VLAN on which to verify forwarding states.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each VLAN in the input list.\"\"\"\n        return [template.render(vlan=vlan) for vlan in self.inputs.vlans]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySTPForwardingPorts.\"\"\"\n        not_configured = []\n        not_forwarding = []\n        for command in self.instance_commands:\n            vlan_id = command.params.vlan\n            if not (topologies := get_value(command.json_output, \"topologies\")):\n                not_configured.append(vlan_id)\n            else:\n                interfaces_not_forwarding = []\n                for value in topologies.values():\n                    if vlan_id and int(vlan_id) in value[\"vlans\"]:\n                        interfaces_not_forwarding = [interface for interface, state in value[\"interfaces\"].items() if state[\"state\"] != \"forwarding\"]\n                if interfaces_not_forwarding:\n                    not_forwarding.append({f\"VLAN {vlan_id}\": interfaces_not_forwarding})\n        if not_configured:\n            self.result.is_failure(f\"STP instance is not configured for the following VLAN(s): {not_configured}\")\n        if not_forwarding:\n            self.result.is_failure(f\"The following VLAN(s) have interface(s) that are not in a forwarding state: {not_forwarding}\")\n        if not not_configured and not interfaces_not_forwarding:\n            self.result.is_success()\n
"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPForwardingPorts-attributes","title":"Inputs","text":"Name Type Description Default vlans list[Vlan] List of VLAN on which to verify forwarding states. -"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPMode","title":"VerifySTPMode","text":"

Verifies the configured STP mode for a provided list of VLAN(s).

Expected Results
  • Success: The test will pass if the STP mode is configured properly in the specified VLAN(s).
  • Failure: The test will fail if the STP mode is NOT configured properly for one or more specified VLAN(s).
Examples
anta.tests.stp:\n  - VerifySTPMode:\n      mode: rapidPvst\n      vlans:\n        - 10\n        - 20\n
Source code in anta/tests/stp.py
class VerifySTPMode(AntaTest):\n    \"\"\"Verifies the configured STP mode for a provided list of VLAN(s).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the STP mode is configured properly in the specified VLAN(s).\n    * Failure: The test will fail if the STP mode is NOT configured properly for one or more specified VLAN(s).\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stp:\n      - VerifySTPMode:\n          mode: rapidPvst\n          vlans:\n            - 10\n            - 20\n    ```\n    \"\"\"\n\n    name = \"VerifySTPMode\"\n    description = \"Verifies the configured STP mode for a provided list of VLAN(s).\"\n    categories: ClassVar[list[str]] = [\"stp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show spanning-tree vlan {vlan}\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySTPMode test.\"\"\"\n\n        mode: Literal[\"mstp\", \"rstp\", \"rapidPvst\"] = \"mstp\"\n        \"\"\"STP mode to verify. Supported values: mstp, rstp, rapidPvst. Defaults to mstp.\"\"\"\n        vlans: list[Vlan]\n        \"\"\"List of VLAN on which to verify STP mode.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each VLAN in the input list.\"\"\"\n        return [template.render(vlan=vlan) for vlan in self.inputs.vlans]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySTPMode.\"\"\"\n        not_configured = []\n        wrong_stp_mode = []\n        for command in self.instance_commands:\n            vlan_id = command.params.vlan\n            if not (\n                stp_mode := get_value(\n                    command.json_output,\n                    f\"spanningTreeVlanInstances.{vlan_id}.spanningTreeVlanInstance.protocol\",\n                )\n            ):\n                not_configured.append(vlan_id)\n            elif stp_mode != self.inputs.mode:\n                wrong_stp_mode.append(vlan_id)\n        if not_configured:\n            self.result.is_failure(f\"STP mode '{self.inputs.mode}' not configured for the following VLAN(s): {not_configured}\")\n        if wrong_stp_mode:\n            self.result.is_failure(f\"Wrong STP mode configured for the following VLAN(s): {wrong_stp_mode}\")\n        if not not_configured and not wrong_stp_mode:\n            self.result.is_success()\n
"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPMode-attributes","title":"Inputs","text":"Name Type Description Default mode Literal['mstp', 'rstp', 'rapidPvst'] STP mode to verify. Supported values: mstp, rstp, rapidPvst. Defaults to mstp. 'mstp' vlans list[Vlan] List of VLAN on which to verify STP mode. -"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPRootPriority","title":"VerifySTPRootPriority","text":"

Verifies the STP root priority for a provided list of VLAN or MST instance ID(s).

Expected Results
  • Success: The test will pass if the STP root priority is configured properly for the specified VLAN or MST instance ID(s).
  • Failure: The test will fail if the STP root priority is NOT configured properly for the specified VLAN or MST instance ID(s).
Examples
anta.tests.stp:\n  - VerifySTPRootPriority:\n      priority: 32768\n      instances:\n        - 10\n        - 20\n
Source code in anta/tests/stp.py
class VerifySTPRootPriority(AntaTest):\n    \"\"\"Verifies the STP root priority for a provided list of VLAN or MST instance ID(s).\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the STP root priority is configured properly for the specified VLAN or MST instance ID(s).\n    * Failure: The test will fail if the STP root priority is NOT configured properly for the specified VLAN or MST instance ID(s).\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stp:\n      - VerifySTPRootPriority:\n          priority: 32768\n          instances:\n            - 10\n            - 20\n    ```\n    \"\"\"\n\n    name = \"VerifySTPRootPriority\"\n    description = \"Verifies the STP root priority for a provided list of VLAN or MST instance ID(s).\"\n    categories: ClassVar[list[str]] = [\"stp\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show spanning-tree root detail\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifySTPRootPriority test.\"\"\"\n\n        priority: int\n        \"\"\"STP root priority to verify.\"\"\"\n        instances: list[Vlan] = Field(default=[])\n        \"\"\"List of VLAN or MST instance ID(s). If empty, ALL VLAN or MST instance ID(s) will be verified.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifySTPRootPriority.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if not (stp_instances := command_output[\"instances\"]):\n            self.result.is_failure(\"No STP instances configured\")\n            return\n        # Checking the type of instances based on first instance\n        first_name = next(iter(stp_instances))\n        if first_name.startswith(\"MST\"):\n            prefix = \"MST\"\n        elif first_name.startswith(\"VL\"):\n            prefix = \"VL\"\n        else:\n            self.result.is_failure(f\"Unsupported STP instance type: {first_name}\")\n            return\n        check_instances = [f\"{prefix}{instance_id}\" for instance_id in self.inputs.instances] if self.inputs.instances else command_output[\"instances\"].keys()\n        wrong_priority_instances = [\n            instance for instance in check_instances if get_value(command_output, f\"instances.{instance}.rootBridge.priority\") != self.inputs.priority\n        ]\n        if wrong_priority_instances:\n            self.result.is_failure(f\"The following instance(s) have the wrong STP root priority configured: {wrong_priority_instances}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.stp/#anta.tests.stp.VerifySTPRootPriority-attributes","title":"Inputs","text":"Name Type Description Default priority int STP root priority to verify. - instances list[Vlan] List of VLAN or MST instance ID(s). If empty, ALL VLAN or MST instance ID(s) will be verified. Field(default=[])"},{"location":"api/tests.stun/","title":"STUN","text":""},{"location":"api/tests.stun/#anta.tests.stun.VerifyStunClient","title":"VerifyStunClient","text":"

Verifies the configuration of the STUN client, specifically the IPv4 source address and port.

Optionally, it can also verify the public address and port.

Expected Results
  • Success: The test will pass if the STUN client is correctly configured with the specified IPv4 source address/port and public address/port.
  • Failure: The test will fail if the STUN client is not configured or if the IPv4 source address, public address, or port details are incorrect.
Examples
anta.tests.stun:\n  - VerifyStunClient:\n      stun_clients:\n        - source_address: 172.18.3.2\n          public_address: 172.18.3.21\n          source_port: 4500\n          public_port: 6006\n        - source_address: 100.64.3.2\n          public_address: 100.64.3.21\n          source_port: 4500\n          public_port: 6006\n
Source code in anta/tests/stun.py
class VerifyStunClient(AntaTest):\n    \"\"\"\n    Verifies the configuration of the STUN client, specifically the IPv4 source address and port.\n\n    Optionally, it can also verify the public address and port.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the STUN client is correctly configured with the specified IPv4 source address/port and public address/port.\n    * Failure: The test will fail if the STUN client is not configured or if the IPv4 source address, public address, or port details are incorrect.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stun:\n      - VerifyStunClient:\n          stun_clients:\n            - source_address: 172.18.3.2\n              public_address: 172.18.3.21\n              source_port: 4500\n              public_port: 6006\n            - source_address: 100.64.3.2\n              public_address: 100.64.3.21\n              source_port: 4500\n              public_port: 6006\n    ```\n    \"\"\"\n\n    name = \"VerifyStunClient\"\n    description = \"Verifies the STUN client is configured with the specified IPv4 source address and port. Validate the public IP and port if provided.\"\n    categories: ClassVar[list[str]] = [\"stun\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaTemplate(template=\"show stun client translations {source_address} {source_port}\")]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyStunClient test.\"\"\"\n\n        stun_clients: list[ClientAddress]\n\n        class ClientAddress(BaseModel):\n            \"\"\"Source and public address/port details of STUN client.\"\"\"\n\n            source_address: IPv4Address\n            \"\"\"IPv4 source address of STUN client.\"\"\"\n            source_port: Port = 4500\n            \"\"\"Source port number for STUN client.\"\"\"\n            public_address: IPv4Address | None = None\n            \"\"\"Optional IPv4 public address of STUN client.\"\"\"\n            public_port: Port | None = None\n            \"\"\"Optional public port number for STUN client.\"\"\"\n\n    def render(self, template: AntaTemplate) -> list[AntaCommand]:\n        \"\"\"Render the template for each STUN translation.\"\"\"\n        return [template.render(source_address=client.source_address, source_port=client.source_port) for client in self.inputs.stun_clients]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyStunClient.\"\"\"\n        self.result.is_success()\n\n        # Iterate over each command output and corresponding client input\n        for command, client_input in zip(self.instance_commands, self.inputs.stun_clients):\n            bindings = command.json_output[\"bindings\"]\n            source_address = str(command.params.source_address)\n            source_port = command.params.source_port\n\n            # If no bindings are found for the STUN client, mark the test as a failure and continue with the next client\n            if not bindings:\n                self.result.is_failure(f\"STUN client transaction for source `{source_address}:{source_port}` is not found.\")\n                continue\n\n            # Extract the public address and port from the client input\n            public_address = client_input.public_address\n            public_port = client_input.public_port\n\n            # Extract the transaction ID from the bindings\n            transaction_id = next(iter(bindings.keys()))\n\n            # Prepare the actual and expected STUN data for comparison\n            actual_stun_data = {\n                \"source ip\": get_value(bindings, f\"{transaction_id}.sourceAddress.ip\"),\n                \"source port\": get_value(bindings, f\"{transaction_id}.sourceAddress.port\"),\n            }\n            expected_stun_data = {\"source ip\": source_address, \"source port\": source_port}\n\n            # If public address is provided, add it to the actual and expected STUN data\n            if public_address is not None:\n                actual_stun_data[\"public ip\"] = get_value(bindings, f\"{transaction_id}.publicAddress.ip\")\n                expected_stun_data[\"public ip\"] = str(public_address)\n\n            # If public port is provided, add it to the actual and expected STUN data\n            if public_port is not None:\n                actual_stun_data[\"public port\"] = get_value(bindings, f\"{transaction_id}.publicAddress.port\")\n                expected_stun_data[\"public port\"] = public_port\n\n            # If the actual STUN data does not match the expected STUN data, mark the test as failure\n            if actual_stun_data != expected_stun_data:\n                failed_log = get_failed_logs(expected_stun_data, actual_stun_data)\n                self.result.is_failure(f\"For STUN source `{source_address}:{source_port}`:{failed_log}\")\n
"},{"location":"api/tests.stun/#anta.tests.stun.VerifyStunClient-attributes","title":"Inputs","text":"Name Type Description Default"},{"location":"api/tests.stun/#anta.tests.stun.VerifyStunClient-attributes","title":"ClientAddress","text":"Name Type Description Default source_address IPv4Address IPv4 source address of STUN client. - source_port Port Source port number for STUN client. 4500 public_address IPv4Address | None Optional IPv4 public address of STUN client. None public_port Port | None Optional public port number for STUN client. None"},{"location":"api/tests.stun/#anta.tests.stun.VerifyStunServer","title":"VerifyStunServer","text":"

Verifies the STUN server status is enabled and running.

Expected Results
  • Success: The test will pass if the STUN server status is enabled and running.
  • Failure: The test will fail if the STUN server is disabled or not running.
Examples
anta.tests.stun:\n  - VerifyStunServer:\n
Source code in anta/tests/stun.py
class VerifyStunServer(AntaTest):\n    \"\"\"\n    Verifies the STUN server status is enabled and running.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the STUN server status is enabled and running.\n    * Failure: The test will fail if the STUN server is disabled or not running.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.stun:\n      - VerifyStunServer:\n    ```\n    \"\"\"\n\n    name = \"VerifyStunServer\"\n    description = \"Verifies the STUN server status is enabled and running.\"\n    categories: ClassVar[list[str]] = [\"stun\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show stun server status\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyStunServer.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        status_disabled = not command_output.get(\"enabled\")\n        not_running = command_output.get(\"pid\") == 0\n\n        if status_disabled and not_running:\n            self.result.is_failure(\"STUN server status is disabled and not running.\")\n        elif status_disabled:\n            self.result.is_failure(\"STUN server status is disabled.\")\n        elif not_running:\n            self.result.is_failure(\"STUN server is not running.\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.system/","title":"System","text":""},{"location":"api/tests.system/#anta.tests.system.VerifyAgentLogs","title":"VerifyAgentLogs","text":"

Verifies that no agent crash reports are present on the device.

Expected Results
  • Success: The test will pass if there is NO agent crash reported.
  • Failure: The test will fail if any agent crashes are reported.
Examples
anta.tests.system:\n  - VerifyAgentLogs:\n
Source code in anta/tests/system.py
class VerifyAgentLogs(AntaTest):\n    \"\"\"Verifies that no agent crash reports are present on the device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there is NO agent crash reported.\n    * Failure: The test will fail if any agent crashes are reported.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyAgentLogs:\n    ```\n    \"\"\"\n\n    name = \"VerifyAgentLogs\"\n    description = \"Verifies there are no agent crash reports.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show agent logs crash\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyAgentLogs.\"\"\"\n        command_output = self.instance_commands[0].text_output\n        if len(command_output) == 0:\n            self.result.is_success()\n        else:\n            pattern = re.compile(r\"^===> (.*?) <===$\", re.MULTILINE)\n            agents = \"\\n * \".join(pattern.findall(command_output))\n            self.result.is_failure(f\"Device has reported agent crashes:\\n * {agents}\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyCPUUtilization","title":"VerifyCPUUtilization","text":"

Verifies whether the CPU utilization is below 75%.

Expected Results
  • Success: The test will pass if the CPU utilization is below 75%.
  • Failure: The test will fail if the CPU utilization is over 75%.
Examples
anta.tests.system:\n  - VerifyCPUUtilization:\n
Source code in anta/tests/system.py
class VerifyCPUUtilization(AntaTest):\n    \"\"\"Verifies whether the CPU utilization is below 75%.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the CPU utilization is below 75%.\n    * Failure: The test will fail if the CPU utilization is over 75%.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyCPUUtilization:\n    ```\n    \"\"\"\n\n    name = \"VerifyCPUUtilization\"\n    description = \"Verifies whether the CPU utilization is below 75%.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show processes top once\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyCPUUtilization.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        command_output_data = command_output[\"cpuInfo\"][\"%Cpu(s)\"][\"idle\"]\n        if command_output_data > CPU_IDLE_THRESHOLD:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device has reported a high CPU utilization: {100 - command_output_data}%\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyCoredump","title":"VerifyCoredump","text":"

Verifies if there are core dump files in the /var/core directory.

Expected Results
  • Success: The test will pass if there are NO core dump(s) in /var/core.
  • Failure: The test will fail if there are core dump(s) in /var/core.
Info
  • This test will NOT check for minidump(s) generated by certain agents in /var/core/minidump.
Examples
anta.tests.system:\n  - VerifyCoreDump:\n
Source code in anta/tests/system.py
class VerifyCoredump(AntaTest):\n    \"\"\"Verifies if there are core dump files in the /var/core directory.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are NO core dump(s) in /var/core.\n    * Failure: The test will fail if there are core dump(s) in /var/core.\n\n    Info\n    ----\n    * This test will NOT check for minidump(s) generated by certain agents in /var/core/minidump.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyCoreDump:\n    ```\n    \"\"\"\n\n    name = \"VerifyCoredump\"\n    description = \"Verifies there are no core dump files.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show system coredump\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyCoredump.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        core_files = command_output[\"coreFiles\"]\n        if \"minidump\" in core_files:\n            core_files.remove(\"minidump\")\n        if not core_files:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Core dump(s) have been found: {core_files}\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyFileSystemUtilization","title":"VerifyFileSystemUtilization","text":"

Verifies that no partition is utilizing more than 75% of its disk space.

Expected Results
  • Success: The test will pass if all partitions are using less than 75% of its disk space.
  • Failure: The test will fail if any partitions are using more than 75% of its disk space.
Examples
anta.tests.system:\n  - VerifyFileSystemUtilization:\n
Source code in anta/tests/system.py
class VerifyFileSystemUtilization(AntaTest):\n    \"\"\"Verifies that no partition is utilizing more than 75% of its disk space.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all partitions are using less than 75% of its disk space.\n    * Failure: The test will fail if any partitions are using more than 75% of its disk space.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyFileSystemUtilization:\n    ```\n    \"\"\"\n\n    name = \"VerifyFileSystemUtilization\"\n    description = \"Verifies that no partition is utilizing more than 75% of its disk space.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"bash timeout 10 df -h\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyFileSystemUtilization.\"\"\"\n        command_output = self.instance_commands[0].text_output\n        self.result.is_success()\n        for line in command_output.split(\"\\n\")[1:]:\n            if \"loop\" not in line and len(line) > 0 and (percentage := int(line.split()[4].replace(\"%\", \"\"))) > DISK_SPACE_THRESHOLD:\n                self.result.is_failure(f\"Mount point {line} is higher than 75%: reported {percentage}%\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyMemoryUtilization","title":"VerifyMemoryUtilization","text":"

Verifies whether the memory utilization is below 75%.

Expected Results
  • Success: The test will pass if the memory utilization is below 75%.
  • Failure: The test will fail if the memory utilization is over 75%.
Examples
anta.tests.system:\n  - VerifyMemoryUtilization:\n
Source code in anta/tests/system.py
class VerifyMemoryUtilization(AntaTest):\n    \"\"\"Verifies whether the memory utilization is below 75%.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the memory utilization is below 75%.\n    * Failure: The test will fail if the memory utilization is over 75%.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyMemoryUtilization:\n    ```\n    \"\"\"\n\n    name = \"VerifyMemoryUtilization\"\n    description = \"Verifies whether the memory utilization is below 75%.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show version\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyMemoryUtilization.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        memory_usage = command_output[\"memFree\"] / command_output[\"memTotal\"]\n        if memory_usage > MEMORY_THRESHOLD:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device has reported a high memory usage: {(1 - memory_usage)*100:.2f}%\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyNTP","title":"VerifyNTP","text":"

Verifies that the Network Time Protocol (NTP) is synchronized.

Expected Results
  • Success: The test will pass if the NTP is synchronised.
  • Failure: The test will fail if the NTP is NOT synchronised.
Examples
anta.tests.system:\n  - VerifyNTP:\n
Source code in anta/tests/system.py
class VerifyNTP(AntaTest):\n    \"\"\"Verifies that the Network Time Protocol (NTP) is synchronized.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the NTP is synchronised.\n    * Failure: The test will fail if the NTP is NOT synchronised.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyNTP:\n    ```\n    \"\"\"\n\n    name = \"VerifyNTP\"\n    description = \"Verifies if NTP is synchronised.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show ntp status\", ofmt=\"text\")]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyNTP.\"\"\"\n        command_output = self.instance_commands[0].text_output\n        if command_output.split(\"\\n\")[0].split(\" \")[0] == \"synchronised\":\n            self.result.is_success()\n        else:\n            data = command_output.split(\"\\n\")[0]\n            self.result.is_failure(f\"The device is not synchronized with the configured NTP server(s): '{data}'\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyReloadCause","title":"VerifyReloadCause","text":"

Verifies the last reload cause of the device.

Expected Results
  • Success: The test will pass if there are NO reload causes or if the last reload was caused by the user or after an FPGA upgrade.
  • Failure: The test will fail if the last reload was NOT caused by the user or after an FPGA upgrade.
  • Error: The test will report an error if the reload cause is NOT available.
Examples
anta.tests.system:\n  - VerifyReloadCause:\n
Source code in anta/tests/system.py
class VerifyReloadCause(AntaTest):\n    \"\"\"Verifies the last reload cause of the device.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if there are NO reload causes or if the last reload was caused by the user or after an FPGA upgrade.\n    * Failure: The test will fail if the last reload was NOT caused by the user or after an FPGA upgrade.\n    * Error: The test will report an error if the reload cause is NOT available.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyReloadCause:\n    ```\n    \"\"\"\n\n    name = \"VerifyReloadCause\"\n    description = \"Verifies the last reload cause of the device.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show reload cause\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyReloadCause.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if \"resetCauses\" not in command_output:\n            self.result.is_error(message=\"No reload causes available\")\n            return\n        if len(command_output[\"resetCauses\"]) == 0:\n            # No reload causes\n            self.result.is_success()\n            return\n        reset_causes = command_output[\"resetCauses\"]\n        command_output_data = reset_causes[0].get(\"description\")\n        if command_output_data in [\n            \"Reload requested by the user.\",\n            \"Reload requested after FPGA upgrade\",\n        ]:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Reload cause is: '{command_output_data}'\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyUptime","title":"VerifyUptime","text":"

Verifies if the device uptime is higher than the provided minimum uptime value.

Expected Results
  • Success: The test will pass if the device uptime is higher than the provided value.
  • Failure: The test will fail if the device uptime is lower than the provided value.
Examples
anta.tests.system:\n  - VerifyUptime:\n      minimum: 86400\n
Source code in anta/tests/system.py
class VerifyUptime(AntaTest):\n    \"\"\"Verifies if the device uptime is higher than the provided minimum uptime value.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the device uptime is higher than the provided value.\n    * Failure: The test will fail if the device uptime is lower than the provided value.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.system:\n      - VerifyUptime:\n          minimum: 86400\n    ```\n    \"\"\"\n\n    name = \"VerifyUptime\"\n    description = \"Verifies the device uptime.\"\n    categories: ClassVar[list[str]] = [\"system\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show uptime\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyUptime test.\"\"\"\n\n        minimum: PositiveInteger\n        \"\"\"Minimum uptime in seconds.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyUptime.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if command_output[\"upTime\"] > self.inputs.minimum:\n            self.result.is_success()\n        else:\n            self.result.is_failure(f\"Device uptime is {command_output['upTime']} seconds\")\n
"},{"location":"api/tests.system/#anta.tests.system.VerifyUptime-attributes","title":"Inputs","text":"Name Type Description Default minimum PositiveInteger Minimum uptime in seconds. -"},{"location":"api/tests.vlan/","title":"VLAN","text":""},{"location":"api/tests.vlan/#anta.tests.vlan.VerifyVlanInternalPolicy","title":"VerifyVlanInternalPolicy","text":"

Verifies if the VLAN internal allocation policy is ascending or descending and if the VLANs are within the specified range.

Expected Results
  • Success: The test will pass if the VLAN internal allocation policy is either ascending or descending and the VLANs are within the specified range.
  • Failure: The test will fail if the VLAN internal allocation policy is neither ascending nor descending or the VLANs are outside the specified range.
Examples
anta.tests.vlan:\n  - VerifyVlanInternalPolicy:\n      policy: ascending\n      start_vlan_id: 1006\n      end_vlan_id: 4094\n
Source code in anta/tests/vlan.py
class VerifyVlanInternalPolicy(AntaTest):\n    \"\"\"Verifies if the VLAN internal allocation policy is ascending or descending and if the VLANs are within the specified range.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the VLAN internal allocation policy is either ascending or descending\n                 and the VLANs are within the specified range.\n    * Failure: The test will fail if the VLAN internal allocation policy is neither ascending nor descending\n                 or the VLANs are outside the specified range.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.vlan:\n      - VerifyVlanInternalPolicy:\n          policy: ascending\n          start_vlan_id: 1006\n          end_vlan_id: 4094\n    ```\n    \"\"\"\n\n    name = \"VerifyVlanInternalPolicy\"\n    description = \"Verifies the VLAN internal allocation policy and the range of VLANs.\"\n    categories: ClassVar[list[str]] = [\"vlan\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show vlan internal allocation policy\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyVlanInternalPolicy test.\"\"\"\n\n        policy: Literal[\"ascending\", \"descending\"]\n        \"\"\"The VLAN internal allocation policy. Supported values: ascending, descending.\"\"\"\n        start_vlan_id: Vlan\n        \"\"\"The starting VLAN ID in the range.\"\"\"\n        end_vlan_id: Vlan\n        \"\"\"The ending VLAN ID in the range.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyVlanInternalPolicy.\"\"\"\n        command_output = self.instance_commands[0].json_output\n\n        keys_to_verify = [\"policy\", \"startVlanId\", \"endVlanId\"]\n        actual_policy_output = {key: get_value(command_output, key) for key in keys_to_verify}\n        expected_policy_output = {\"policy\": self.inputs.policy, \"startVlanId\": self.inputs.start_vlan_id, \"endVlanId\": self.inputs.end_vlan_id}\n\n        # Check if the actual output matches the expected output\n        if actual_policy_output != expected_policy_output:\n            failed_log = \"The VLAN internal allocation policy is not configured properly:\"\n            failed_log += get_failed_logs(expected_policy_output, actual_policy_output)\n            self.result.is_failure(failed_log)\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.vlan/#anta.tests.vlan.VerifyVlanInternalPolicy-attributes","title":"Inputs","text":"Name Type Description Default policy Literal['ascending', 'descending'] The VLAN internal allocation policy. Supported values: ascending, descending. - start_vlan_id Vlan The starting VLAN ID in the range. - end_vlan_id Vlan The ending VLAN ID in the range. -"},{"location":"api/tests.vxlan/","title":"VXLAN","text":""},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlan1ConnSettings","title":"VerifyVxlan1ConnSettings","text":"

Verifies the interface vxlan1 source interface and UDP port.

Expected Results
  • Success: Passes if the interface vxlan1 source interface and UDP port are correct.
  • Failure: Fails if the interface vxlan1 source interface or UDP port are incorrect.
  • Skipped: Skips if the Vxlan1 interface is not configured.
Examples
anta.tests.vxlan:\n  - VerifyVxlan1ConnSettings:\n      source_interface: Loopback1\n      udp_port: 4789\n
Source code in anta/tests/vxlan.py
class VerifyVxlan1ConnSettings(AntaTest):\n    \"\"\"Verifies the interface vxlan1 source interface and UDP port.\n\n    Expected Results\n    ----------------\n    * Success: Passes if the interface vxlan1 source interface and UDP port are correct.\n    * Failure: Fails if the interface vxlan1 source interface or UDP port are incorrect.\n    * Skipped: Skips if the Vxlan1 interface is not configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.vxlan:\n      - VerifyVxlan1ConnSettings:\n          source_interface: Loopback1\n          udp_port: 4789\n    ```\n    \"\"\"\n\n    name = \"VerifyVxlan1ConnSettings\"\n    description = \"Verifies the interface vxlan1 source interface and UDP port.\"\n    categories: ClassVar[list[str]] = [\"vxlan\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyVxlan1ConnSettings test.\"\"\"\n\n        source_interface: VxlanSrcIntf\n        \"\"\"Source loopback interface of vxlan1 interface.\"\"\"\n        udp_port: int = Field(ge=1024, le=65335)\n        \"\"\"UDP port used for vxlan1 interface.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyVxlan1ConnSettings.\"\"\"\n        self.result.is_success()\n        command_output = self.instance_commands[0].json_output\n\n        # Skip the test case if vxlan1 interface is not configured\n        vxlan_output = get_value(command_output, \"interfaces.Vxlan1\")\n        if not vxlan_output:\n            self.result.is_skipped(\"Vxlan1 interface is not configured.\")\n            return\n\n        src_intf = vxlan_output.get(\"srcIpIntf\")\n        port = vxlan_output.get(\"udpPort\")\n\n        # Check vxlan1 source interface and udp port\n        if src_intf != self.inputs.source_interface:\n            self.result.is_failure(f\"Source interface is not correct. Expected `{self.inputs.source_interface}` as source interface but found `{src_intf}` instead.\")\n        if port != self.inputs.udp_port:\n            self.result.is_failure(f\"UDP port is not correct. Expected `{self.inputs.udp_port}` as UDP port but found `{port}` instead.\")\n
"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlan1ConnSettings-attributes","title":"Inputs","text":"Name Type Description Default source_interface VxlanSrcIntf Source loopback interface of vxlan1 interface. - udp_port int UDP port used for vxlan1 interface. Field(ge=1024, le=65335)"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlan1Interface","title":"VerifyVxlan1Interface","text":"

Verifies if the Vxlan1 interface is configured and \u2018up/up\u2019.

Warning

The name of this test has been updated from \u2018VerifyVxlan\u2019 for better representation.

Expected Results
  • Success: The test will pass if the Vxlan1 interface is configured with line protocol status and interface status \u2018up\u2019.
  • Failure: The test will fail if the Vxlan1 interface line protocol status or interface status are not \u2018up\u2019.
  • Skipped: The test will be skipped if the Vxlan1 interface is not configured.
Examples
anta.tests.vxlan:\n  - VerifyVxlan1Interface:\n
Source code in anta/tests/vxlan.py
class VerifyVxlan1Interface(AntaTest):\n    \"\"\"Verifies if the Vxlan1 interface is configured and 'up/up'.\n\n    Warning\n    -------\n    The name of this test has been updated from 'VerifyVxlan' for better representation.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the Vxlan1 interface is configured with line protocol status and interface status 'up'.\n    * Failure: The test will fail if the Vxlan1 interface line protocol status or interface status are not 'up'.\n    * Skipped: The test will be skipped if the Vxlan1 interface is not configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.vxlan:\n      - VerifyVxlan1Interface:\n    ```\n    \"\"\"\n\n    name = \"VerifyVxlan1Interface\"\n    description = \"Verifies the Vxlan1 interface status.\"\n    categories: ClassVar[list[str]] = [\"vxlan\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show interfaces description\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyVxlan1Interface.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if \"Vxlan1\" not in command_output[\"interfaceDescriptions\"]:\n            self.result.is_skipped(\"Vxlan1 interface is not configured\")\n        elif (\n            command_output[\"interfaceDescriptions\"][\"Vxlan1\"][\"lineProtocolStatus\"] == \"up\"\n            and command_output[\"interfaceDescriptions\"][\"Vxlan1\"][\"interfaceStatus\"] == \"up\"\n        ):\n            self.result.is_success()\n        else:\n            self.result.is_failure(\n                f\"Vxlan1 interface is {command_output['interfaceDescriptions']['Vxlan1']['lineProtocolStatus']}\"\n                f\"/{command_output['interfaceDescriptions']['Vxlan1']['interfaceStatus']}\",\n            )\n
"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlanConfigSanity","title":"VerifyVxlanConfigSanity","text":"

Verifies that no issues are detected with the VXLAN configuration.

Expected Results
  • Success: The test will pass if no issues are detected with the VXLAN configuration.
  • Failure: The test will fail if issues are detected with the VXLAN configuration.
  • Skipped: The test will be skipped if VXLAN is not configured on the device.
Examples
anta.tests.vxlan:\n  - VerifyVxlanConfigSanity:\n
Source code in anta/tests/vxlan.py
class VerifyVxlanConfigSanity(AntaTest):\n    \"\"\"Verifies that no issues are detected with the VXLAN configuration.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if no issues are detected with the VXLAN configuration.\n    * Failure: The test will fail if issues are detected with the VXLAN configuration.\n    * Skipped: The test will be skipped if VXLAN is not configured on the device.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.vxlan:\n      - VerifyVxlanConfigSanity:\n    ```\n    \"\"\"\n\n    name = \"VerifyVxlanConfigSanity\"\n    description = \"Verifies there are no VXLAN config-sanity inconsistencies.\"\n    categories: ClassVar[list[str]] = [\"vxlan\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show vxlan config-sanity\", revision=1)]\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyVxlanConfigSanity.\"\"\"\n        command_output = self.instance_commands[0].json_output\n        if \"categories\" not in command_output or len(command_output[\"categories\"]) == 0:\n            self.result.is_skipped(\"VXLAN is not configured\")\n            return\n        failed_categories = {\n            category: content\n            for category, content in command_output[\"categories\"].items()\n            if category in [\"localVtep\", \"mlag\", \"pd\"] and content[\"allCheckPass\"] is not True\n        }\n        if len(failed_categories) > 0:\n            self.result.is_failure(f\"VXLAN config sanity check is not passing: {failed_categories}\")\n        else:\n            self.result.is_success()\n
"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlanVniBinding","title":"VerifyVxlanVniBinding","text":"

Verifies the VNI-VLAN bindings of the Vxlan1 interface.

Expected Results
  • Success: The test will pass if the VNI-VLAN bindings provided are properly configured.
  • Failure: The test will fail if any VNI lacks bindings or if any bindings are incorrect.
  • Skipped: The test will be skipped if the Vxlan1 interface is not configured.
Examples
anta.tests.vxlan:\n  - VerifyVxlanVniBinding:\n      bindings:\n        10010: 10\n        10020: 20\n
Source code in anta/tests/vxlan.py
class VerifyVxlanVniBinding(AntaTest):\n    \"\"\"Verifies the VNI-VLAN bindings of the Vxlan1 interface.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if the VNI-VLAN bindings provided are properly configured.\n    * Failure: The test will fail if any VNI lacks bindings or if any bindings are incorrect.\n    * Skipped: The test will be skipped if the Vxlan1 interface is not configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.vxlan:\n      - VerifyVxlanVniBinding:\n          bindings:\n            10010: 10\n            10020: 20\n    ```\n    \"\"\"\n\n    name = \"VerifyVxlanVniBinding\"\n    description = \"Verifies the VNI-VLAN bindings of the Vxlan1 interface.\"\n    categories: ClassVar[list[str]] = [\"vxlan\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show vxlan vni\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyVxlanVniBinding test.\"\"\"\n\n        bindings: dict[Vni, Vlan]\n        \"\"\"VNI to VLAN bindings to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyVxlanVniBinding.\"\"\"\n        self.result.is_success()\n\n        no_binding = []\n        wrong_binding = []\n\n        if (vxlan1 := get_value(self.instance_commands[0].json_output, \"vxlanIntfs.Vxlan1\")) is None:\n            self.result.is_skipped(\"Vxlan1 interface is not configured\")\n            return\n\n        for vni, vlan in self.inputs.bindings.items():\n            str_vni = str(vni)\n            if str_vni in vxlan1[\"vniBindings\"]:\n                retrieved_vlan = vxlan1[\"vniBindings\"][str_vni][\"vlan\"]\n            elif str_vni in vxlan1[\"vniBindingsToVrf\"]:\n                retrieved_vlan = vxlan1[\"vniBindingsToVrf\"][str_vni][\"vlan\"]\n            else:\n                no_binding.append(str_vni)\n                retrieved_vlan = None\n\n            if retrieved_vlan and vlan != retrieved_vlan:\n                wrong_binding.append({str_vni: retrieved_vlan})\n\n        if no_binding:\n            self.result.is_failure(f\"The following VNI(s) have no binding: {no_binding}\")\n\n        if wrong_binding:\n            self.result.is_failure(f\"The following VNI(s) have the wrong VLAN binding: {wrong_binding}\")\n
"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlanVniBinding-attributes","title":"Inputs","text":"Name Type Description Default bindings dict[Vni, Vlan] VNI to VLAN bindings to verify. -"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlanVtep","title":"VerifyVxlanVtep","text":"

Verifies the VTEP peers of the Vxlan1 interface.

Expected Results
  • Success: The test will pass if all provided VTEP peers are identified and matching.
  • Failure: The test will fail if any VTEP peer is missing or there are unexpected VTEP peers.
  • Skipped: The test will be skipped if the Vxlan1 interface is not configured.
Examples
anta.tests.vxlan:\n  - VerifyVxlanVtep:\n      vteps:\n        - 10.1.1.5\n        - 10.1.1.6\n
Source code in anta/tests/vxlan.py
class VerifyVxlanVtep(AntaTest):\n    \"\"\"Verifies the VTEP peers of the Vxlan1 interface.\n\n    Expected Results\n    ----------------\n    * Success: The test will pass if all provided VTEP peers are identified and matching.\n    * Failure: The test will fail if any VTEP peer is missing or there are unexpected VTEP peers.\n    * Skipped: The test will be skipped if the Vxlan1 interface is not configured.\n\n    Examples\n    --------\n    ```yaml\n    anta.tests.vxlan:\n      - VerifyVxlanVtep:\n          vteps:\n            - 10.1.1.5\n            - 10.1.1.6\n    ```\n    \"\"\"\n\n    name = \"VerifyVxlanVtep\"\n    description = \"Verifies the VTEP peers of the Vxlan1 interface\"\n    categories: ClassVar[list[str]] = [\"vxlan\"]\n    commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command=\"show vxlan vtep\", revision=1)]\n\n    class Input(AntaTest.Input):\n        \"\"\"Input model for the VerifyVxlanVtep test.\"\"\"\n\n        vteps: list[IPv4Address]\n        \"\"\"List of VTEP peers to verify.\"\"\"\n\n    @AntaTest.anta_test\n    def test(self) -> None:\n        \"\"\"Main test function for VerifyVxlanVtep.\"\"\"\n        self.result.is_success()\n\n        inputs_vteps = [str(input_vtep) for input_vtep in self.inputs.vteps]\n\n        if (vxlan1 := get_value(self.instance_commands[0].json_output, \"interfaces.Vxlan1\")) is None:\n            self.result.is_skipped(\"Vxlan1 interface is not configured\")\n            return\n\n        difference1 = set(inputs_vteps).difference(set(vxlan1[\"vteps\"]))\n        difference2 = set(vxlan1[\"vteps\"]).difference(set(inputs_vteps))\n\n        if difference1:\n            self.result.is_failure(f\"The following VTEP peer(s) are missing from the Vxlan1 interface: {sorted(difference1)}\")\n\n        if difference2:\n            self.result.is_failure(f\"Unexpected VTEP peer(s) on Vxlan1 interface: {sorted(difference2)}\")\n
"},{"location":"api/tests.vxlan/#anta.tests.vxlan.VerifyVxlanVtep-attributes","title":"Inputs","text":"Name Type Description Default vteps list[IPv4Address] List of VTEP peers to verify. -"},{"location":"api/types/","title":"Input Types","text":""},{"location":"api/types/#anta.custom_types","title":"anta.custom_types","text":"

Module that provides predefined types for AntaTest.Input instances.

"},{"location":"api/types/#anta.custom_types.AAAAuthMethod","title":"AAAAuthMethod module-attribute","text":"
AAAAuthMethod = Annotated[str, AfterValidator(aaa_group_prefix)]\n
"},{"location":"api/types/#anta.custom_types.Afi","title":"Afi module-attribute","text":"
Afi = Literal['ipv4', 'ipv6', 'vpn-ipv4', 'vpn-ipv6', 'evpn', 'rt-membership', 'path-selection', 'link-state']\n
"},{"location":"api/types/#anta.custom_types.BfdInterval","title":"BfdInterval module-attribute","text":"
BfdInterval = Annotated[int, Field(ge=50, le=60000)]\n
"},{"location":"api/types/#anta.custom_types.BfdMultiplier","title":"BfdMultiplier module-attribute","text":"
BfdMultiplier = Annotated[int, Field(ge=3, le=50)]\n
"},{"location":"api/types/#anta.custom_types.EcdsaKeySize","title":"EcdsaKeySize module-attribute","text":"
EcdsaKeySize = Literal[256, 384, 512]\n
"},{"location":"api/types/#anta.custom_types.EncryptionAlgorithm","title":"EncryptionAlgorithm module-attribute","text":"
EncryptionAlgorithm = Literal['RSA', 'ECDSA']\n
"},{"location":"api/types/#anta.custom_types.ErrDisableInterval","title":"ErrDisableInterval module-attribute","text":"
ErrDisableInterval = Annotated[int, Field(ge=30, le=86400)]\n
"},{"location":"api/types/#anta.custom_types.ErrDisableReasons","title":"ErrDisableReasons module-attribute","text":"
ErrDisableReasons = Literal['acl', 'arp-inspection', 'bpduguard', 'dot1x-session-replace', 'hitless-reload-down', 'lacp-rate-limit', 'link-flap', 'no-internal-vlan', 'portchannelguard', 'portsec', 'tapagg', 'uplink-failure-detection']\n
"},{"location":"api/types/#anta.custom_types.EthernetInterface","title":"EthernetInterface module-attribute","text":"
EthernetInterface = Annotated[str, Field(pattern='^Ethernet[0-9]+(\\\\/[0-9]+)*$'), BeforeValidator(interface_autocomplete), BeforeValidator(interface_case_sensitivity)]\n
"},{"location":"api/types/#anta.custom_types.Hostname","title":"Hostname module-attribute","text":"
Hostname = Annotated[str, Field(pattern=REGEXP_TYPE_HOSTNAME)]\n
"},{"location":"api/types/#anta.custom_types.Interface","title":"Interface module-attribute","text":"
Interface = Annotated[str, Field(pattern=REGEXP_TYPE_EOS_INTERFACE), BeforeValidator(interface_autocomplete), BeforeValidator(interface_case_sensitivity)]\n
"},{"location":"api/types/#anta.custom_types.MlagPriority","title":"MlagPriority module-attribute","text":"
MlagPriority = Annotated[int, Field(ge=1, le=32767)]\n
"},{"location":"api/types/#anta.custom_types.MultiProtocolCaps","title":"MultiProtocolCaps module-attribute","text":"
MultiProtocolCaps = Annotated[str, BeforeValidator(bgp_multiprotocol_capabilities_abbreviations)]\n
"},{"location":"api/types/#anta.custom_types.Percent","title":"Percent module-attribute","text":"
Percent = Annotated[float, Field(ge=0.0, le=100.0)]\n
"},{"location":"api/types/#anta.custom_types.Port","title":"Port module-attribute","text":"
Port = Annotated[int, Field(ge=1, le=65535)]\n
"},{"location":"api/types/#anta.custom_types.PositiveInteger","title":"PositiveInteger module-attribute","text":"
PositiveInteger = Annotated[int, Field(ge=0)]\n
"},{"location":"api/types/#anta.custom_types.REGEXP_BGP_IPV4_MPLS_LABELS","title":"REGEXP_BGP_IPV4_MPLS_LABELS module-attribute","text":"
REGEXP_BGP_IPV4_MPLS_LABELS = '\\\\b(ipv4[\\\\s\\\\-]?mpls[\\\\s\\\\-]?label(s)?)\\\\b'\n

Match IPv4 MPLS Labels.

"},{"location":"api/types/#anta.custom_types.REGEXP_BGP_L2VPN_AFI","title":"REGEXP_BGP_L2VPN_AFI module-attribute","text":"
REGEXP_BGP_L2VPN_AFI = '\\\\b(l2[\\\\s\\\\-]?vpn[\\\\s\\\\-]?evpn)\\\\b'\n

Match L2VPN EVPN AFI.

"},{"location":"api/types/#anta.custom_types.REGEXP_EOS_BLACKLIST_CMDS","title":"REGEXP_EOS_BLACKLIST_CMDS module-attribute","text":"
REGEXP_EOS_BLACKLIST_CMDS = ['^reload.*', '^conf\\\\w*\\\\s*(terminal|session)*', '^wr\\\\w*\\\\s*\\\\w+']\n

List of regular expressions to blacklist from eos commands.

"},{"location":"api/types/#anta.custom_types.REGEXP_INTERFACE_ID","title":"REGEXP_INTERFACE_ID module-attribute","text":"
REGEXP_INTERFACE_ID = '\\\\d+(\\\\/\\\\d+)*(\\\\.\\\\d+)?'\n

Match Interface ID lilke 1/1.1.

"},{"location":"api/types/#anta.custom_types.REGEXP_PATH_MARKERS","title":"REGEXP_PATH_MARKERS module-attribute","text":"
REGEXP_PATH_MARKERS = '[\\\\\\\\\\\\/\\\\s]'\n

Match directory path from string.

"},{"location":"api/types/#anta.custom_types.REGEXP_TYPE_EOS_INTERFACE","title":"REGEXP_TYPE_EOS_INTERFACE module-attribute","text":"
REGEXP_TYPE_EOS_INTERFACE = '^(Dps|Ethernet|Fabric|Loopback|Management|Port-Channel|Tunnel|Vlan|Vxlan)[0-9]+(\\\\/[0-9]+)*(\\\\.[0-9]+)?$'\n

Match EOS interface types like Ethernet1/1, Vlan1, Loopback1, etc.

"},{"location":"api/types/#anta.custom_types.REGEXP_TYPE_HOSTNAME","title":"REGEXP_TYPE_HOSTNAME module-attribute","text":"
REGEXP_TYPE_HOSTNAME = '^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\\\-]*[a-zA-Z0-9])\\\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\\\-]*[A-Za-z0-9])$'\n

Match hostname like my-hostname, my-hostname-1, my-hostname-1-2.

"},{"location":"api/types/#anta.custom_types.REGEXP_TYPE_VXLAN_SRC_INTERFACE","title":"REGEXP_TYPE_VXLAN_SRC_INTERFACE module-attribute","text":"
REGEXP_TYPE_VXLAN_SRC_INTERFACE = '^(Loopback)([0-9]|[1-9][0-9]{1,2}|[1-7][0-9]{3}|8[01][0-9]{2}|819[01])$'\n

Match Vxlan source interface like Loopback10.

"},{"location":"api/types/#anta.custom_types.REGEX_BGP_IPV4_MPLS_VPN","title":"REGEX_BGP_IPV4_MPLS_VPN module-attribute","text":"
REGEX_BGP_IPV4_MPLS_VPN = '\\\\b(ipv4[\\\\s\\\\-]?mpls[\\\\s\\\\-]?vpn)\\\\b'\n

Match IPv4 MPLS VPN.

"},{"location":"api/types/#anta.custom_types.REGEX_BGP_IPV4_UNICAST","title":"REGEX_BGP_IPV4_UNICAST module-attribute","text":"
REGEX_BGP_IPV4_UNICAST = '\\\\b(ipv4[\\\\s\\\\-]?uni[\\\\s\\\\-]?cast)\\\\b'\n

Match IPv4 Unicast.

"},{"location":"api/types/#anta.custom_types.RegexString","title":"RegexString module-attribute","text":"
RegexString = Annotated[str, AfterValidator(validate_regex)]\n
"},{"location":"api/types/#anta.custom_types.Revision","title":"Revision module-attribute","text":"
Revision = Annotated[int, Field(ge=1, le=99)]\n
"},{"location":"api/types/#anta.custom_types.RsaKeySize","title":"RsaKeySize module-attribute","text":"
RsaKeySize = Literal[2048, 3072, 4096]\n
"},{"location":"api/types/#anta.custom_types.Safi","title":"Safi module-attribute","text":"
Safi = Literal['unicast', 'multicast', 'labeled-unicast', 'sr-te']\n
"},{"location":"api/types/#anta.custom_types.TestStatus","title":"TestStatus module-attribute","text":"
TestStatus = Literal['unset', 'success', 'failure', 'error', 'skipped']\n
"},{"location":"api/types/#anta.custom_types.Vlan","title":"Vlan module-attribute","text":"
Vlan = Annotated[int, Field(ge=0, le=4094)]\n
"},{"location":"api/types/#anta.custom_types.Vni","title":"Vni module-attribute","text":"
Vni = Annotated[int, Field(ge=1, le=16777215)]\n
"},{"location":"api/types/#anta.custom_types.VxlanSrcIntf","title":"VxlanSrcIntf module-attribute","text":"
VxlanSrcIntf = Annotated[str, Field(pattern=REGEXP_TYPE_VXLAN_SRC_INTERFACE), BeforeValidator(interface_autocomplete), BeforeValidator(interface_case_sensitivity)]\n
"},{"location":"api/types/#anta.custom_types.aaa_group_prefix","title":"aaa_group_prefix","text":"
aaa_group_prefix(v: str) -> str\n

Prefix the AAA method with \u2018group\u2019 if it is known.

Source code in anta/custom_types.py
def aaa_group_prefix(v: str) -> str:\n    \"\"\"Prefix the AAA method with 'group' if it is known.\"\"\"\n    built_in_methods = [\"local\", \"none\", \"logging\"]\n    return f\"group {v}\" if v not in built_in_methods and not v.startswith(\"group \") else v\n
"},{"location":"api/types/#anta.custom_types.bgp_multiprotocol_capabilities_abbreviations","title":"bgp_multiprotocol_capabilities_abbreviations","text":"
bgp_multiprotocol_capabilities_abbreviations(value: str) -> str\n

Abbreviations for different BGP multiprotocol capabilities.

Examples
- IPv4 Unicast\n- L2vpnEVPN\n- ipv4 MPLS Labels\n- ipv4Mplsvpn\n
Source code in anta/custom_types.py
def bgp_multiprotocol_capabilities_abbreviations(value: str) -> str:\n    \"\"\"Abbreviations for different BGP multiprotocol capabilities.\n\n    Examples\n    --------\n        - IPv4 Unicast\n        - L2vpnEVPN\n        - ipv4 MPLS Labels\n        - ipv4Mplsvpn\n\n    \"\"\"\n    patterns = {\n        REGEXP_BGP_L2VPN_AFI: \"l2VpnEvpn\",\n        REGEXP_BGP_IPV4_MPLS_LABELS: \"ipv4MplsLabels\",\n        REGEX_BGP_IPV4_MPLS_VPN: \"ipv4MplsVpn\",\n        REGEX_BGP_IPV4_UNICAST: \"ipv4Unicast\",\n    }\n\n    for pattern, replacement in patterns.items():\n        match = re.search(pattern, value, re.IGNORECASE)\n        if match:\n            return replacement\n\n    return value\n
"},{"location":"api/types/#anta.custom_types.interface_autocomplete","title":"interface_autocomplete","text":"
interface_autocomplete(v: str) -> str\n

Allow the user to only provide the beginning of an interface name.

Supported alias: - et, eth will be changed to Ethernet - po will be changed to Port-Channel - lo will be changed to Loopback

Source code in anta/custom_types.py
def interface_autocomplete(v: str) -> str:\n    \"\"\"Allow the user to only provide the beginning of an interface name.\n\n    Supported alias:\n         - `et`, `eth` will be changed to `Ethernet`\n         - `po` will be changed to `Port-Channel`\n    - `lo` will be changed to `Loopback`\n    \"\"\"\n    intf_id_re = re.compile(REGEXP_INTERFACE_ID)\n    m = intf_id_re.search(v)\n    if m is None:\n        msg = f\"Could not parse interface ID in interface '{v}'\"\n        raise ValueError(msg)\n    intf_id = m[0]\n\n    alias_map = {\"et\": \"Ethernet\", \"eth\": \"Ethernet\", \"po\": \"Port-Channel\", \"lo\": \"Loopback\"}\n\n    return next((f\"{full_name}{intf_id}\" for alias, full_name in alias_map.items() if v.lower().startswith(alias)), v)\n
"},{"location":"api/types/#anta.custom_types.interface_case_sensitivity","title":"interface_case_sensitivity","text":"
interface_case_sensitivity(v: str) -> str\n

Reformat interface name to match expected case sensitivity.

Examples
 - ethernet -> Ethernet\n - vlan -> Vlan\n - loopback -> Loopback\n
Source code in anta/custom_types.py
def interface_case_sensitivity(v: str) -> str:\n    \"\"\"Reformat interface name to match expected case sensitivity.\n\n    Examples\n    --------\n         - ethernet -> Ethernet\n         - vlan -> Vlan\n         - loopback -> Loopback\n\n    \"\"\"\n    if isinstance(v, str) and v != \"\" and not v[0].isupper():\n        return f\"{v[0].upper()}{v[1:]}\"\n    return v\n
"},{"location":"api/types/#anta.custom_types.validate_regex","title":"validate_regex","text":"
validate_regex(value: str) -> str\n

Validate that the input value is a valid regex format.

Source code in anta/custom_types.py
def validate_regex(value: str) -> str:\n    \"\"\"Validate that the input value is a valid regex format.\"\"\"\n    try:\n        re.compile(value)\n    except re.error as e:\n        msg = f\"Invalid regex: {e}\"\n        raise ValueError(msg) from e\n    return value\n
"},{"location":"cli/check/","title":"Check","text":""},{"location":"cli/check/#anta-check-commands","title":"ANTA check commands","text":"

The ANTA check command allow to execute some checks on the ANTA input files. Only checking the catalog is currently supported.

anta check --help\nUsage: anta check [OPTIONS] COMMAND [ARGS]...\n\n  Check commands for building ANTA\n\nOptions:\n  --help  Show this message and exit.\n\nCommands:\n  catalog  Check that the catalog is valid\n
"},{"location":"cli/check/#checking-the-catalog","title":"Checking the catalog","text":"
Usage: anta check catalog [OPTIONS]\n\n  Check that the catalog is valid.\n\nOptions:\n  -c, --catalog FILE            Path to the test catalog file  [env var:\n                                ANTA_CATALOG; required]\n  --catalog-format [yaml|json]  Format of the catalog file, either 'yaml' or\n                                'json'  [env var: ANTA_CATALOG_FORMAT]\n  --help                        Show this message and exit.\n
"},{"location":"cli/debug/","title":"Helpers","text":""},{"location":"cli/debug/#anta-debug-commands","title":"ANTA debug commands","text":"

The ANTA CLI includes a set of debugging tools, making it easier to build and test ANTA content. This functionality is accessed via the debug subcommand and offers the following options:

  • Executing a command on a device from your inventory and retrieving the result.
  • Running a templated command on a device from your inventory and retrieving the result.

These tools are especially helpful in building the tests, as they give a visual access to the output received from the eAPI. They also facilitate the extraction of output content for use in unit tests, as described in our contribution guide.

Warning

The debug tools require a device from your inventory. Thus, you MUST use a valid ANTA Inventory.

"},{"location":"cli/debug/#executing-an-eos-command","title":"Executing an EOS command","text":"

You can use the run-cmd entrypoint to run a command, which includes the following options:

"},{"location":"cli/debug/#command-overview","title":"Command overview","text":"
Usage: anta debug run-cmd [OPTIONS]\n\n  Run arbitrary command to an ANTA device.\n\nOptions:\n  -u, --username TEXT       Username to connect to EOS  [env var:\n                            ANTA_USERNAME; required]\n  -p, --password TEXT       Password to connect to EOS that must be provided.\n                            It can be prompted using '--prompt' option.  [env\n                            var: ANTA_PASSWORD]\n  --enable-password TEXT    Password to access EOS Privileged EXEC mode. It\n                            can be prompted using '--prompt' option. Requires\n                            '--enable' option.  [env var:\n                            ANTA_ENABLE_PASSWORD]\n  --enable                  Some commands may require EOS Privileged EXEC\n                            mode. This option tries to access this mode before\n                            sending a command to the device.  [env var:\n                            ANTA_ENABLE]\n  -P, --prompt              Prompt for passwords if they are not provided.\n                            [env var: ANTA_PROMPT]\n  --timeout FLOAT           Global API timeout. This value will be used for\n                            all devices.  [env var: ANTA_TIMEOUT; default:\n                            30.0]\n  --insecure                Disable SSH Host Key validation.  [env var:\n                            ANTA_INSECURE]\n  --disable-cache           Disable cache globally.  [env var:\n                            ANTA_DISABLE_CACHE]\n  -i, --inventory FILE      Path to the inventory YAML file.  [env var:\n                            ANTA_INVENTORY; required]\n  --tags TEXT               List of tags using comma as separator:\n                            tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  --ofmt [json|text]        EOS eAPI format to use. can be text or json\n  -v, --version [1|latest]  EOS eAPI version\n  -r, --revision INTEGER    eAPI command revision\n  -d, --device TEXT         Device from inventory to use  [required]\n  -c, --command TEXT        Command to run  [required]\n  --help                    Show this message and exit.\n

username, password, enable-password, enable, timeout and insecure values are the same for all devices

"},{"location":"cli/debug/#example","title":"Example","text":"

This example illustrates how to run the show interfaces description command with a JSON format (default):

anta debug run-cmd --command \"show interfaces description\" --device DC1-SPINE1\nRun command show interfaces description on DC1-SPINE1\n{\n    'interfaceDescriptions': {\n        'Ethernet1': {'lineProtocolStatus': 'up', 'description': 'P2P_LINK_TO_DC1-LEAF1A_Ethernet1', 'interfaceStatus': 'up'},\n        'Ethernet2': {'lineProtocolStatus': 'up', 'description': 'P2P_LINK_TO_DC1-LEAF1B_Ethernet1', 'interfaceStatus': 'up'},\n        'Ethernet3': {'lineProtocolStatus': 'up', 'description': 'P2P_LINK_TO_DC1-BL1_Ethernet1', 'interfaceStatus': 'up'},\n        'Ethernet4': {'lineProtocolStatus': 'up', 'description': 'P2P_LINK_TO_DC1-BL2_Ethernet1', 'interfaceStatus': 'up'},\n        'Loopback0': {'lineProtocolStatus': 'up', 'description': 'EVPN_Overlay_Peering', 'interfaceStatus': 'up'},\n        'Management0': {'lineProtocolStatus': 'up', 'description': 'oob_management', 'interfaceStatus': 'up'}\n    }\n}\n
"},{"location":"cli/debug/#executing-an-eos-command-using-templates","title":"Executing an EOS command using templates","text":"

The run-template entrypoint allows the user to provide an f-string templated command. It is followed by a list of arguments (key-value pairs) that build a dictionary used as template parameters.

"},{"location":"cli/debug/#command-overview_1","title":"Command overview","text":"
Usage: anta debug run-template [OPTIONS] PARAMS...\n\n  Run arbitrary templated command to an ANTA device.\n\n  Takes a list of arguments (keys followed by a value) to build a dictionary\n  used as template parameters.\n\n  Example: ------- anta debug run-template -d leaf1a -t 'show vlan {vlan_id}'\n  vlan_id 1\n\nOptions:\n  -u, --username TEXT       Username to connect to EOS  [env var:\n                            ANTA_USERNAME; required]\n  -p, --password TEXT       Password to connect to EOS that must be provided.\n                            It can be prompted using '--prompt' option.  [env\n                            var: ANTA_PASSWORD]\n  --enable-password TEXT    Password to access EOS Privileged EXEC mode. It\n                            can be prompted using '--prompt' option. Requires\n                            '--enable' option.  [env var:\n                            ANTA_ENABLE_PASSWORD]\n  --enable                  Some commands may require EOS Privileged EXEC\n                            mode. This option tries to access this mode before\n                            sending a command to the device.  [env var:\n                            ANTA_ENABLE]\n  -P, --prompt              Prompt for passwords if they are not provided.\n                            [env var: ANTA_PROMPT]\n  --timeout FLOAT           Global API timeout. This value will be used for\n                            all devices.  [env var: ANTA_TIMEOUT; default:\n                            30.0]\n  --insecure                Disable SSH Host Key validation.  [env var:\n                            ANTA_INSECURE]\n  --disable-cache           Disable cache globally.  [env var:\n                            ANTA_DISABLE_CACHE]\n  -i, --inventory FILE      Path to the inventory YAML file.  [env var:\n                            ANTA_INVENTORY; required]\n  --tags TEXT               List of tags using comma as separator:\n                            tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  --ofmt [json|text]        EOS eAPI format to use. can be text or json\n  -v, --version [1|latest]  EOS eAPI version\n  -r, --revision INTEGER    eAPI command revision\n  -d, --device TEXT         Device from inventory to use  [required]\n  -t, --template TEXT       Command template to run. E.g. 'show vlan\n                            {vlan_id}'  [required]\n  --help                    Show this message and exit.\n

username, password, enable-password, enable, timeout and insecure values are the same for all devices

"},{"location":"cli/debug/#example_1","title":"Example","text":"

This example uses the show vlan {vlan_id} command in a JSON format:

anta debug run-template --template \"show vlan {vlan_id}\" vlan_id 10 --device DC1-LEAF1A\nRun templated command 'show vlan {vlan_id}' with {'vlan_id': '10'} on DC1-LEAF1A\n{\n    'vlans': {\n        '10': {\n            'name': 'VRFPROD_VLAN10',\n            'dynamic': False,\n            'status': 'active',\n            'interfaces': {\n                'Cpu': {'privatePromoted': False, 'blocked': None},\n                'Port-Channel11': {'privatePromoted': False, 'blocked': None},\n                'Vxlan1': {'privatePromoted': False, 'blocked': None}\n            }\n        }\n    },\n    'sourceDetail': ''\n}\n

Warning

If multiple arguments of the same key are provided, only the last argument value will be kept in the template parameters.

"},{"location":"cli/debug/#example-of-multiple-arguments","title":"Example of multiple arguments","text":"
anta -log DEBUG debug run-template --template \"ping {dst} source {src}\" dst \"8.8.8.8\" src Loopback0 --device DC1-SPINE1 \u00a0 \u00a0\n> {'dst': '8.8.8.8', 'src': 'Loopback0'}\n\nanta -log DEBUG debug run-template --template \"ping {dst} source {src}\" dst \"8.8.8.8\" src Loopback0 dst \"1.1.1.1\" src Loopback1 --device DC1-SPINE1 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0\n> {'dst': '1.1.1.1', 'src': 'Loopback1'}\n# Notice how `src` and `dst` keep only the latest value\n
"},{"location":"cli/exec/","title":"Execute commands","text":""},{"location":"cli/exec/#executing-commands-on-devices","title":"Executing Commands on Devices","text":"

ANTA CLI provides a set of entrypoints to facilitate remote command execution on EOS devices.

"},{"location":"cli/exec/#exec-command-overview","title":"EXEC Command overview","text":"
anta exec --help\nUsage: anta exec [OPTIONS] COMMAND [ARGS]...\n\n  Execute commands to inventory devices\n\nOptions:\n  --help  Show this message and exit.\n\nCommands:\n  clear-counters        Clear counter statistics on EOS devices\n  collect-tech-support  Collect scheduled tech-support from EOS devices\n  snapshot              Collect commands output from devices in inventory\n
"},{"location":"cli/exec/#clear-interfaces-counters","title":"Clear interfaces counters","text":"

This command clears interface counters on EOS devices specified in your inventory.

"},{"location":"cli/exec/#command-overview","title":"Command overview","text":"
Usage: anta exec clear-counters [OPTIONS]\n\n  Clear counter statistics on EOS devices.\n\nOptions:\n  -u, --username TEXT     Username to connect to EOS  [env var: ANTA_USERNAME;\n                          required]\n  -p, --password TEXT     Password to connect to EOS that must be provided. It\n                          can be prompted using '--prompt' option.  [env var:\n                          ANTA_PASSWORD]\n  --enable-password TEXT  Password to access EOS Privileged EXEC mode. It can\n                          be prompted using '--prompt' option. Requires '--\n                          enable' option.  [env var: ANTA_ENABLE_PASSWORD]\n  --enable                Some commands may require EOS Privileged EXEC mode.\n                          This option tries to access this mode before sending\n                          a command to the device.  [env var: ANTA_ENABLE]\n  -P, --prompt            Prompt for passwords if they are not provided.  [env\n                          var: ANTA_PROMPT]\n  --timeout FLOAT         Global API timeout. This value will be used for all\n                          devices.  [env var: ANTA_TIMEOUT; default: 30.0]\n  --insecure              Disable SSH Host Key validation.  [env var:\n                          ANTA_INSECURE]\n  --disable-cache         Disable cache globally.  [env var:\n                          ANTA_DISABLE_CACHE]\n  -i, --inventory FILE    Path to the inventory YAML file.  [env var:\n                          ANTA_INVENTORY; required]\n  --tags TEXT             List of tags using comma as separator:\n                          tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  --help                  Show this message and exit.\n

username, password, enable-password, enable, timeout and insecure values are the same for all devices

"},{"location":"cli/exec/#example","title":"Example","text":"
anta exec clear-counters --tags SPINE\n[20:19:13] INFO     Connecting to devices...                                                                                                                         utils.py:43\n           INFO     Clearing counters on remote devices...                                                                                                           utils.py:46\n           INFO     Cleared counters on DC1-SPINE2 (cEOSLab)                                                                                                         utils.py:41\n           INFO     Cleared counters on DC2-SPINE1 (cEOSLab)                                                                                                         utils.py:41\n           INFO     Cleared counters on DC1-SPINE1 (cEOSLab)                                                                                                         utils.py:41\n           INFO     Cleared counters on DC2-SPINE2 (cEOSLab)\n
"},{"location":"cli/exec/#collect-a-set-of-commands","title":"Collect a set of commands","text":"

This command collects all the commands specified in a commands-list file, which can be in either json or text format.

"},{"location":"cli/exec/#command-overview_1","title":"Command overview","text":"
Usage: anta exec snapshot [OPTIONS]\n\n  Collect commands output from devices in inventory.\n\nOptions:\n  -u, --username TEXT       Username to connect to EOS  [env var:\n                            ANTA_USERNAME; required]\n  -p, --password TEXT       Password to connect to EOS that must be provided.\n                            It can be prompted using '--prompt' option.  [env\n                            var: ANTA_PASSWORD]\n  --enable-password TEXT    Password to access EOS Privileged EXEC mode. It\n                            can be prompted using '--prompt' option. Requires\n                            '--enable' option.  [env var:\n                            ANTA_ENABLE_PASSWORD]\n  --enable                  Some commands may require EOS Privileged EXEC\n                            mode. This option tries to access this mode before\n                            sending a command to the device.  [env var:\n                            ANTA_ENABLE]\n  -P, --prompt              Prompt for passwords if they are not provided.\n                            [env var: ANTA_PROMPT]\n  --timeout FLOAT           Global API timeout. This value will be used for\n                            all devices.  [env var: ANTA_TIMEOUT; default:\n                            30.0]\n  --insecure                Disable SSH Host Key validation.  [env var:\n                            ANTA_INSECURE]\n  --disable-cache           Disable cache globally.  [env var:\n                            ANTA_DISABLE_CACHE]\n  -i, --inventory FILE      Path to the inventory YAML file.  [env var:\n                            ANTA_INVENTORY; required]\n  --tags TEXT               List of tags using comma as separator:\n                            tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  -c, --commands-list FILE  File with list of commands to collect  [env var:\n                            ANTA_EXEC_SNAPSHOT_COMMANDS_LIST; required]\n  -o, --output DIRECTORY    Directory to save commands output.  [env var:\n                            ANTA_EXEC_SNAPSHOT_OUTPUT; default:\n                            anta_snapshot_2024-04-09_15_56_19]\n  --help                    Show this message and exit.\n

username, password, enable-password, enable, timeout and insecure values are the same for all devices

The commands-list file should follow this structure:

---\njson_format:\n  - show version\ntext_format:\n  - show bfd peers\n
"},{"location":"cli/exec/#example_1","title":"Example","text":"
anta exec snapshot --tags SPINE --commands-list ./commands.yaml --output ./\n[20:25:15] INFO     Connecting to devices...                                                                                                                         utils.py:78\n           INFO     Collecting commands from remote devices                                                                                                          utils.py:81\n           INFO     Collected command 'show version' from device DC2-SPINE1 (cEOSLab)                                                                                utils.py:76\n           INFO     Collected command 'show version' from device DC2-SPINE2 (cEOSLab)                                                                                utils.py:76\n           INFO     Collected command 'show version' from device DC1-SPINE1 (cEOSLab)                                                                                utils.py:76\n           INFO     Collected command 'show version' from device DC1-SPINE2 (cEOSLab)                                                                                utils.py:76\n[20:25:16] INFO     Collected command 'show bfd peers' from device DC2-SPINE2 (cEOSLab)                                                                              utils.py:76\n           INFO     Collected command 'show bfd peers' from device DC2-SPINE1 (cEOSLab)                                                                              utils.py:76\n           INFO     Collected command 'show bfd peers' from device DC1-SPINE1 (cEOSLab)                                                                              utils.py:76\n           INFO     Collected command 'show bfd peers' from device DC1-SPINE2 (cEOSLab)\n

The results of the executed commands will be stored in the output directory specified during command execution:

tree _2023-07-14_20_25_15\n_2023-07-14_20_25_15\n\u251c\u2500\u2500 DC1-SPINE1\n\u2502\u00a0\u00a0 \u251c\u2500\u2500 json\n\u2502\u00a0\u00a0 \u2502\u00a0\u00a0 \u2514\u2500\u2500 show version.json\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 text\n\u2502\u00a0\u00a0     \u2514\u2500\u2500 show bfd peers.log\n\u251c\u2500\u2500 DC1-SPINE2\n\u2502\u00a0\u00a0 \u251c\u2500\u2500 json\n\u2502\u00a0\u00a0 \u2502\u00a0\u00a0 \u2514\u2500\u2500 show version.json\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 text\n\u2502\u00a0\u00a0     \u2514\u2500\u2500 show bfd peers.log\n\u251c\u2500\u2500 DC2-SPINE1\n\u2502\u00a0\u00a0 \u251c\u2500\u2500 json\n\u2502\u00a0\u00a0 \u2502\u00a0\u00a0 \u2514\u2500\u2500 show version.json\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 text\n\u2502\u00a0\u00a0     \u2514\u2500\u2500 show bfd peers.log\n\u2514\u2500\u2500 DC2-SPINE2\n    \u251c\u2500\u2500 json\n    \u2502\u00a0\u00a0 \u2514\u2500\u2500 show version.json\n    \u2514\u2500\u2500 text\n        \u2514\u2500\u2500 show bfd peers.log\n\n12 directories, 8 files\n
"},{"location":"cli/exec/#get-scheduled-tech-support","title":"Get Scheduled tech-support","text":"

EOS offers a feature that automatically creates a tech-support archive every hour by default. These archives are stored under /mnt/flash/schedule/tech-support.

leaf1#show schedule summary\nMaximum concurrent jobs  1\nPrepend host name to logfile: Yes\nName                 At Time       Last        Interval       Timeout        Max        Max     Logfile Location                  Status\n                                   Time         (mins)        (mins)         Log        Logs\n                                                                            Files       Size\n----------------- ------------- ----------- -------------- ------------- ----------- ---------- --------------------------------- ------\ntech-support           now         08:37          60            30           100         -      flash:schedule/tech-support/      Success\n\n\nleaf1#bash ls /mnt/flash/schedule/tech-support\nleaf1_tech-support_2023-03-09.1337.log.gz  leaf1_tech-support_2023-03-10.0837.log.gz  leaf1_tech-support_2023-03-11.0337.log.gz\n

For Network Readiness for Use (NRFU) tests and to keep a comprehensive report of the system state before going live, ANTA provides a command-line interface that efficiently retrieves these files.

"},{"location":"cli/exec/#command-overview_2","title":"Command overview","text":"
Usage: anta exec collect-tech-support [OPTIONS]\n\n  Collect scheduled tech-support from EOS devices.\n\nOptions:\n  -u, --username TEXT     Username to connect to EOS  [env var: ANTA_USERNAME;\n                          required]\n  -p, --password TEXT     Password to connect to EOS that must be provided. It\n                          can be prompted using '--prompt' option.  [env var:\n                          ANTA_PASSWORD]\n  --enable-password TEXT  Password to access EOS Privileged EXEC mode. It can\n                          be prompted using '--prompt' option. Requires '--\n                          enable' option.  [env var: ANTA_ENABLE_PASSWORD]\n  --enable                Some commands may require EOS Privileged EXEC mode.\n                          This option tries to access this mode before sending\n                          a command to the device.  [env var: ANTA_ENABLE]\n  -P, --prompt            Prompt for passwords if they are not provided.  [env\n                          var: ANTA_PROMPT]\n  --timeout FLOAT         Global API timeout. This value will be used for all\n                          devices.  [env var: ANTA_TIMEOUT; default: 30.0]\n  --insecure              Disable SSH Host Key validation.  [env var:\n                          ANTA_INSECURE]\n  --disable-cache         Disable cache globally.  [env var:\n                          ANTA_DISABLE_CACHE]\n  -i, --inventory FILE    Path to the inventory YAML file.  [env var:\n                          ANTA_INVENTORY; required]\n  --tags TEXT             List of tags using comma as separator:\n                          tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  -o, --output PATH       Path for test catalog  [default: ./tech-support]\n  --latest INTEGER        Number of scheduled show-tech to retrieve\n  --configure             Ensure devices have 'aaa authorization exec default\n                          local' configured (required for SCP on EOS). THIS\n                          WILL CHANGE THE CONFIGURATION OF YOUR NETWORK.\n  --help                  Show this message and exit.\n

username, password, enable-password, enable, timeout and insecure values are the same for all devices

When executed, this command fetches tech-support files and downloads them locally into a device-specific subfolder within the designated folder. You can specify the output folder with the --output option.

ANTA uses SCP to download files from devices and will not trust unknown SSH hosts by default. Add the SSH public keys of your devices to your known_hosts file or use the anta --insecure option to ignore SSH host keys validation.

The configuration aaa authorization exec default must be present on devices to be able to use SCP. ANTA can automatically configure aaa authorization exec default local using the anta exec collect-tech-support --configure option. If you require specific AAA configuration for aaa authorization exec default, like aaa authorization exec default none or aaa authorization exec default group tacacs+, you will need to configure it manually.

The --latest option allows retrieval of a specific number of the most recent tech-support files.

Warning

By default all the tech-support files present on the devices are retrieved.

"},{"location":"cli/exec/#example_2","title":"Example","text":"
anta --insecure exec collect-tech-support\n[15:27:19] INFO     Connecting to devices...\nINFO     Copying '/mnt/flash/schedule/tech-support/spine1_tech-support_2023-06-09.1315.log.gz' from device spine1 to 'tech-support/spine1' locally\nINFO     Copying '/mnt/flash/schedule/tech-support/leaf3_tech-support_2023-06-09.1315.log.gz' from device leaf3 to 'tech-support/leaf3' locally\nINFO     Copying '/mnt/flash/schedule/tech-support/leaf1_tech-support_2023-06-09.1315.log.gz' from device leaf1 to 'tech-support/leaf1' locally\nINFO     Copying '/mnt/flash/schedule/tech-support/leaf2_tech-support_2023-06-09.1315.log.gz' from device leaf2 to 'tech-support/leaf2' locally\nINFO     Copying '/mnt/flash/schedule/tech-support/spine2_tech-support_2023-06-09.1315.log.gz' from device spine2 to 'tech-support/spine2' locally\nINFO     Copying '/mnt/flash/schedule/tech-support/leaf4_tech-support_2023-06-09.1315.log.gz' from device leaf4 to 'tech-support/leaf4' locally\nINFO     Collected 1 scheduled tech-support from leaf2\nINFO     Collected 1 scheduled tech-support from spine2\nINFO     Collected 1 scheduled tech-support from leaf3\nINFO     Collected 1 scheduled tech-support from spine1\nINFO     Collected 1 scheduled tech-support from leaf1\nINFO     Collected 1 scheduled tech-support from leaf4\n

The output folder structure is as follows:

tree tech-support/\ntech-support/\n\u251c\u2500\u2500 leaf1\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 leaf1_tech-support_2023-06-09.1315.log.gz\n\u251c\u2500\u2500 leaf2\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 leaf2_tech-support_2023-06-09.1315.log.gz\n\u251c\u2500\u2500 leaf3\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 leaf3_tech-support_2023-06-09.1315.log.gz\n\u251c\u2500\u2500 leaf4\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 leaf4_tech-support_2023-06-09.1315.log.gz\n\u251c\u2500\u2500 spine1\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 spine1_tech-support_2023-06-09.1315.log.gz\n\u2514\u2500\u2500 spine2\n    \u2514\u2500\u2500 spine2_tech-support_2023-06-09.1315.log.gz\n\n6 directories, 6 files\n

Each device has its own subdirectory containing the collected tech-support files.

"},{"location":"cli/get-inventory-information/","title":"Get Inventory Information","text":""},{"location":"cli/get-inventory-information/#retrieving-inventory-information","title":"Retrieving Inventory Information","text":"

The ANTA CLI offers multiple entrypoints to access data from your local inventory.

"},{"location":"cli/get-inventory-information/#inventory-used-of-examples","title":"Inventory used of examples","text":"

Let\u2019s consider the following inventory:

---\nanta_inventory:\n  hosts:\n    - host: 172.20.20.101\n      name: DC1-SPINE1\n      tags: [\"SPINE\", \"DC1\"]\n\n    - host: 172.20.20.102\n      name: DC1-SPINE2\n      tags: [\"SPINE\", \"DC1\"]\n\n    - host: 172.20.20.111\n      name: DC1-LEAF1A\n      tags: [\"LEAF\", \"DC1\"]\n\n    - host: 172.20.20.112\n      name: DC1-LEAF1B\n      tags: [\"LEAF\", \"DC1\"]\n\n    - host: 172.20.20.121\n      name: DC1-BL1\n      tags: [\"BL\", \"DC1\"]\n\n    - host: 172.20.20.122\n      name: DC1-BL2\n      tags: [\"BL\", \"DC1\"]\n\n    - host: 172.20.20.201\n      name: DC2-SPINE1\n      tags: [\"SPINE\", \"DC2\"]\n\n    - host: 172.20.20.202\n      name: DC2-SPINE2\n      tags: [\"SPINE\", \"DC2\"]\n\n    - host: 172.20.20.211\n      name: DC2-LEAF1A\n      tags: [\"LEAF\", \"DC2\"]\n\n    - host: 172.20.20.212\n      name: DC2-LEAF1B\n      tags: [\"LEAF\", \"DC2\"]\n\n    - host: 172.20.20.221\n      name: DC2-BL1\n      tags: [\"BL\", \"DC2\"]\n\n    - host: 172.20.20.222\n      name: DC2-BL2\n      tags: [\"BL\", \"DC2\"]\n
"},{"location":"cli/get-inventory-information/#obtaining-all-configured-tags","title":"Obtaining all configured tags","text":"

As most of ANTA\u2019s commands accommodate tag filtering, this particular command is useful for enumerating all tags configured in the inventory. Running the anta get tags command will return a list of all tags that have been configured in the inventory.

"},{"location":"cli/get-inventory-information/#command-overview","title":"Command overview","text":"
Usage: anta get tags [OPTIONS]\n\n  Get list of configured tags in user inventory.\n\nOptions:\n  -u, --username TEXT     Username to connect to EOS  [env var: ANTA_USERNAME;\n                          required]\n  -p, --password TEXT     Password to connect to EOS that must be provided. It\n                          can be prompted using '--prompt' option.  [env var:\n                          ANTA_PASSWORD]\n  --enable-password TEXT  Password to access EOS Privileged EXEC mode. It can\n                          be prompted using '--prompt' option. Requires '--\n                          enable' option.  [env var: ANTA_ENABLE_PASSWORD]\n  --enable                Some commands may require EOS Privileged EXEC mode.\n                          This option tries to access this mode before sending\n                          a command to the device.  [env var: ANTA_ENABLE]\n  -P, --prompt            Prompt for passwords if they are not provided.  [env\n                          var: ANTA_PROMPT]\n  --timeout FLOAT         Global API timeout. This value will be used for all\n                          devices.  [env var: ANTA_TIMEOUT; default: 30.0]\n  --insecure              Disable SSH Host Key validation.  [env var:\n                          ANTA_INSECURE]\n  --disable-cache         Disable cache globally.  [env var:\n                          ANTA_DISABLE_CACHE]\n  -i, --inventory FILE    Path to the inventory YAML file.  [env var:\n                          ANTA_INVENTORY; required]\n  --tags TEXT             List of tags using comma as separator:\n                          tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  --help                  Show this message and exit.\n
"},{"location":"cli/get-inventory-information/#example","title":"Example","text":"

To get the list of all configured tags in the inventory, run the following command:

anta get tags\nTags found:\n[\n  \"BL\",\n  \"DC1\",\n  \"DC2\",\n  \"LEAF\",\n  \"SPINE\"\n]\n\n* note that tag all has been added by anta\n

Note

Even if you haven\u2019t explicitly configured the all tag in the inventory, it is automatically added. This default tag allows to execute commands on all devices in the inventory when no tag is specified.

"},{"location":"cli/get-inventory-information/#list-devices-in-inventory","title":"List devices in inventory","text":"

This command will list all devices available in the inventory. Using the --tags option, you can filter this list to only include devices with specific tags. The --connected option allows to display only the devices where a connection has been established.

"},{"location":"cli/get-inventory-information/#command-overview_1","title":"Command overview","text":"
Usage: anta get inventory [OPTIONS]\n\n  Show inventory loaded in ANTA.\n\nOptions:\n  -u, --username TEXT            Username to connect to EOS  [env var:\n                                 ANTA_USERNAME; required]\n  -p, --password TEXT            Password to connect to EOS that must be\n                                 provided. It can be prompted using '--prompt'\n                                 option.  [env var: ANTA_PASSWORD]\n  --enable-password TEXT         Password to access EOS Privileged EXEC mode.\n                                 It can be prompted using '--prompt' option.\n                                 Requires '--enable' option.  [env var:\n                                 ANTA_ENABLE_PASSWORD]\n  --enable                       Some commands may require EOS Privileged EXEC\n                                 mode. This option tries to access this mode\n                                 before sending a command to the device.  [env\n                                 var: ANTA_ENABLE]\n  -P, --prompt                   Prompt for passwords if they are not\n                                 provided.  [env var: ANTA_PROMPT]\n  --timeout FLOAT                Global API timeout. This value will be used\n                                 for all devices.  [env var: ANTA_TIMEOUT;\n                                 default: 30.0]\n  --insecure                     Disable SSH Host Key validation.  [env var:\n                                 ANTA_INSECURE]\n  --disable-cache                Disable cache globally.  [env var:\n                                 ANTA_DISABLE_CACHE]\n  -i, --inventory FILE           Path to the inventory YAML file.  [env var:\n                                 ANTA_INVENTORY; required]\n  --tags TEXT                    List of tags using comma as separator:\n                                 tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  --connected / --not-connected  Display inventory after connection has been\n                                 created\n  --help                         Show this message and exit.\n

Tip

In its default mode, anta get inventory provides only information that doesn\u2019t rely on a device connection. If you are interested in obtaining connection-dependent details, like the hardware model, please use the --connected option.

"},{"location":"cli/get-inventory-information/#example_1","title":"Example","text":"

To retrieve a comprehensive list of all devices along with their details, execute the following command. It will provide all the data loaded into the ANTA inventory from your inventory file.

anta get inventory --tags SPINE\nCurrent inventory content is:\n{\n    'DC1-SPINE1': AsyncEOSDevice(\n        name='DC1-SPINE1',\n        tags=['SPINE', 'DC1'],\n        hw_model=None,\n        is_online=False,\n        established=False,\n        disable_cache=False,\n        host='172.20.20.101',\n        eapi_port=443,\n        username='arista',\n        enable=True,\n        enable_password='arista',\n        insecure=False\n    ),\n    'DC1-SPINE2': AsyncEOSDevice(\n        name='DC1-SPINE2',\n        tags=['SPINE', 'DC1'],\n        hw_model=None,\n        is_online=False,\n        established=False,\n        disable_cache=False,\n        host='172.20.20.102',\n        eapi_port=443,\n        username='arista',\n        enable=True,\n        insecure=False\n    ),\n    'DC2-SPINE1': AsyncEOSDevice(\n        name='DC2-SPINE1',\n        tags=['SPINE', 'DC2'],\n        hw_model=None,\n        is_online=False,\n        established=False,\n        disable_cache=False,\n        host='172.20.20.201',\n        eapi_port=443,\n        username='arista',\n        enable=True,\n        insecure=False\n    ),\n    'DC2-SPINE2': AsyncEOSDevice(\n        name='DC2-SPINE2',\n        tags=['SPINE', 'DC2'],\n        hw_model=None,\n        is_online=False,\n        established=False,\n        disable_cache=False,\n        host='172.20.20.202',\n        eapi_port=443,\n        username='arista',\n        enable=True,\n        insecure=False\n    )\n}\n
"},{"location":"cli/inv-from-ansible/","title":"Inventory from Ansible","text":""},{"location":"cli/inv-from-ansible/#create-an-inventory-from-ansible-inventory","title":"Create an Inventory from Ansible inventory","text":"

In large setups, it might be beneficial to construct your inventory based on your Ansible inventory. The from-ansible entrypoint of the get command enables the user to create an ANTA inventory from Ansible.

"},{"location":"cli/inv-from-ansible/#command-overview","title":"Command overview","text":"
$ anta get from-ansible --help\nUsage: anta get from-ansible [OPTIONS]\n\n  Build ANTA inventory from an ansible inventory YAML file.\n\n  NOTE: This command does not support inline vaulted variables. Make sure to\n  comment them out.\n\nOptions:\n  -o, --output FILE         Path to save inventory file  [env var:\n                            ANTA_INVENTORY; required]\n  --overwrite               Do not prompt when overriding current inventory\n                            [env var: ANTA_GET_FROM_ANSIBLE_OVERWRITE]\n  -g, --ansible-group TEXT  Ansible group to filter\n  --ansible-inventory FILE  Path to your ansible inventory file to read\n                            [required]\n  --help                    Show this message and exit.\n

Warning

anta get from-ansible does not support inline vaulted variables, comment them out to generate your inventory. If the vaulted variable is necessary to build the inventory (e.g. ansible_host), it needs to be unvaulted for from-ansible command to work.\u201d

The output is an inventory where the name of the container is added as a tag for each host:

anta_inventory:\n  hosts:\n  - host: 10.73.252.41\n    name: srv-pod01\n  - host: 10.73.252.42\n    name: srv-pod02\n  - host: 10.73.252.43\n    name: srv-pod03\n

Warning

The current implementation only considers devices directly attached to a specific Ansible group and does not support inheritance when using the --ansible-group option.

By default, if user does not provide --output file, anta will save output to configured anta inventory (anta --inventory). If the output file has content, anta will ask user to overwrite when running in interactive console. This mechanism can be controlled by triggers in case of CI usage: --overwrite to force anta to overwrite file. If not set, anta will exit

"},{"location":"cli/inv-from-ansible/#command-output","title":"Command output","text":"

host value is coming from the ansible_host key in your inventory while name is the name you defined for your host. Below is an ansible inventory example used to generate previous inventory:

---\ntooling:\n  children:\n    endpoints:\n      hosts:\n        srv-pod01:\n          ansible_httpapi_port: 9023\n          ansible_port: 9023\n          ansible_host: 10.73.252.41\n          type: endpoint\n        srv-pod02:\n          ansible_httpapi_port: 9024\n          ansible_port: 9024\n          ansible_host: 10.73.252.42\n          type: endpoint\n        srv-pod03:\n          ansible_httpapi_port: 9025\n          ansible_port: 9025\n          ansible_host: 10.73.252.43\n          type: endpoint\n
"},{"location":"cli/inv-from-cvp/","title":"Inventory from CVP","text":""},{"location":"cli/inv-from-cvp/#create-an-inventory-from-cloudvision","title":"Create an Inventory from CloudVision","text":"

In large setups, it might be beneficial to construct your inventory based on CloudVision. The from-cvp entrypoint of the get command enables the user to create an ANTA inventory from CloudVision.

Info

The current implementation only works with on-premises CloudVision instances, not with CloudVision as a Service (CVaaS).

"},{"location":"cli/inv-from-cvp/#command-overview","title":"Command overview","text":"
Usage: anta get from-cvp [OPTIONS]\n\n  Build ANTA inventory from CloudVision.\n\n  NOTE: Only username/password authentication is supported for on-premises CloudVision instances.\n  Token authentication for both on-premises and CloudVision as a Service (CVaaS) is not supported.\n\nOptions:\n  -o, --output FILE     Path to save inventory file  [env var: ANTA_INVENTORY;\n                        required]\n  --overwrite           Do not prompt when overriding current inventory  [env\n                        var: ANTA_GET_FROM_CVP_OVERWRITE]\n  -host, --host TEXT    CloudVision instance FQDN or IP  [required]\n  -u, --username TEXT   CloudVision username  [required]\n  -p, --password TEXT   CloudVision password  [required]\n  -c, --container TEXT  CloudVision container where devices are configured\n  --ignore-cert         By default connection to CV will use HTTPS\n                        certificate, set this flag to disable it  [env var:\n                        ANTA_GET_FROM_CVP_IGNORE_CERT]\n  --help                Show this message and exit.\n

The output is an inventory where the name of the container is added as a tag for each host:

anta_inventory:\n  hosts:\n  - host: 192.168.0.13\n    name: leaf2\n    tags:\n    - pod1\n  - host: 192.168.0.15\n    name: leaf4\n    tags:\n    - pod2\n

Warning

The current implementation only considers devices directly attached to a specific container when using the --cvp-container option.

"},{"location":"cli/inv-from-cvp/#creating-an-inventory-from-multiple-containers","title":"Creating an inventory from multiple containers","text":"

If you need to create an inventory from multiple containers, you can use a bash command and then manually concatenate files to create a single inventory file:

$ for container in pod01 pod02 spines; do anta get from-cvp -ip <cvp-ip> -u cvpadmin -p cvpadmin -c $container -d test-inventory; done\n\n[12:25:35] INFO     Getting auth token from cvp.as73.inetsix.net for user tom\n[12:25:36] INFO     Creating inventory folder /home/tom/Projects/arista/network-test-automation/test-inventory\n           WARNING  Using the new api_token parameter. This will override usage of the cvaas_token parameter if both are provided. This is because api_token and cvaas_token parameters\n                    are for the same use case and api_token is more generic\n           INFO     Connected to CVP cvp.as73.inetsix.net\n\n\n[12:25:37] INFO     Getting auth token from cvp.as73.inetsix.net for user tom\n[12:25:38] WARNING  Using the new api_token parameter. This will override usage of the cvaas_token parameter if both are provided. This is because api_token and cvaas_token parameters\n                    are for the same use case and api_token is more generic\n           INFO     Connected to CVP cvp.as73.inetsix.net\n\n\n[12:25:38] INFO     Getting auth token from cvp.as73.inetsix.net for user tom\n[12:25:39] WARNING  Using the new api_token parameter. This will override usage of the cvaas_token parameter if both are provided. This is because api_token and cvaas_token parameters\n                    are for the same use case and api_token is more generic\n           INFO     Connected to CVP cvp.as73.inetsix.net\n\n           INFO     Inventory file has been created in /home/tom/Projects/arista/network-test-automation/test-inventory/inventory-spines.yml\n
"},{"location":"cli/nrfu/","title":"NRFU","text":""},{"location":"cli/nrfu/#execute-network-readiness-for-use-nrfu-testing","title":"Execute Network Readiness For Use (NRFU) Testing","text":"

ANTA provides a set of commands for performing NRFU tests on devices. These commands are under the anta nrfu namespace and offer multiple output format options:

  • Text view
  • Table view
  • JSON view
  • Custom template view
"},{"location":"cli/nrfu/#nrfu-command-overview","title":"NRFU Command overview","text":"
Usage: anta nrfu [OPTIONS] COMMAND [ARGS]...\n\n  Run ANTA tests on selected inventory devices.\n\nOptions:\n  -u, --username TEXT             Username to connect to EOS  [env var:\n                                  ANTA_USERNAME; required]\n  -p, --password TEXT             Password to connect to EOS that must be\n                                  provided. It can be prompted using '--\n                                  prompt' option.  [env var: ANTA_PASSWORD]\n  --enable-password TEXT          Password to access EOS Privileged EXEC mode.\n                                  It can be prompted using '--prompt' option.\n                                  Requires '--enable' option.  [env var:\n                                  ANTA_ENABLE_PASSWORD]\n  --enable                        Some commands may require EOS Privileged\n                                  EXEC mode. This option tries to access this\n                                  mode before sending a command to the device.\n                                  [env var: ANTA_ENABLE]\n  -P, --prompt                    Prompt for passwords if they are not\n                                  provided.  [env var: ANTA_PROMPT]\n  --timeout FLOAT                 Global API timeout. This value will be used\n                                  for all devices.  [env var: ANTA_TIMEOUT;\n                                  default: 30.0]\n  --insecure                      Disable SSH Host Key validation.  [env var:\n                                  ANTA_INSECURE]\n  --disable-cache                 Disable cache globally.  [env var:\n                                  ANTA_DISABLE_CACHE]\n  -i, --inventory FILE            Path to the inventory YAML file.  [env var:\n                                  ANTA_INVENTORY; required]\n  --tags TEXT                     List of tags using comma as separator:\n                                  tag1,tag2,tag3.  [env var: ANTA_TAGS]\n  -c, --catalog FILE              Path to the test catalog file  [env var:\n                                  ANTA_CATALOG; required]\n  --catalog-format [yaml|json]    Format of the catalog file, either 'yaml' or\n                                  'json'  [env var: ANTA_CATALOG_FORMAT]\n  -d, --device TEXT               Run tests on a specific device. Can be\n                                  provided multiple times.\n  -t, --test TEXT                 Run a specific test. Can be provided\n                                  multiple times.\n  --ignore-status                 Exit code will always be 0.  [env var:\n                                  ANTA_NRFU_IGNORE_STATUS]\n  --ignore-error                  Exit code will be 0 if all tests succeeded\n                                  or 1 if any test failed.  [env var:\n                                  ANTA_NRFU_IGNORE_ERROR]\n  --hide [success|failure|error|skipped]\n                                  Hide result by type: success / failure /\n                                  error / skipped'.\n  --dry-run                       Run anta nrfu command but stop before\n                                  starting to execute the tests. Considers all\n                                  devices as connected.  [env var:\n                                  ANTA_NRFU_DRY_RUN]\n  --help                          Show this message and exit.\n\nCommands:\n  json        ANTA command to check network state with JSON result.\n  table       ANTA command to check network states with table result.\n  text        ANTA command to check network states with text result.\n  tpl-report  ANTA command to check network state with templated report.\n

username, password, enable-password, enable, timeout and insecure values are the same for all devices

All commands under the anta nrfu namespace require a catalog yaml file specified with the --catalog option and a device inventory file specified with the --inventory option.

Info

Issuing the command anta nrfu will run anta nrfu table without any option.

"},{"location":"cli/nrfu/#tag-management","title":"Tag management","text":"

The --tags option can be used to target specific devices in your inventory and run only tests configured with this specific tags from your catalog. The default tag is set to all and is implicit. Expected behaviour is provided below:

Command Description none Run all tests on all devices according tag definition in your inventory and test catalog. And tests with no tag are executed on all devices --tags leaf Run all tests marked with leaf tag on all devices configured with leaf tag. All other tags are ignored --tags leaf,spine Run all tests marked with leaf tag on all devices configured with leaf tag.Run all tests marked with spine tag on all devices configured with spine tag. All other tags are ignored

Info

More examples available on this dedicated page.

"},{"location":"cli/nrfu/#device-and-test-filtering","title":"Device and test filtering","text":"

Options --device and --test can be used to target one or multiple devices and/or tests to run in your environment. The options can be repeated. Example: anta nrfu --device leaf1a --device leaf1b --test VerifyUptime --test VerifyReloadCause.

"},{"location":"cli/nrfu/#hide-results","title":"Hide results","text":"

Option --hide can be used to hide test results in the output based on their status. The option can be repeated. Example: anta nrfu --hide error --hide skipped.

"},{"location":"cli/nrfu/#performing-nrfu-with-text-rendering","title":"Performing NRFU with text rendering","text":"

The text subcommand provides a straightforward text report for each test executed on all devices in your inventory.

"},{"location":"cli/nrfu/#command-overview","title":"Command overview","text":"
Usage: anta nrfu text [OPTIONS]\n\n  ANTA command to check network states with text result.\n\nOptions:\n  --help  Show this message and exit.\n
"},{"location":"cli/nrfu/#example","title":"Example","text":"

anta nrfu --device DC1-LEAF1A text\n

"},{"location":"cli/nrfu/#performing-nrfu-with-table-rendering","title":"Performing NRFU with table rendering","text":"

The table command under the anta nrfu namespace offers a clear and organized table view of the test results, suitable for filtering. It also has its own set of options for better control over the output.

"},{"location":"cli/nrfu/#command-overview_1","title":"Command overview","text":"
Usage: anta nrfu table [OPTIONS]\n\n  ANTA command to check network states with table result.\n\nOptions:\n  --group-by [device|test]  Group result by test or device.\n  --help                    Show this message and exit.\n

The --group-by option show a summarized view of the test results per host or per test.

"},{"location":"cli/nrfu/#examples","title":"Examples","text":"

anta nrfu --tags LEAF table\n

For larger setups, you can also group the results by host or test to get a summarized view:

anta nrfu table --group-by device\n

anta nrfu table --group-by test\n

To get more specific information, it is possible to filter on a single device or a single test:

anta nrfu --device spine1 table\n

anta nrfu --test VerifyZeroTouch table\n

"},{"location":"cli/nrfu/#performing-nrfu-with-json-rendering","title":"Performing NRFU with JSON rendering","text":"

The JSON rendering command in NRFU testing is useful in generating a JSON output that can subsequently be passed on to another tool for reporting purposes.

"},{"location":"cli/nrfu/#command-overview_2","title":"Command overview","text":"
anta nrfu json --help\nUsage: anta nrfu json [OPTIONS]\n\n  ANTA command to check network state with JSON result.\n\nOptions:\n  -o, --output FILE  Path to save report as a file  [env var:\n                     ANTA_NRFU_JSON_OUTPUT]\n  --help             Show this message and exit.\n

The --output option allows you to save the JSON report as a file.

"},{"location":"cli/nrfu/#example_1","title":"Example","text":"

anta nrfu --tags LEAF json\n

"},{"location":"cli/nrfu/#performing-nrfu-with-custom-reports","title":"Performing NRFU with custom reports","text":"

ANTA offers a CLI option for creating custom reports. This leverages the Jinja2 template system, allowing you to tailor reports to your specific needs.

"},{"location":"cli/nrfu/#command-overview_3","title":"Command overview","text":"

anta nrfu tpl-report --help\nUsage: anta nrfu tpl-report [OPTIONS]\n\n  ANTA command to check network state with templated report\n\nOptions:\n  -tpl, --template FILE  Path to the template to use for the report  [env var:\n                         ANTA_NRFU_TPL_REPORT_TEMPLATE; required]\n  -o, --output FILE      Path to save report as a file  [env var:\n                         ANTA_NRFU_TPL_REPORT_OUTPUT]\n  --help                 Show this message and exit.\n
The --template option is used to specify the Jinja2 template file for generating the custom report.

The --output option allows you to choose the path where the final report will be saved.

"},{"location":"cli/nrfu/#example_2","title":"Example","text":"

anta nrfu --tags LEAF tpl-report --template ./custom_template.j2\n

The template ./custom_template.j2 is a simple Jinja2 template:

{% for d in data %}\n* {{ d.test }} is [green]{{ d.result | upper}}[/green] for {{ d.name }}\n{% endfor %}\n

The Jinja2 template has access to all TestResult elements and their values, as described in this documentation.

You can also save the report result to a file using the --output option:

anta nrfu --tags LEAF tpl-report --template ./custom_template.j2 --output nrfu-tpl-report.txt\n

The resulting output might look like this:

cat nrfu-tpl-report.txt\n* VerifyMlagStatus is [green]SUCCESS[/green] for DC1-LEAF1A\n* VerifyMlagInterfaces is [green]SUCCESS[/green] for DC1-LEAF1A\n* VerifyMlagConfigSanity is [green]SUCCESS[/green] for DC1-LEAF1A\n* VerifyMlagReloadDelay is [green]SUCCESS[/green] for DC1-LEAF1A\n
"},{"location":"cli/nrfu/#dry-run-mode","title":"Dry-run mode","text":"

It is possible to run anta nrfu --dry-run to execute ANTA up to the point where it should communicate with the network to execute the tests. When using --dry-run, all inventory devices are assumed to be online. This can be useful to check how many tests would be run using the catalog and inventory.

"},{"location":"cli/overview/","title":"Overview","text":""},{"location":"cli/overview/#overview-of-antas-command-line-interface-cli","title":"Overview of ANTA\u2019s Command-Line Interface (CLI)","text":"

ANTA provides a powerful Command-Line Interface (CLI) to perform a wide range of operations. This document provides a comprehensive overview of ANTA CLI usage and its commands.

ANTA can also be used as a Python library, allowing you to build your own tools based on it. Visit this page for more details.

To start using the ANTA CLI, open your terminal and type anta.

"},{"location":"cli/overview/#invoking-anta-cli","title":"Invoking ANTA CLI","text":"
$ anta --help\nUsage: anta [OPTIONS] COMMAND [ARGS]...\n\n  Arista Network Test Automation (ANTA) CLI.\n\nOptions:\n  --version                       Show the version and exit.\n  --log-file FILE                 Send the logs to a file. If logging level is\n                                  DEBUG, only INFO or higher will be sent to\n                                  stdout.  [env var: ANTA_LOG_FILE]\n  -l, --log-level [CRITICAL|ERROR|WARNING|INFO|DEBUG]\n                                  ANTA logging level  [env var:\n                                  ANTA_LOG_LEVEL; default: INFO]\n  --help                          Show this message and exit.\n\nCommands:\n  check  Commands to validate configuration files.\n  debug  Commands to execute EOS commands on remote devices.\n  exec   Commands to execute various scripts on EOS devices.\n  get    Commands to get information from or generate inventories.\n  nrfu   Run ANTA tests on selected inventory devices.\n
"},{"location":"cli/overview/#anta-environment-variables","title":"ANTA environment variables","text":"

Certain parameters are required and can be either passed to the ANTA CLI or set as an environment variable (ENV VAR).

To pass the parameters via the CLI:

anta nrfu -u admin -p arista123 -i inventory.yaml -c tests.yaml\n

To set them as environment variables:

export ANTA_USERNAME=admin\nexport ANTA_PASSWORD=arista123\nexport ANTA_INVENTORY=inventory.yml\nexport ANTA_INVENTORY=tests.yml\n

Then, run the CLI without options:

anta nrfu\n

Note

All environment variables may not be needed for every commands. Refer to <command> --help for the comprehensive environment variables names.

Below are the environment variables usable with the anta nrfu command:

Variable Name Purpose Required ANTA_USERNAME The username to use in the inventory to connect to devices. Yes ANTA_PASSWORD The password to use in the inventory to connect to devices. Yes ANTA_INVENTORY The path to the inventory file. Yes ANTA_CATALOG The path to the catalog file. Yes ANTA_PROMPT The value to pass to the prompt for password is password is not provided No ANTA_INSECURE Whether or not using insecure mode when connecting to the EOS devices HTTP API. No ANTA_DISABLE_CACHE A variable to disable caching for all ANTA tests (enabled by default). No ANTA_ENABLE Whether it is necessary to go to enable mode on devices. No ANTA_ENABLE_PASSWORD The optional enable password, when this variable is set, ANTA_ENABLE or --enable is required. No

Info

Caching can be disabled with the global parameter --disable-cache. For more details about how caching is implemented in ANTA, please refer to Caching in ANTA.

"},{"location":"cli/overview/#anta-exit-codes","title":"ANTA Exit Codes","text":"

ANTA CLI utilizes the following exit codes:

  • Exit code 0 - All tests passed successfully.
  • Exit code 1 - An internal error occurred while executing ANTA.
  • Exit code 2 - A usage error was raised.
  • Exit code 3 - Tests were run, but at least one test returned an error.
  • Exit code 4 - Tests were run, but at least one test returned a failure.

To ignore the test status, use anta nrfu --ignore-status, and the exit code will always be 0.

To ignore errors, use anta nrfu --ignore-error, and the exit code will be 0 if all tests succeeded or 1 if any test failed.

"},{"location":"cli/overview/#shell-completion","title":"Shell Completion","text":"

You can enable shell completion for the ANTA CLI:

ZSHBASH

If you use ZSH shell, add the following line in your ~/.zshrc:

eval \"$(_ANTA_COMPLETE=zsh_source anta)\" > /dev/null\n

With bash, add the following line in your ~/.bashrc:

eval \"$(_ANTA_COMPLETE=bash_source anta)\" > /dev/null\n
"},{"location":"cli/tag-management/","title":"Tag Management","text":""},{"location":"cli/tag-management/#tag-management","title":"Tag management","text":""},{"location":"cli/tag-management/#overview","title":"Overview","text":"

Some of the ANTA commands like anta nrfu command come with a --tags option.

For nrfu, this allows users to specify a set of tests, marked with a given tag, to be run on devices marked with the same tag. For instance, you can run tests dedicated to leaf devices on your leaf devices only and not on other devices.

Tags are string defined by the user and can be anything considered as a string by Python. A default one is present for all tests and devices.

The next table provides a short summary of the scope of tags using CLI

Command Description none Run all tests on all devices according tag definition in your inventory and test catalog. And tests with no tag are executed on all devices --tags leaf Run all tests marked with leaf tag on all devices configured with leaf tag. All other tags are ignored --tags leaf,spine Run all tests marked with leaf tag on all devices configured with leaf tag.Run all tests marked with spine tag on all devices configured with spine tag. All other tags are ignored"},{"location":"cli/tag-management/#inventory-and-catalog-for-tests","title":"Inventory and Catalog for tests","text":"

All commands in this page are based on the following inventory and test catalog.

InventoryTest Catalog
---\nanta_inventory:\n  hosts:\n  - host: 192.168.0.10\n    name: spine01\n    tags: ['fabric', 'spine']\n  - host: 192.168.0.11\n    name: spine02\n    tags: ['fabric', 'spine']\n  - host: 192.168.0.12\n    name: leaf01\n    tags: ['fabric', 'leaf']\n  - host: 192.168.0.13\n    name: leaf02\n    tags: ['fabric', 'leaf']\n  - host: 192.168.0.14\n    name: leaf03\n    tags: ['fabric', 'leaf']\n  - host: 192.168.0.15\n    name: leaf04\n    tags: ['fabric', 'leaf'\n
anta.tests.system:\n  - VerifyUptime:\n      minimum: 10\n      filters:\n        tags: ['fabric']\n  - VerifyReloadCause:\n      tags: ['leaf', spine']\n  - VerifyCoredump:\n  - VerifyAgentLogs:\n  - VerifyCPUUtilization:\n      filters:\n        tags: ['spine', 'leaf']\n  - VerifyMemoryUtilization:\n  - VerifyFileSystemUtilization:\n  - VerifyNTP:\n\nanta.tests.mlag:\n  - VerifyMlagStatus:\n\n\nanta.tests.interfaces:\n  - VerifyL3MTU:\n      mtu: 1500\n      filters:\n        tags: ['demo']\n
"},{"location":"cli/tag-management/#default-tags","title":"Default tags","text":"

By default, ANTA uses a default tag for both devices and tests. This default tag is all and it can be explicit if you want to make it visible in your inventory and also implicit since the framework injects this tag if it is not defined.

So this command will run all tests from your catalog on all devices. With a mapping for tags defined in your inventory and catalog. If no tags configured, then tests are executed against all devices.

$ anta nrfu -c .personal/catalog-class.yml table --group-by device\n\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Settings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 Running ANTA tests:                                  \u2502\n\u2502 - ANTA Inventory contains 6 devices (AsyncEOSDevice) \u2502\n\u2502 - Tests catalog contains 10 tests                    \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n\n\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2533\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2513\n\u2503 Device  \u2503 # of success \u2503 # of skipped \u2503 # of failure \u2503 # of errors \u2503 List of failed or error test cases \u2503\n\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2547\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2529\n\u2502 spine01 \u2502 5            \u2502 1            \u2502 1            \u2502 0           \u2502 ['VerifyCPUUtilization']           \u2502\n\u2502 spine02 \u2502 5            \u2502 1            \u2502 1            \u2502 0           \u2502 ['VerifyCPUUtilization']           \u2502\n\u2502 leaf01  \u2502 6            \u2502 0            \u2502 1            \u2502 0           \u2502 ['VerifyCPUUtilization']           \u2502\n\u2502 leaf02  \u2502 6            \u2502 0            \u2502 1            \u2502 0           \u2502 ['VerifyCPUUtilization']           \u2502\n\u2502 leaf03  \u2502 6            \u2502 0            \u2502 1            \u2502 0           \u2502 ['VerifyCPUUtilization']           \u2502\n\u2502 leaf04  \u2502 6            \u2502 0            \u2502 1            \u2502 0           \u2502 ['VerifyCPUUtilization']           \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n
"},{"location":"cli/tag-management/#use-a-single-tag-in-cli","title":"Use a single tag in CLI","text":"

The most used approach is to use a single tag in your CLI to filter tests & devices configured with this one.

In such scenario, ANTA will run tests marked with $tag only on devices marked with $tag. All other tests and devices will be ignored

$ anta nrfu -c .personal/catalog-class.yml --tags leaf text\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Settings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 Running ANTA tests:                                  \u2502\n\u2502 - ANTA Inventory contains 6 devices (AsyncEOSDevice) \u2502\n\u2502 - Tests catalog contains 10 tests                    \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n\nleaf01 :: VerifyUptime :: SUCCESS\nleaf01 :: VerifyReloadCause :: SUCCESS\nleaf01 :: VerifyCPUUtilization :: SUCCESS\nleaf02 :: VerifyUptime :: SUCCESS\nleaf02 :: VerifyReloadCause :: SUCCESS\nleaf02 :: VerifyCPUUtilization :: SUCCESS\nleaf03 :: VerifyUptime :: SUCCESS\nleaf03 :: VerifyReloadCause :: SUCCESS\nleaf03 :: VerifyCPUUtilization :: SUCCESS\nleaf04 :: VerifyUptime :: SUCCESS\nleaf04 :: VerifyReloadCause :: SUCCESS\nleaf04 :: VerifyCPUUtilization :: SUCCESS\n

In this case, only leaf devices defined in your inventory are used to run tests marked with leaf in your test catalog

"},{"location":"cli/tag-management/#use-multiple-tags-in-cli","title":"Use multiple tags in CLI","text":"

A more advanced usage of the tag feature is to list multiple tags in your CLI using --tags $tag1,$tag2 syntax.

In such scenario, all devices marked with $tag1 will be selected and ANTA will run tests with $tag1, then devices with $tag2 will be selected and will be tested with tests marked with $tag2

anta nrfu -c .personal/catalog-class.yml --tags leaf,fabric text\n\nspine01 :: VerifyUptime :: SUCCESS\nspine02 :: VerifyUptime :: SUCCESS\nleaf01 :: VerifyUptime :: SUCCESS\nleaf01 :: VerifyReloadCause :: SUCCESS\nleaf01 :: VerifyCPUUtilization :: SUCCESS\nleaf02 :: VerifyUptime :: SUCCESS\nleaf02 :: VerifyReloadCause :: SUCCESS\nleaf02 :: VerifyCPUUtilization :: SUCCESS\nleaf03 :: VerifyUptime :: SUCCESS\nleaf03 :: VerifyReloadCause :: SUCCESS\nleaf03 :: VerifyCPUUtilization :: SUCCESS\nleaf04 :: VerifyUptime :: SUCCESS\nleaf04 :: VerifyReloadCause :: SUCCESS\nleaf04 :: VerifyCPUUtilization :: SUCCESS\n
"}]} \ No newline at end of file diff --git a/main/sitemap.xml.gz b/main/sitemap.xml.gz index b7cb2c728..85deafcdc 100644 Binary files a/main/sitemap.xml.gz and b/main/sitemap.xml.gz differ diff --git a/main/snippets/anta_nrfu_help.txt b/main/snippets/anta_nrfu_help.txt index 0717daa9e..48bb15b9b 100644 --- a/main/snippets/anta_nrfu_help.txt +++ b/main/snippets/anta_nrfu_help.txt @@ -43,7 +43,8 @@ Options: or 1 if any test failed. [env var: ANTA_NRFU_IGNORE_ERROR] --hide [success|failure|error|skipped] - Group result by test or device. + Hide result by type: success / failure / + error / skipped'. --dry-run Run anta nrfu command but stop before starting to execute the tests. Considers all devices as connected. [env var: