### Start Development Environment Source: https://github.com/nornir-automation/nornir/blob/main/docs/contributing/index.md Use this command to start the necessary services for development and testing, managed by docker-compose. ```bash make start_dev_env ``` -------------------------------- ### Basic Nornir Runbook Example Source: https://github.com/nornir-automation/nornir/blob/main/docs/index.md This snippet demonstrates how to initialize Nornir, run a NAPALM task to retrieve facts and interfaces, and print the results. Ensure Nornir and nornir-napalm are installed, and a 'nornir.yaml' configuration file exists. ```python from nornir import InitNornir from nornir_utils.plugins.functions import print_result from nornir_napalm.plugins.tasks import napalm_get nr = InitNornir( config_file="nornir.yaml", dry_run=True ) results = nr.run( task=napalm_get, getters=["facts", "interfaces"] ) print_result(results) ``` -------------------------------- ### Registering Inventory Plugin via Entry Points (setup.py) Source: https://github.com/nornir-automation/nornir/blob/main/docs/plugins/index.md Example of how to register an inventory plugin using setuptools entry points in setup.py. ```APIDOC ## Registering Inventory Plugin via Entry Points (setup.py) ### Description Example of how to register an inventory plugin using setuptools entry points in setup.py. ### Method Entry Points ### Endpoint `setup.py` ### Parameters #### Path Parameters - **PATH** (string) - Required - The entry point path, e.g., `nornir.plugins.inventory`. - **NAME** (string) - Required - The name to refer to the plugin. - **path.to:Plugin** (string) - Required - The import path to the plugin class. ### Request Example ```python setup( # ... entry_points={ "nornir.plugins.inventory": "inventory-name = path.to:InventoryPlugin", } ) ``` ``` -------------------------------- ### Install ipdb Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/ipdb_how_to_inspect_complex_structures.md Install ipdb using pip. Ensure ipython is installed first by following its official guide. ```bash pip install ipdb ``` -------------------------------- ### start(host: Host) Source: https://github.com/nornir-automation/nornir/blob/main/docs/api/nornir/core/task.md Initiates and runs a task for a specified host. This method is crucial for executing automation tasks on individual inventory hosts. ```APIDOC ## start(host: Host) ### Description Runs the task for the given host. This method is called internally by Nornir to execute a task against a specific host in the inventory. ### Method This is a method call within the Nornir SDK, not an HTTP endpoint. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **host** ([`nornir.core.inventory.Host`](inventory.md#nornir.core.inventory.Host)) – Host we are operating with. Populated right before calling the `task`. * **nornir** (`nornir.core.Nornir`) – Populated right before calling the `task`. ### Returns Results of the task and its subtasks. ### Return type host ([`nornir.core.task.MultiResult`](#nornir.core.task.MultiResult)) ``` -------------------------------- ### Example Inventory Hosts File Content Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb This is an example of the YAML content for the hosts.yaml inventory file, detailing device hostnames, groups, and custom data. ```yaml --- lab-csr-011.lab.norn.local: hostname: lab-csr-011.lab.norn.local groups: - ios - lab - mel data: mgmt_ip: 10.0.0.16 vendor: cisco device_type: router os_version: 16.6.4 site_code: mel dfjt-r001.lab.norn.local: hostname: dfjt-r001.lab.norn.local groups: - ios - lab - bcn data: mgmt_ip: 10.0.0.1 vendor: cisco device_type: router os_version: 16.6.3 site_code: bcn lab-arista-01.lab.norn.local: hostname: lab-arista-01.lab.norn.local groups: - eos - lab - mtl data: mgmt_ip: 10.0.0.11 vendor: arista device_type: switch os_version: 4.22.0F site_code: mtl lab-arista-02.lab.norn.local: hostname: lab-arista-02.lab.norn.local groups: - eos - lab - mel data: mgmt_ip: 10.0.0.18 vendor: arista device_type: switch os_version: 4.23.2F site_code: mel lab-junos-01.lab.norn.local: hostname: lab-junos-01.lab.norn.local groups: - junos - lab - mtl data: mgmt_ip: 10.0.0.15 vendor: juniper device_type: router os_version: 18.4R2-S5 site_code: mtl lab-nxos-01.lab.norn.local: hostname: lab-nxos-01.lab.norn.local groups: - nxos - lab - mtl data: mgmt_ip: 10.0.0.14 vendor: cisco device_type: switch os_version: 9.3(6) site_code: mtl lab-paloalto-01.lab.djft.local: hostname: lab-paloalto-01.lab.djft.local groups: - panos - lab - mel data: mgmt_ip: 10.0.0.21 vendor: palo alto device_type: firewall os_version: 10.0.3 site_code: mel lab-paloalto-02.lab.norn.local: hostname: lab-paloalto-02.lab.norn.local groups: - panos - lab - bcn data: mgmt_ip: 10.0.0.22 vendor: palo alto device_type: firewall os_version: 9.1.3-h1 site_code: bcn lab-junos-06.lab.norn.local: hostname: lab-junos-06.lab.norn.local groups: - junos - lab - mel data: mgmt_ip: 10.0.0.23 vendor: juniper device_type: switch os_version: 18.4R2-S5 site_code: mel prd-csr-01.prd.norn.local: hostname: prd-csr-01.prd.norn.local groups: - ios - prod - mel data: mgmt_ip: 10.0.16.16 vendor: cisco device_type: router os_version: 16.6.4 site_code: mel dfjt-r001.prd.norn.local: hostname: dfjt-r001.prd.norn.local groups: - ios - prod - mel data: mgmt_ip: 10.0.16.1 vendor: cisco device_type: router os_version: 16.6.3 site_code: mel prd-arista-01.prd.norn.local: hostname: prd-arista-01.prd.norn.local groups: - eos - prod - mel data: mgmt_ip: 10.0.16.11 vendor: arista device_type: switch os_version: 4.21.1F site_code: mel prd-arista-02.prd.nron.local: hostname: prd-arista-02.prd.norn.local groups: - eos - prod - mel data: mgmt_ip: 10.0.16.18 vendor: arista device_type: switch os_version: 4.23.1F site_code: mel prd-junos-01.prd.norn.local: hostname: prd-junos-01.prd.norn.local groups: - junos - prod - mel data: mgmt_ip: 10.0.16.15 vendor: juniper device_type: router os_version: 15.1R7-S6 site_code: mel prd-nxos-01.prd.norn.local: hostname: prd-nxos-01.prd.norn.local groups: - nxos_ssh - prod - mel data: mgmt_ip: 10.0.16.14 vendor: cisco device_type: switch os_version: 7.0(3) site_code: mel prd-paloalto-01.prd.norn.local: hostname: prd-paloalto-01.prd.norn.local groups: - panos - prod - mel data: mgmt_ip: 10.0.16.21 vendor: palo alto device_type: firewall os_version: 10.0.3 site_code: mel prd-paloalto-02.prd.norn.local: hostname: prd-paloalto-02.prd.norn.local groups: - panos - prod - mel data: ``` -------------------------------- ### Registering Inventory Plugin via Entry Points (pyproject.toml) Source: https://github.com/nornir-automation/nornir/blob/main/docs/plugins/index.md Example of how to register an inventory plugin using pyproject.toml with a standards-based build tool. ```APIDOC ## Registering Inventory Plugin via Entry Points (pyproject.toml) ### Description Example of how to register an inventory plugin using pyproject.toml with a standards-based build tool. ### Method Entry Points ### Endpoint `pyproject.toml` ### Parameters #### Path Parameters - **PATH** (string) - Required - The entry point path, e.g., `nornir.plugins.inventory`. - **NAME** (string) - Required - The name to refer to the plugin. - **path.to:Plugin** (string) - Required - The import path to the plugin class. ### Request Example ```toml [project.entry-points."nornir.plugins.inventory"] inventory-name = "path.to:InventoryPlugin" ``` ``` -------------------------------- ### Registering Inventory Plugin via Entry Points (poetry) Source: https://github.com/nornir-automation/nornir/blob/main/docs/plugins/index.md Example of how to register an inventory plugin using poetry. ```APIDOC ## Registering Inventory Plugin via Entry Points (poetry) ### Description Example of how to register an inventory plugin using poetry. ### Method Entry Points ### Endpoint `pyproject.toml` (with poetry) ### Parameters #### Path Parameters - **PATH** (string) - Required - The entry point path, e.g., `nornir.plugins.inventory`. - **NAME** (string) - Required - The name to refer to the plugin. - **path.to:Plugin** (string) - Required - The import path to the plugin class. ### Request Example ```toml [tool.poetry.plugins."nornir.plugins.inventory"] "inventory-name" = "path.to:InventoryPlugin" ``` ``` -------------------------------- ### Check pip Installation Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/install.md Verify that pip is installed on your system. You might need to use 'pip3' on some systems. ```bash $ pip --version pip 20.1 from /home/dbarroso/.virtualenvs/nornir/lib/python3.8/site-packages/pip (python 3.8) ``` -------------------------------- ### Example of Nornir Processor Results Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/processors.ipynb This snippet shows the typical output structure when using Nornir processors, illustrating the 'completed' status and 'result' for each host, along with a 'started' flag for the overall execution. ```json { "spine00.cmh": { "completed": true, "result": "hi! my name is spine00.cmh" }, "spine01.bma": { "completed": true, "result": "hi! my name is spine01.bma" }, "spine01.cmh": { "completed": true, "result": "hi! my name is spine01.cmh" }, "started": true } ``` -------------------------------- ### Initialize Nornir and Load Configuration Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/processors.ipynb Initializes the Nornir object and loads the configuration from a specified file. This is a common setup step for Nornir automation tasks. ```python from typing import Dict from nornir import InitNornir nr = InitNornir(config_file="config.yaml") ``` -------------------------------- ### Inventory Host Configuration Example Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/handling_connections.ipynb Displays a snippet from a YAML inventory file showing how connection parameters like port, hostname, username, and platform can be specified at the host level, including nested connection options for different plugins. ```yaml dev1.group_1: port: 65020 hostname: localhost username: password: a_password platform: eos data: some_string_to_test_any_all: prefix my_var: comes_from_dev1.group_1 www_server: nginx role: www nested_data: a_dict: a: 1 b: 2 a_list: [1, 2] a_string: asdasd groups: - group_1 connection_options: paramiko: port: 65020 hostname: username: root password: docker platform: linux extras: {} dummy: hostname: dummy_from_host port: username: password: platform: extras: blah: from_host ``` -------------------------------- ### Verify Nornir Installation in Python Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/install.md Import the InitNornir function from the nornir package to confirm a successful installation. This is done within a Python interactive session. ```python >>> from nornir import InitNornir >>> ``` -------------------------------- ### Install Nornir using pip Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/install.md Install the Nornir package and its dependencies using pip. The output may vary, but ensure the success message indicates Nornir was installed. ```bash $ pip install nornir Collecting nornir Downloading nornir-3.0.0-py3-none-any.whl (28 kB) Requirement already satisfied: typing_extensions<4.0,>=3.7 in /home/dbarroso/.virtualenvs/tmp-nornir/lib/python3.8/site-packages (from nornir) (3.7.4.2) Requirement already satisfied: mypy_extensions<0.5.0,>=0.4.1 in /home/dbarroso/.virtualenvs/tmp-nornir/lib/python3.8/site-packages (from nornir) (0.4.3) Collecting ruamel.yaml<0.17,>=0.16 Using cached ruamel.yaml-0.16.10-py2.py3-none-any.whl (111 kB) Collecting ruamel.yaml.clib>=0.1.2; platform_python_implementation == "CPython" and python_version < "3.9" Using cached ruamel.yaml.clib-0.2.0-cp38-cp38-manylinux1_x86_64.whl (578 kB) Installing collected packages: colorama, ruamel.yaml.clib, ruamel.yaml, nornir Successfully installed nornir-3.0.0 ruamel.yaml-0.16.10 ruamel.yaml.clib-0.2.0 ``` -------------------------------- ### Install Nornir with Pip Source: https://github.com/nornir-automation/nornir/blob/main/README.md Use this command to install Nornir. Requires Python 3.10 or higher. ```bash pip install nornir ``` -------------------------------- ### Registering Inventory Plugin Programmatically Source: https://github.com/nornir-automation/nornir/blob/main/docs/plugins/index.md Example of how to register an inventory plugin programmatically. ```APIDOC ## Registering Inventory Plugin Programmatically ### Description Example of how to register an inventory plugin programmatically. ### Method Programmatic Registration ### Endpoint Python Script ### Request Example ```python from nornir.core.plugins.inventory import InventoryPluginRegister from path.to import InventoryPlugin InventoryPluginRegister.register("inventory-name", InventoryPlugin) ``` ``` -------------------------------- ### Filter by Multiple Groups Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb This example demonstrates filtering devices that belong to all specified groups ('eos', 'prod', 'mel'). It's useful for targeting devices that must meet multiple group memberships. ```python from nornir import InitNornir nr = InitNornir() all_groups_devices = nr.filter(lambda x: all(group in x.groups for group in ['eos', 'prod', 'mel'])) print(f"Total: {len(all_groups_devices)}") print("==================================================") ``` -------------------------------- ### Filter by Hostname Prefix using startswith Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Filters inventory hosts whose names start with a specific prefix. Useful for selecting devices in a particular region or naming convention. ```python print("=" * 50) print("All devices starts with 'am' in region - using startswith operation") # Iterate over filtered results and printout information for host, data in am_devs.inventory.hosts.items(): print( f"Host: {host} " + f"- Platform: {data['region']}" ) # Print total and seperator print(f"Total: {len(am_devs.inventory.hosts.items())}") print("=" * 50) ``` -------------------------------- ### Stop Development Environment Source: https://github.com/nornir-automation/nornir/blob/main/docs/contributing/index.md Use this command to stop the services that were started for the development environment. ```bash make stop_dev_env ``` -------------------------------- ### Displaying Custom Host Data (YAML Extract) Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Shows an example of custom data stored under the 'data' key for a host in YAML format. This data can include management IPs, vendor information, and OS versions. ```yaml --- lab-csr-011.lab.norn.local: hostname: lab-csr-011.lab.norn.local groups: - ios - lab - mel data: # Anything under this key is custom data mgmt_ip: 10.0.0.16 # This is custom data vendor: cisco # So is this device_type: router # Same as this os_version: 16.6.4 # Also this too site_code: mel # Yes, and also this ``` -------------------------------- ### Define a Simple Greeter Task Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/processors.ipynb Defines a basic Nornir task function that returns a greeting string including the host's name. This serves as a simple example task to be used with processors. ```python def greeter(task: Task, greet: str) -> Result: return Result(host=task.host, result=f"{greet}! my name is {task.host.name}") ``` -------------------------------- ### Apply Custom Filter Functions to Nornir Inventory Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Demonstrates how to apply custom Python filter functions to a Nornir inventory. This example shows filtering for even-numbered devices, compliant naming conventions, and non-compliant naming conventions. ```python from nornir import InitNornir # Assume filter functions (even_device_naming_convention, device_name_convention, non_device_name_convention) are defined above nr = InitNornir(config_file="filtering_deep_dive/config.yaml") # Use Case 1 - Filter inventory for "even" numbered devices. even_device_name_hosts = nr.filter(filter_func=even_device_naming_convention) print("\n" + "=" * 50) print("The hosts which match the even device naming convention are:") for host, data in even_device_name_hosts.inventory.hosts.items(): print(f"Host: {host} ") print(f"Total: {len(even_device_name_hosts.inventory.hosts.items())}") print("=" * 50) # Use Case 2 - Filter inventory for device which meet the naming convention. compliant_naming_convention_hosts = nr.filter(filter_func=device_name_convention) print("\n" + "=" * 50) print("The hosts which match the device naming convention are:") for host, data in compliant_naming_convention_hosts.inventory.hosts.items(): print(f"Host: {host} ") print(f"Total: {len(compliant_naming_convention_hosts.inventory.hosts.items())}") print("=" * 50) # Use Case 3 - Filter inventory for device which DO NOT meet the naming convention. non_compliant_naming_convention_hosts = nr.filter(filter_func=non_device_name_convention) print("\n" + "=" * 50) print("The hosts which DO NOT match the device naming convention are:") for host, data in non_compliant_naming_convention_hosts.inventory.hosts.items(): print(f"Host: {host} ") print(f"Total: {len(non_compliant_naming_convention_hosts.inventory.hosts.items())}") print("=" * 50) ``` -------------------------------- ### Nornir and Tqdm Progress Bar Integration Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/progress_bar.md This example demonstrates how to use two nested tqdm progress bars within a Nornir task to track the progress of different operations independently. The task function receives the progress bar objects and updates them as operations complete. Use `tqdm.write()` to print messages without interfering with the progress bars. ```python from nornir import InitNornir from nornir_napalm.tasks import napalm_get from tqdm import tqdm nr = InitNornir(config_file="config.yaml") def multiple_progress_bar(task, napalm_get_bar, other_bar): """ This task takes two paramters that are in fact bars; napalm_get_bar and other_bar. When we want to tell to each respective bar that we are done and should update the progress we can do so with bar_name.update() """ task.run(task=napalm_get, getters=["facts"]) napalm_get_bar.update() tqdm.write(f"{task.host}: facts gathered") # more actions go here other_bar.update() tqdm.write(f"{task.host}: done!") # we create the first bar named napalm_get_bar with tqdm( total=len(nr.inventory.hosts), desc="gathering facts", ) as napalm_get_bar: # we create the second bar named other_bar with tqdm( total=len(nr.inventory.hosts), desc="other action ", ) as other_bar: # we call our grouped task passing both bars nr.run( task=multiple_progress_bar, napalm_get_bar=napalm_get_bar, other_bar=other_bar, ) ``` -------------------------------- ### Register Inventory Plugin via setup.py Source: https://github.com/nornir-automation/nornir/blob/main/docs/plugins/index.md Register an inventory plugin using entry points in your setup.py file. Replace 'PATH' with the appropriate plugin type and 'NAME' with your desired plugin name. ```python setup( # ... entry_points={ "PATH": "NAME = path.to:Plugin", } ) ``` -------------------------------- ### Initialize Nornir and Access Inventory Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/inventory.ipynb Initializes Nornir with a configuration file and prints the dictionary of hosts available in the inventory. ```python from nornir import InitNornir nr = InitNornir(config_file="config.yaml") print(nr.inventory.hosts) ``` -------------------------------- ### Filter regions starting with 'am' using 'startswith' operation Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Filters inventory for devices where the 'region' attribute starts with the string 'am'. This is useful for matching prefixes in string attributes. ```python # Use Case 6 - startswith operation # Filter for a platform that starts with "am". # i.e match "amer", "amea" but not "apac" am_devs = nr.filter(F(region__startswith="am")) ``` -------------------------------- ### Execute the 'Hello World' Task Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/tasks.ipynb Executes the 'hello_world' task on the filtered hosts using Nornir's run method and prints the results. The output shows the result for each host. ```python result = nr.run(task=hello_world) print_result(result) ``` -------------------------------- ### Filter devices starting with 'am' in region Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Shows how to filter devices where the 'region' attribute starts with the string 'am'. This is useful for selecting devices within a specific geographical or logical region. ```python print(f"Total: {len(eos_prod_mel.inventory.hosts.items())}") print("=" * 50) for host, data in eos_prod_mel.inventory.hosts.items(): if data.region.startswith("am"): print(f"Host: {host} - Platform: {data.platform}") print(f"Total: {len(eos_prod_mel.inventory.hosts.items())})") print("=" * 50) ``` -------------------------------- ### Initialize Nornir with a Configuration File Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/initializing_nornir.ipynb Initialize Nornir using a YAML configuration file. Ensure the configuration file exists at the specified path. ```python from nornir import InitNornir nr = InitNornir(config_file="config.yaml") ``` -------------------------------- ### Get Children of a Group Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/inventory.ipynb Retrieve all hosts that are children of a specified group. ```python nr.inventory.children_of_group("eu") ``` -------------------------------- ### nornir.init_nornir.InitNornir Source: https://github.com/nornir-automation/nornir/blob/main/docs/api/nornir/init_nornir.md Initializes and configures a Nornir object. This is the primary entry point for setting up Nornir with a configuration file and optional parameters. ```APIDOC ## nornir.init_nornir.InitNornir ### Description Initializes and configures a Nornir object. This is the primary entry point for setting up Nornir with a configuration file and optional parameters. ### Method `InitNornir` ### Parameters #### Path Parameters * **config_file** (str) - Optional - Path to the configuration file. * **dry_run** (bool) - Optional - Whether to simulate changes or not. * **configure_logging** (bool) - Deprecated - Whether to configure logging or not. Please use logging.enabled parameter in the configuration instead. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response * **Nornir object** (`nornir.core.Nornir`) - A fully instantiated and configured Nornir object. #### Response Example None ``` -------------------------------- ### Initialize Nornir and Load Inventory Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/advanced_filtering.ipynb Initializes Nornir with a configuration file and loads the inventory. This is a prerequisite for filtering. ```python from nornir import InitNornir from nornir.core.filter import F nr = InitNornir(config_file="advanced_filtering/config.yaml") ``` -------------------------------- ### Run Jupyter Notebook Tutorial Verification Source: https://github.com/nornir-automation/nornir/blob/main/docs/contributing/index.md Build the test container and then run the nbval tests to verify Jupyter notebook outputs. ```bash make build_test_container && make nbval ``` -------------------------------- ### Initialize Nornir Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Initializes Nornir with a specified configuration file. Ensure the config file path is correct. ```python nr = InitNornir(config_file="filtering_deep_dive/config.yaml") ``` -------------------------------- ### Basic Nornir Initialization Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Initializes Nornir using a configuration file. This is a prerequisite for most Nornir operations. ```python # Import modules from nornir import InitNornir from nornir.core.filter import F # Initialise nornir nr = InitNornir(config_file="filtering_deep_dive/config.yaml") ``` -------------------------------- ### Import Nornir Modules for Filtering Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Imports necessary modules from the Nornir library and the 're' module for regular expression operations. This setup is required for advanced filtering logic. ```python from nornir import InitNornir from nornir.core.filter import F import re ``` -------------------------------- ### Initialize Nornir and Filter Inventory Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/tasks.ipynb Initializes Nornir with a configuration file and filters the inventory to include only hosts from a specific site and role. ```python # Initializing objects for later use from nornir import InitNornir from nornir_utils.plugins.functions import print_result nr = InitNornir(config_file="config.yaml") # filtering objects to simplify output nr = nr.filter(site="cmh", role="host") ``` -------------------------------- ### SimpleInventory.load() Source: https://github.com/nornir-automation/nornir/blob/main/docs/api/nornir/plugins/inventory/simple.md Loads inventory data from specified YAML files (hosts, groups, defaults). ```APIDOC ## SimpleInventory.load() ### Description Loads inventory data from specified YAML files (hosts, groups, defaults). ### Method load() ### Parameters This method does not accept any parameters. ### Response #### Success Response - Returns an `Inventory` object containing the loaded inventory data. ### Response Example ```json { "example": "Inventory object" } ``` ``` -------------------------------- ### Initialize Nornir with Configuration File and Code Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/initializing_nornir.ipynb Initialize Nornir by combining a configuration file with programmatic overrides for specific settings like the number of workers. ```python from nornir import InitNornir nr = InitNornir( config_file="config.yaml", runner={ "plugin": "threaded", "options": { "num_workers": 50, }, }, ) ``` -------------------------------- ### Inspect AggregatedResult Object Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/ipdb_how_to_inspect_complex_structures.md After hitting a breakpoint, use ipdb commands to inspect the type and structure of the result object. This example shows how to determine if the object is dictionary-like and explore its keys. ```python print(type(r)) print(r.keys()) ``` -------------------------------- ### Initialize Nornir and Access Single Host Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Initializes Nornir with a configuration file and demonstrates how to access a specific host from the inventory using standard Python dictionary key access. It also prints the total number of hosts. ```python # Import modules from nornir import InitNornir from nornir.core.filter import F # Initialise nornir nr = InitNornir(config_file="filtering_deep_dive/config.yaml") # Print the number of hosts in the inventory print(f"Number of hosts in entire inventory: {len(nr.inventory.hosts)}") # Access the host lab-csr-011.lab.norn.local using standard python key methods single_host = nr.inventory.hosts['lab-csr-011.lab.norn.local'] # Print out the host print(f"Single host: {single_host}") ``` -------------------------------- ### Execute Greeter Task with Processors Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/processors.ipynb Executes the greeter task using `nr_with_processors`, demonstrating the use of the `PrintResult` processor to display output for 'hi!' and 'bye!' greetings. ```python nr_with_processors.run( name="hi!", task=greeter, greet="hi", ) nr_with_processors.run( name="bye!", task=greeter, greet="bye", ) ``` -------------------------------- ### PluginRegister Class Source: https://github.com/nornir-automation/nornir/blob/main/docs/api/nornir/core/plugins/register.md The PluginRegister class manages the registration and retrieval of Nornir plugins. It provides methods to automatically register plugins, deregister specific plugins or all plugins, and to get a plugin by its registered name. ```APIDOC ## class nornir.core.plugins.register.PluginRegister ### Description Manages the registration and retrieval of Nornir plugins. ### Methods #### auto_register() Registers plugins automatically. #### deregister(name: str) Deregisters a registered plugin by its name. * **Parameters:** * **name** (str) - The name of the plugin to deregister. * **Raises:** * [nornir.core.exceptions.PluginNotRegistered](../exceptions.md#nornir.core.exceptions.PluginNotRegistered) - If the plugin with the specified name is not registered. #### deregister_all() Deregisters all registered plugins. #### get_plugin(name: str) Fetches the plugin by name if already registered. * **Parameters:** * **name** (str) - The name of the plugin to fetch. * **Returns:** * The registered plugin. * **Raises:** * [nornir.core.exceptions.PluginNotRegistered](../exceptions.md#nornir.core.exceptions.PluginNotRegistered) - If the plugin with the specified name is not registered. #### register(name: str, plugin: T) Registers a plugin with a specified name. * **Parameters:** * **name** (str) - The name of the connection plugin to register. * **plugin** (T) - The plugin class to register. * **Raises:** * [nornir.core.exceptions.PluginAlreadyRegistered](../exceptions.md#nornir.core.exceptions.PluginAlreadyRegistered) - If another plugin with the specified name was already registered. ``` -------------------------------- ### Initialize Nornir and Define Tasks Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/task_results.ipynb Initializes Nornir, filters hosts, and defines two sample tasks: 'count' and 'say'. The 'say' task includes a hardcoded exception for demonstration. ```python import logging from nornir import InitNornir from nornir.core.task import Task, Result # instantiate the nr object nr = InitNornir(config_file="config.yaml") # let's filter it down to simplify the output cmh = nr.filter(site="cmh", type="host") def count(task: Task, number: int) -> Result: return Result( host=task.host, result=f"{ [n for n in range(0, number)] }" ) def say(task: Task, text: str) -> Result: if task.host.name == "host2.cmh": raise Exception("I can't say anything right now") return Result( host=task.host, result=f"{task.host.name} says {text}" ) ``` -------------------------------- ### InitNornir Source: https://github.com/nornir-automation/nornir/blob/main/docs/api/nornir/__init__.md Initializes and configures the Nornir object. This is the primary entry point for using Nornir. ```APIDOC ## InitNornir ### Description Initializes and configures the Nornir object. This is the primary entry point for using Nornir. ### Method N/A (Constructor) ### Endpoint N/A (Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **config_file** (str) - Optional - Path to the configuration file. * **dry_run** (bool) - Optional - Whether to simulate changes or not. * **configure_logging** (bool) - Optional - Whether to configure logging or not. This argument is being deprecated. Please use logging.enabled parameter in the configuration instead. * **kwargs** (Any) - Extra information to pass to the [`nornir.core.configuration.Config`](core/configuration.md#nornir.core.configuration.Config) object. ### Request Example None (Constructor) ### Response #### Success Response Returns a fully instantiated and configured Nornir object. #### Response Example ```python nornir.core.Nornir ``` ``` -------------------------------- ### Running a Task and Checking for Failures Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/failed_tasks.ipynb Executes the 'greet_and_count' task with a number and demonstrates how to check if any tasks failed using the 'failed' attribute. ```python result = cmh.run( task=greet_and_count, number=5, ) ``` ```python result.failed ``` -------------------------------- ### Configure Nornir with YAML Source: https://github.com/nornir-automation/nornir/blob/main/docs/configuration/index.md Set up Nornir using a YAML configuration file. This method is less preferred than programmatic configuration but more preferred than environment variables. ```yaml --- inventory: plugin: SimpleInventory options: host_file: "advanced_filtering/inventory/hosts.yaml" group_file: "advanced_filtering/inventory/groups.yaml" runner: plugin: threaded options: num_workers: 20 ``` -------------------------------- ### Filter for 'junos' Platform using 'eq' Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Initializes Nornir and filters inventory to include only devices with the platform set to 'junos' using the 'eq' (equals) operator. Displays the hostname and platform for each matching device. ```python # Import modules from nornir import InitNornir from nornir.core.filter import F # Initialise nornir nr = InitNornir(config_file="filtering_deep_dive/config.yaml") # Use Case 1 - eq operation # Filter for equals platform of "junos" junos_devices = nr.filter(F(platform__eq="junos")) # Print seperator and header print("=" * 50) print("All junos devices - using eq operation") # Iterate over filtered results and printout information for host, data in junos_devices.inventory.hosts.items(): print( f"Host: {host} " + f"- Platform: {data.platform}" ) # Print total and seperator print(f"Total: {len(junos_devices.inventory.hosts.items())}") print("=" * 50) ``` -------------------------------- ### Boilerplate and Helper Tasks Source: https://github.com/nornir-automation/nornir/blob/main/docs/tutorial/failed_tasks.ipynb Sets up Nornir, defines helper tasks 'count' and 'say', and includes a task 'say' that intentionally raises an exception for demonstration. ```python import logging from nornir import InitNornir from nornir.core.task import Task, Result from nornir_utils.plugins.functions import print_result # instantiate the nr object nr = InitNornir(config_file="config.yaml") # let's filter it down to simplify the output cmh = nr.filter(site="cmh", type="host") def count(task: Task, number: int) -> Result: return Result( host=task.host, result=f"{ [n for n in range(0, number)] }" ) def say(task: Task, text: str) -> Result: if task.host.name == "host2.cmh": raise Exception("I can't say anything right now") return Result( host=task.host, result=f"{task.host.name} says {text}" ) ``` -------------------------------- ### Initialize Nornir Programmatically Source: https://github.com/nornir-automation/nornir/blob/main/docs/configuration/index.md Configure Nornir by passing a dictionary of options directly in the code. This method has the highest precedence. ```python nr = InitNornir( runner={"plugin": "threaded", "options": {"num_workers": 20}}, logging={"log_file": "mylogs", "level": "DEBUG"} ) ``` -------------------------------- ### Filter Devices by Vendor, Device Type, and Site Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Demonstrates sequential filtering of Nornir inventory to isolate devices based on vendor, device type, and a specific site name. ```python # Initialise nornir nr = InitNornir(config_file="filtering_deep_dive/config.yaml") # Filter all devices for Cisco devices cisco_devices = nr.filter(vendor="cisco") # Print seperator and header print("=" * 50) print("All cisco devices") # Iterate over filtered results and printout information for host, data in cisco_devices.inventory.hosts.items(): print( f"Host: {host} " + f"- Vendor: {data['vendor']}" ) # Print total and seperator print(f"Total: {len(cisco_devices.inventory.hosts.items())}") print("=" * 50) # Filter all Cisco devices for Cisco switches cisco_switches = cisco_devices.filter(device_type="switch") # Print seperator and header print("=" * 50) print("All cisco switches") # Iterate over filtered results and printout information for host, data in cisco_switches.inventory.hosts.items(): print( f"Host: {host} " + f"- Device Type: {data['device_type']}" ) # Print total and seperator print(f"Total: {len(cisco_switches.inventory.hosts.items())}") print("=" * 50) # Filter all Cisco switches for Christchurch switches chc_cisco_switches = cisco_switches.filter(full_name="Christchurch") # Print seperator and header print("=" * 50) print("All Christchuch cisco switches") # Iterate over filtered results and printout information for host, data in chc_cisco_switches.inventory.hosts.items(): print( f"Host: {host} \n" + " " * 8 + f"- Vendor: {data['vendor']}\n" + " " * 8 + f"- Device Type: {data['device_type']}\n" + " " * 8 + f"- Site Name: {data['full_name']}" ) # Print total and seperator print(f"Total: {len(chc_cisco_switches.inventory.hosts.items())}") print("=" * 50) ``` -------------------------------- ### nornir.init_nornir.load_runner Source: https://github.com/nornir-automation/nornir/blob/main/docs/api/nornir/init_nornir.md Loads the runner plugin based on the provided configuration. ```APIDOC ## nornir.init_nornir.load_runner ### Description Loads the runner plugin based on the provided configuration. ### Method `load_runner` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response * **RunnerPlugin object** (`nornir.core.plugins.runners.RunnerPlugin`) - The loaded runner plugin. #### Response Example None ``` -------------------------------- ### Initialize Nornir and Run Task Automatically Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/handling_connections.ipynb Initializes Nornir with a configuration file and runs a task (napalm_get) to retrieve facts from a filtered set of hosts. Connections are handled automatically. ```python from nornir import InitNornir from nornir_napalm.plugins.tasks import napalm_get import pprint ``` ```python nr = InitNornir(config_file="handling_connections/config.yaml") rtr = nr.filter(name="rtr00") r = rtr.run( task=napalm_get, getters=["facts"] ) pprint.pprint(r["rtr00"][0].result) ``` -------------------------------- ### Initialize Nornir Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Initializes Nornir with a specified configuration file. This is a prerequisite for performing inventory filtering operations. ```python # Import modules from nornir import InitNornir # Initialise nornir nr = InitNornir(config_file="filtering_deep_dive/config.yaml") ``` -------------------------------- ### Filter devices in a list of platforms Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Demonstrates filtering devices where the 'platform' attribute is present in the provided list: ['eos', 'paloalto_panos', 'junos']. This is useful for selecting devices from a predefined set of platforms. ```python print(f"Total: {len(eos_prod_mel.inventory.hosts.items())}") print("=" * 50) for host, data in eos_prod_mel.inventory.hosts.items(): if data.platform in ['eos', 'paloalto_panos', 'junos']: print(f"Host: {host} - Platform: {data.platform}") print(f"Total: {len(eos_prod_mel.inventory.hosts.items())})") print("=" * 50) ``` -------------------------------- ### Register Inventory Plugin via pyproject.toml (uv) Source: https://github.com/nornir-automation/nornir/blob/main/docs/plugins/index.md Register an inventory plugin using entry points in your pyproject.toml file when using a standards-based build tool like uv. 'PATH' specifies the plugin type and 'NAME' is the plugin's identifier. ```toml [project.entry-points."PATH"] NAME = "path.to:Plugin" ``` -------------------------------- ### Host Class Methods Source: https://github.com/nornir-automation/nornir/blob/main/docs/api/nornir/core/inventory.md Provides details on methods available for the Host class, including connection management, data retrieval, and inheritance. ```APIDOC ## Host Class Methods ### close_connection(connection: str) -> None #### Description Close the connection. ### close_connections() -> None ### dict() -> Dict[str, Any] ### extended_data() -> Dict[str, Any] #### Description Returns the data associated with the object including inherited data. ### get(item: str, default: Any = None) -> Any #### Description Returns the value `item` from the host or hosts group variables. #### Parameters * **item** (`str`) – The variable to get * **default** (`any`) – Return value if item not found ### get_connection(connection: str, configuration: [Config](configuration.md#nornir.core.configuration.Config)) -> Any #### Description The function of this method is twofold: > 1. If an existing connection is already established for the given type return it > 2. If none exists, establish a new connection of that type with default parameters > and return it #### Raises: **AttributeError** – if it’s unknown how to establish a connection for the given type #### Parameters: **connection** – Name of the connection, for instance, netmiko, paramiko, napalm… #### Returns: An already established connection ### get_connection_parameters(connection: str | None = None) -> [ConnectionOptions](#nornir.core.inventory.ConnectionOptions) ### has_parent_group(group: str | [Group](#nornir.core.inventory.Group)) -> bool #### Description Returns whether the object is a child of the [`Group`](#nornir.core.inventory.Group) `group` ### items() -> ItemsView[str, Any] #### Description Returns all the data accessible from a device, including the one inherited from parent groups ### keys() -> KeysView[str] #### Description Returns the keys of the attribute `data` and of the parent(s) groups. ### open_connection(connection: str, configuration: [Config](configuration.md#nornir.core.configuration.Config), hostname: str | None = None, username: str | None = None, password: str | None = None, port: int | None = None, platform: str | None = None, extras: Dict[str, Any] | None = None, default_to_host_attributes: bool = True) -> [ConnectionPlugin](plugins/connections.md#nornir.core.plugins.connections.ConnectionPlugin) #### Description Open a new connection. If `default_to_host_attributes` is set to `True` arguments will default to host attributes if not specified. #### Raises: **AttributeError** – if it’s unknown how to establish a connection for the given type #### Returns: An already established connection ### *classmethod* schema() -> Dict[str, Any] ### values() -> ValuesView[Any] #### Description Returns the values of the attribute `data` and of the parent(s) groups. ``` -------------------------------- ### Accessing Host Data Source: https://github.com/nornir-automation/nornir/blob/main/docs/howto/filtering_deep_dive.ipynb Demonstrates how to access and print specific data attributes from a Nornir host object. Requires a Nornir inventory to be initialized. ```python print(f"Displaying data for host: {single_host}") # Access the site_code value, nested under the data key single_host_site_code = single_host.dict()["data"]["site_code"] print(f"Site code is: {single_host_site_code}") # Access the platform value single_host_platform = single_host.dict()["platform"] print(f"Platform is: {single_host_platform}") # Access the os_version value, nested under the data key single_host_os_version = single_host.dict()["data"]["os_version"] print(f"OS Version is: {single_host_os_version}") ``` -------------------------------- ### Importing InitNornir Source: https://github.com/nornir-automation/nornir/blob/main/docs/upgrading/1_to_2.md Shows the updated import path for InitNornir in Nornir 2.x. ```python from nornir.core import InitNornir ``` ```python from nornir import InitNornir ```