### Install from PyPI Source: https://github.com/aruba/pyedgeconnect/blob/main/README.md Install the package using pip and verify the installation. ```bash $ pip install pyedgeconnect ... $ pip list Package Version ----------------------------- -------------------------------- ... ... pyedgeconnect x.y.z ... ... ``` -------------------------------- ### Install with Development Extras Source: https://github.com/aruba/pyedgeconnect/blob/main/README.md Install the package with additional development tools like black, flake8, and sphinx. ```bash $ pip install pyedgeconnect[dev] or $ pip install git+https://github.com/aruba/pyedgeconnect#egg=pyedgeconnect[dev] ``` -------------------------------- ### Install from GitHub Source: https://github.com/aruba/pyedgeconnect/blob/main/README.md Install the most recent version of the package directly from the GitHub repository. ```bash $ pip install git+https://github.com/aruba/pyedgeconnect ... $ pip list Package Version ----------------------------- -------------------------------- ... ... pyedgeconnect x.y.z ... ... ``` -------------------------------- ### Install pyedgeconnect from PyPI Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/install.rst Install the package using pip and verify the installation with pip list. ```bash $ pip install pyedgeconnect ... $ pip list Package Version ----------------------------- -------------------------------- ... ... pyedgeconnect x.y.z ... ... ``` -------------------------------- ### Install pyedgeconnect from GitHub Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/install.rst Install the latest version of the package directly from the GitHub repository. ```bash $ pip install git+https://github.com/aruba/pyedgeconnect ... $ pip list Package Version ----------------------------- -------------------------------- ... ... pyedgeconnect x.y.z ... ... ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/install.rst Clone the repository, install development dependencies, and generate HTML documentation. ```bash $ git clone https://github.com/aruba/pyedgeconnect.git $ cd pyedgeconnect $ pip install .[dev] $ cd docs $ make html ``` -------------------------------- ### Start the demo infrastructure with docker-compose up -d Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Starts the demo containers and begins telemetry collection. If the user is not in the docker group and uses sudo, add the -E flag to pass host environment variables, e.g., sudo -E docker-compose up -d. Host environment variables take precedence over those in the .env file. ```bash $ docker-compose up -d ``` -------------------------------- ### Install Python dependencies for boost_timeseries example Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/boost_timeseries.rst Installs the required Python packages, including pyedgeconnect and pandas, as listed in the requirements.txt file in the boost_timeseries example directory. ```python pip install -r requirements.txt ``` -------------------------------- ### Example limit_appliances.json with appliance_subset Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Example contents where telemetry is limited to two appliances: REAL-HOSTNAME-01 and REAL-HOSTNAME-02, as specified under the appliance_subset key. ```python { "appliance_subset": [ "REAL-HOSTNAME-01", "REAL-HOSTNAME-02" ], "example": [ "Hostname-01", "SITE-HQ-02", "MyAppliance-A" ], "comment": "List of appliance hostnames to limit telemetry collection to" } ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/aruba/pyedgeconnect/blob/main/README.md Commands to clone the repository, install development dependencies, and generate HTML documentation. ```bash git clone https://github.com/aruba/pyedgeconnect.git cd edgeconnect-python pip install .[dev] cd docs make html ``` -------------------------------- ### Setup Python Virtual Environment Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/install.rst Create and activate a virtual environment to isolate project dependencies. ```bash :~$ python3.9 -m venv my_new_project :~$ source my_new_project/bin/activate (my_new_project) :~$ python3 --version Python 3.9.13 ``` -------------------------------- ### Render Dashboard to PNG via cURL (Example) Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Example cURL command with concrete values for rendering the EdgeConnect telemetry dashboard. The rendered dashboard is downloaded to the specified file. ```bash $ curl "http://my.docker.lab:3000/render/d/ec-appliance/edgeconnect-telemetry?orgId=1&var-db_bucket=ECTELEM&var-ec_hostname=SantaClara1-Jaurigui&var-tunnel_analysis_peer=to_WEST2-AWS_RECREATIONAL&var-wan_labels=All&var-lan_interfaces=All&from=now-1h&to=now&width=1640&height=5400" -H 'Authorization: Bearer abc123456789' --compressed > EC_DASHBOARD.png ``` -------------------------------- ### Output of API key prompt Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Example output showing the prompt and the entered API key. ```text Output: Please enter Orchestrator API key: 39c7ef4fc156481fb8866a5305b815164bf841c501dd401886a6ada0b2a9280a131a1757acd947a99b61cf83c7b209a3fda964ee33334ece82fd2e0aebf7107f ``` -------------------------------- ### Install required dependencies Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/generate_preconfig.rst Install the necessary Python packages, either via the requirements file or individually. ```bash pip install -r requirements.txt # OR pip install pyedgeconnect pip install jinja2 ``` -------------------------------- ### Setup Python Virtual Environment Source: https://github.com/aruba/pyedgeconnect/blob/main/README.md Create and activate a virtual environment to manage project dependencies for Python 3.7+. ```bash :~$ python3.9 -m venv my_new_project :~$ source my_new_project/bin/activate (my_new_project) :~$ python --version Python 3.9.13 ``` -------------------------------- ### Output of Orchestrator URL prompt Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Example output showing the prompt and the entered value. ```text Output: Please enter FQDN or IP of Orchestrator: 192.168.102.12 ``` -------------------------------- ### Install specific branch from GitHub Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/install.rst Install a specific branch of the package using the @branch syntax. ```bash $ pip install git+https://github.com/aruba/pyedgeconnect@ # Install the Development branch $ pip install git+https://github.com/aruba/pyedgeconnect@development ``` -------------------------------- ### Usage of get_api_key Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/release-notes/0.16.0-a1.rst Example of calling the get_api_key function with a name parameter. ```default orch.get_api_key(name="myKey") ``` -------------------------------- ### Output of Orchestrator version Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Example output showing the Orchestrator version. ```text Output: Orchestrator version: 9.5 ``` -------------------------------- ### Install Specific Branch from GitHub Source: https://github.com/aruba/pyedgeconnect/blob/main/README.md Install a specific branch of the package using the @branch syntax. ```bash $ pip install git+https://github.com/aruba/pyedgeconnect@ ... # Install the Development branch $ pip install git+https://github.com/aruba/pyedgeconnect@development ... ``` -------------------------------- ### Run script with appliance and label arguments Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/update_port_forwarding.rst Command-line invocation of the script with the appliance management IP and WAN label. This example uses -a 198.51.100.254 and -l INET1. ```bash $ python update_port_forwarding_from_dhcp.py -a 198.51.100.254 -l INET1 ``` -------------------------------- ### Successful and Failed Preconfig Upload Output Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Example output showing successful uploads for three devices and a validation failure for one device. ```text Output: Posted EC Preconfig EDGECONNECT1 Posted EC Preconfig EDGECONNECT2 Posted EC Preconfig EDGECONNECT3 Preconfig for WacoEC1 failed validation | error: Appliance region invalid: US. Valid regions are: [NewMexico, Texas] ``` -------------------------------- ### Example log messages for two appliances Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Example error log messages for appliances EC-01 and EC-02, showing login failure and ping failure. The log format is: - - cid: - @ - : . ```default 2022-09-12 22:03:33,033 - ERROR - cid: de11e3d0706e - EC-01 @ 10.41.2.125 - 2.8259: FAILED TO LOGIN 2022-09-12 22:03:34,271 - ERROR - cid: 1aa54222ea6b - EC-02 @ 10.41.0.70 - 4.0705: FAILED TO PING APPLIANCE -- ping response code: 256 ``` -------------------------------- ### Python packages installed in Ubuntu containers (requirements.txt) Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Lists the Python packages installed in the Ubuntu-based containers as documented in app/ec-telemetry/requirements.txt. Includes pyedgeconnect, influxdb_client, click, Redis, rq, and rq-dashboard with version constraints. ```default pyedgeconnect influxdb_client == 1.30.0 click >=7,<8 Redis == 4.3.4 rq == 1.11.0 rq-dashboard== 0.6.1 ``` -------------------------------- ### Run optional monitoring stack with multiple compose files Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Starts the additional cAdvisor and Prometheus containers for monitoring resource utilization, along with a Grafana dashboard. Specify multiple compose files using -f. ```bash $ docker-compose -f docker-compose.yml -f docker-compose.monitor.yml up -d ``` -------------------------------- ### Output of printed Orchestrator URL Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Example output showing the printed value. ```text Output: 192.168.102.12 ``` -------------------------------- ### Retrieve deployment and find WAN interface with DHCP IP Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/update_port_forwarding.rst Gets the appliance deployment and iterates through WAN labels to find the label ID matching the target label. Then searches interfaces for a subinterface with that label and DHCP enabled, storing the WAN IP. Exits if label not found. ```python # Get deployment detail from appliance deployment = ec.get_appliance_deployment() # Identify WAN label ID from label name provided by user for wan_label in deployment["sysConfig"]["ifLabels"]["wan"]: if wan_label["name"] == target_label: label_id = wan_label["id"] break else: label_id = None if label_id is None: print(f"WAN label {target_label} not present on {hostname}") exit() # Find WAN IP address of corresponding interface with WAN label that is # configured with DHCP for interface in deployment["modeIfs"]: for subinterface in interface["applianceIPs"]: if subinterface["label"] == label_id and subinterface["dhcp"] is True: wan_ip = subinterface["ip"] break else: wan_ip = None ``` -------------------------------- ### Clone the pyedgeconnect repository Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/index.rst Use this command to clone the pyedgeconnect repository from GitHub, which contains all example scripts and documentation. ```bash $ git clone https://github.com/aruba/pyedgeconnect.git ``` -------------------------------- ### Clone pyedgeconnect Repository Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/update_port_forwarding.rst Clones the pyedgeconnect repository from GitHub, which contains all published examples. ```bash $ git clone https://github.com/aruba/pyedgeconnect.git ``` -------------------------------- ### PEP585 Type Hinting Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/code_formatting.rst Examples of function parameter and return type hinting using Python 3.9+ generic types. ```default def my_func(my_var: str) -> dict: ... # or def my_func(my_var: list[int]) -> list: ... ``` -------------------------------- ### GET /Location Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_sse_orchestration.rst Retrieves existing Locations configured in the SSE service. ```APIDOC ## GET /Location ### Description Gets existing Locations configured in SSE service. ### Method GET ### Endpoint /Location ``` -------------------------------- ### Run Flake8 CLI Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/code_formatting.rst Commands to execute flake8 against the pyedgeconnect modules or examples from the root directory. ```bash $ flake8 pyedgeconnect # or $ flake8 examples ``` -------------------------------- ### GET /Tunnel Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_sse_orchestration.rst Retrieves existing IPSEC Tunnels configured in the SSE service. ```APIDOC ## GET /Tunnel ### Description Gets existing IPSEC Tunnels configured in SSE service. ### Method GET ### Endpoint /Tunnel ``` -------------------------------- ### Docstring Line Length Exception Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/code_formatting.rst Example of using # noqa: W505 to bypass the 72-character limit for long strings in docstrings. ```default """docstring .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - login - GET - /long_endpoint/path/{that_cannot}/be/wrapped/over_multiple_lines ... """ # noqa: W505 ``` -------------------------------- ### Validation Failure Output Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Example output when validation fails, showing HTTP 400 and an error message about an invalid appliance region. ```text Output: [POST] /gms/appliance/preconfiguration/validate | Received HTTP 400 | Response text: Appliance region invalid: US. Valid regions are: [NewMexico, Texas] ``` -------------------------------- ### Stop telemetry workers only Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Stops all telemetry collection workers while keeping other containers running to continue exploring collected data. Uses a filter on container names starting with ec-telemetry*. ```bash $ docker container stop $(docker container ls -q --filter name="ec-telemetry*") ``` -------------------------------- ### Set up and activate virtual environment Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig_from_existing_appliance/README.md Creates a Python virtual environment and activates it. The activation commands differ for macOS/Linux and Windows. ```bash python -m venv venv source venv/bin/activate # On macOS/Linux venv\Scripts\activate # On Windows ``` -------------------------------- ### Configure new service, associate all appliances, and configure SSE Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_sse_orchestration.rst Runs the script to configure a new service, associate all appliances, and configure respective locations/tunnels on the SSE service. ```bash python ec_sse_quickstart.py -af all -cso -as -sse ``` -------------------------------- ### Run the main script Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig_from_existing_appliance/README.md Executes the main.py script to generate the preconfig YAML file. ```bash python main.py ``` -------------------------------- ### Run preconfig.py with upload flag Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/generate_preconfig.rst Executes the script to generate preconfigs and upload them to Orchestrator by setting the -u flag to True. ```bash python preconfig.py -c new_preconfigs.csv -u True ``` -------------------------------- ### Collect data for all appliances Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/wan_util_95th.rst Run the script to collect data for all appliances. Requires the -c flag. ```bash python wan_util_95th.py -c ``` -------------------------------- ### Enable Logging for Orchestrator and EdgeConnect Source: https://github.com/aruba/pyedgeconnect/blob/main/README.md Demonstrates how to instantiate Orchestrator and EdgeConnect classes with logging enabled for files, console, and successful API responses. ```python orch_url = 'orchestrator.example.com' orch = Orchestrator(orch_url, log_file=True, log_console=True) # or ecos_url = '10.2.30.50' ec = EdgeConnect(ecos_url, log_success=True) ``` -------------------------------- ### Render Dashboard to PNG via GUI URL Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Navigate to this URL in a browser to render a dashboard or panel to a PNG image. Replace the placeholders (DOCKER_HOST, DASHBOARD_UID, DASHBOARD_NAME, APPLIANCE_HOSTNAME, PEER_TUNNEL_NAME) with appropriate values. ```default http://${DOCKER_HOST}:3000/render/d/${DASHBOARD_UID}/${DASHBOARD_NAME}?orgId=1&var-db_bucket=ECTELEM&var-ec_hostname=${APPLIANCE_HOSTNAME}&var-tunnel_analysis_peer=${PEER_TUNNEL_NAME}&var-wan_labels=All&var-lan_interfaces=All&from=now-1h&to=now&width=1640&height=5400 ``` -------------------------------- ### Enable Logging for Orchestrator and EdgeConnect Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/logging.rst Demonstrates how to enable console logging with success response logging for Orchestrator, and file logging for EdgeConnect. ```python orch_url = 'orchestrator.example.com' orch = Orchestrator(orch_url, log_console=True, log_success=True) # or ecos_url = '10.2.30.50' ec = EdgeConnect(ecos_url, log_file=True) ``` -------------------------------- ### Report data for all existing files Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/wan_util_95th.rst Run the reporting/analysis portion of the script to analyze previously collected data files for all appliances. ```bash python wan_util_95th.py -r ``` -------------------------------- ### Calculate system deployment and license utilization percentages Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/wan_util_95th.rst Computes 95th percentile utilization percentages for system deployment and license values. Uses rx_bytes and tx_bytes converted to bits per minute, divided by system_max_inbound/outbound or license values, multiplied by 100, and rounded to 2 decimals. ```python system_df["system_dep_pct_inbound"] = round( ( (system_df["rx_bytes"] * 8 / 60) / (system_df["system_max_inbound"] * 1000) ) * 100, 2, ) system_df["system_dep_pct_outbound"] = round( ( (system_df["tx_bytes"] * 8 / 60) / (system_df["system_max_outbound"] * 1000) ) * 100, 2, ) system_df["system_lic_pct_inbound"] = round( ( (system_df["rx_bytes"] * 8 / 60) / (system_df["license"] * 1000) ) * 100, 2, ) system_df["system_lic_pct_outbound"] = round( ( (system_df["tx_bytes"] * 8 / 60) / (system_df["license"] * 1000) ) * 100, 2, ) ``` -------------------------------- ### Collect data for all appliances Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/boost_timeseries.rst Run the script without specific appliance filters to collect data for all appliances. ```bash python boost_timeseries.py ``` -------------------------------- ### Initialize Orchestrator Source: https://github.com/aruba/pyedgeconnect/blob/main/README.md Initialize the Orchestrator instance. Set verify_ssl to False if connecting without a valid certificate. ```python orch_url = '10.1.1.100' orch_url = 'orchestrator.example.com' orch = Orchestrator(orch_url, verify_ssl=False) ``` -------------------------------- ### Configure SSE tunnels for all appliances Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_sse_orchestration.rst Runs the script to configure respective locations/tunnels on the SSE service for all appliances of an existing service. ```bash python ec_sse_quickstart.py -af all -sse ``` -------------------------------- ### Initialize Orchestrator and EdgeConnect instances Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/quickstart.rst Instantiate Orchestrator with an IP or FQDN. Set verify_ssl=False when connecting to an Orchestrator without a valid certificate to ignore certificate warnings/errors. ```python orch = Orchestrator('10.1.1.100') # or orch = Orchestrator('orchestrator.example.com', verify_ssl=False) ec = EdgeConnect('10.2.30.50') # or ec = EdgeConnect('edgeconnect.example.com', verify_ssl=False) ``` -------------------------------- ### Associate single appliance and configure SSE Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_sse_orchestration.rst Runs the script to associate a single appliance to an existing service and configure respective locations/tunnels on the SSE service. ```bash python ec_sse_quickstart.py -af hostname:My-Appliance-01 -as -sse ``` -------------------------------- ### Initialize EdgeConnect Source: https://github.com/aruba/pyedgeconnect/blob/main/README.md Initialize the EdgeConnect instance. Set verify_ssl to False if connecting without a valid certificate. ```python ecos_url = '10.2.30.50' ecos_url = 'edgeconnect.example.com' ec = EdgeConnect(ecos_url, verify_ssl=False) ``` -------------------------------- ### Set output directory for preconfig YAML files Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Creates a local directory 'preconfig_outputs/' if it does not exist, to store generated preconfig YAML files. ```python # Local directory for configuration outputs output_directory = "preconfig_outputs/" if not os.path.exists(output_directory): os.makedirs(output_directory) ``` -------------------------------- ### Collect data for a single appliance Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/boost_timeseries.rst Use the -a flag to specify a single appliance hostname for data collection. ```bash python boost_timeseries.py -a MY-appliance-01 ``` -------------------------------- ### Initialize Orchestrator with API Key Source: https://github.com/aruba/pyedgeconnect/blob/main/README.md Authenticate using an API key during initialization to avoid manual login/logout calls. ```python orch_url = 'orchestrator.example.com' orch = Orchestrator(orch_url, api_key='xxx') ``` -------------------------------- ### Collect data for a single appliance Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/wan_util_95th.rst Run the script to collect data for a single appliance, specified by hostname with -a. ```bash python wan_util_95th.py -c -a MY-appliance-01 ``` -------------------------------- ### Load Jinja2 template for EdgeConnect Preconfig Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Sets up a Jinja2 environment with trim_blocks and lstrip_blocks to reduce whitespace, and loads the template file 'ec_preconfig_template.jinja2' from the 'templates' directory. ```python ec_template_file = 'ec_preconfig_template.jinja2' env = Environment( loader=FileSystemLoader("templates"), trim_blocks=True, lstrip_blocks=True, ) ec_template = env.get_template(ec_template_file) ``` -------------------------------- ### Package Directory Structure Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/package_structure.rst Visual representation of the pyedgeconnect directory hierarchy, showing the separation of ecos and orch modules. ```default └── pyedgeconnect ├── __init__.py ├── ecos │   ├── __init__.py │   ├── <_ecos_function_group>.py │   └── ... └── orch ├── __init__.py ├── <_orch_function_group>.py └── ... ``` -------------------------------- ### appliance_post_api: version-aware endpoint construction Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/sdk_logic.rst Constructs the API endpoint path based on the Orchestrator version (9.3+ vs pre-9.3) and sends a POST request. Uses self.orch_version to choose between query parameter and path parameter syntax. ```python def appliance_post_api( self, ne_pk: str, url: str, data, ) -> dict: """""" if self.orch_version >= 9.3: path = f"/appliance/rest?nePk={ne_pk}&url={url}" else: path = f"/appliance/rest/{ne_pk}/{url}" return self._post( path, data=data, expected_status=[200, 204], return_type="bool", ) ``` -------------------------------- ### Run preconfig.py with required CSV argument Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/generate_preconfig.rst Executes the script using only the mandatory CSV source file argument. ```bash python preconfig.py -c new_preconfigs.csv ``` -------------------------------- ### Demo directory structure Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Shows the file layout of the ec-telemetry demo, including the app containers, Grafana dashboards, and Docker Compose files. ```default ├── app │ ├── ec-telemetry │ │ ├── ec_discover.py │ │ ├── ec_telemetry.py │ │ ├── limit_appliances.json │ │ └── requirements.txt │ ├── grafana │ │ ├── dashboards │ │ │ ├── boost_utilization.json │ │ │ ├── demo_monitor.json │ │ │ ├── ec_appliance.json │ │ │ └── wan_utilization.json │ │ └── provisioning │ │ ├── dashboards │ │ │ └── dashboard_provider.yml │ │ └── datasources │ │ └── datasources.yml │ ├── grafana_render │ │ └── config.json │ └── prometheus │ └── prometheus.yml ├── demo_cleanup.sh ├── docker-compose.monitor.yml ├── docker-compose.yml ├── Dockerfile └── example.env ``` -------------------------------- ### Import necessary Python libraries Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Imports csv, datetime, os, Jinja2 Environment and FileSystemLoader, and the Orchestrator class from pyedgeconnect. ```python import csv import datetime import os from jinja2 import Environment, FileSystemLoader from pyedgeconnect import Orchestrator ``` -------------------------------- ### Generate and Validate Preconfigs from CSV Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Iterates over each row in a CSV file, renders a YAML preconfig using a Jinja template, validates it via the Orchestrator, and optionally uploads it. Writes local YAML files for both successful and failed validations. Requires a CSV file with headers including 'hostname' and 'appliance_serial', and an initialized Orchestrator object 'orch'. ```python # Open CSV file with configuration data and iterate over each row and generate a preconfig per device (row) upload_to_orch = True csv_filename = 'preconfig.csv' with open(csv_filename, encoding="utf-8-sig") as csvfile: csv_dict = csv.DictReader(csvfile) # Set initial row number for row identification of data # First row is headers row_number = 2 # Generate Edge Connect YAML preconfig for each row in data for row in csv_dict: # Render CSV values through the Jinja template yaml_preconfig = ec_template.render(data=row) # Set value for serial number if provided appliance_serial = row.get("appliance_serial") if appliance_serial is None: appliance_serial = "" else: pass # Validate preconfig via Orchestrator validate = orch.validate_preconfig( preconfig_name=row["hostname"], yaml_preconfig=yaml_preconfig, auto_apply=True, ) # Write local YAML file to see resulting YAML file locally # whether or not validation passes or fails yaml_filename = f'{row["hostname"]}_preconfig.yml' with open(output_directory + yaml_filename, "w") as preconfig_file: write_data = preconfig_file.write(yaml_preconfig) # If the validate function passes on Orchestrator, move on # to check if uploading to Orchestrator option selected if validate.status_code == 200: # If upload option was chosen, upload preconfig to # Orchestrator with selected auto-apply settings if upload_to_orch is True: # In this example the appliance hostname from the CSV # data (row["hostname"]) is used both for the name of # the preconfig to appear in Orchestrator, as well as # the tag on the preconfig that could be used to match # against a discovered appliance # Additionally a comment is added with the current # date comment_timestamp = datetime.date.today().strftime("%d %B %Y") orch.create_preconfig( preconfig_name=row["hostname"], yaml_preconfig=yaml_preconfig, auto_apply=True, tag=row["hostname"], serial_number=appliance_serial, comment=f"Created/Uploaded @ {comment_timestamp}", ) print(f'Posted EC Preconfig {row["hostname"]}') else: pass else: print( f'Preconfig for {row["hostname"]}' f" failed validation | error: {validate.text}" ) # Write local YAML file of failed config for reference yaml_filename = f'{row["hostname"]}_preconfig-FAILED.yml' with open(output_directory + yaml_filename, "w") as preconfig_file: write_data = preconfig_file.write(yaml_preconfig) # Increment row number when iterating to next row in CSV row_number += 1 ``` -------------------------------- ### Update Preconfig function syntax Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/release-notes/0.15.0-a1.rst Comparison of old and new syntax for Preconfig functions, showing the parameter rename from hostname to preconfig_name and the removal of auto_apply in validate_preconfig. ```python # OLD syntax validate = orch.validate_preconfig( hostname="edgeconnect-preconfig-01", yaml_preconfig=yaml_preconfig, auto_apply=auto_apply, ) orch.create_preconfig( hostname="edgeconnect-preconfig-01", yaml_preconfig=yaml_preconfig, auto_apply=auto_apply, tag="tag value", comment="New preconfig for appliance" ) # NEW syntax validate = orch.validate_preconfig( preconfig_name="edgeconnect-preconfig-01", yaml_preconfig=yaml_preconfig, ) orch.create_preconfig( preconfig_name="edgeconnect-preconfig-01", yaml_preconfig=yaml_preconfig, auto_apply=auto_apply, tag="tag value", comment="New preconfig for appliance" ) # CODE REQUIRING NO CHANGE syntax validate = orch.validate_preconfig( "edgeconnect-preconfig-01", yaml_preconfig=yaml_preconfig, ) orch.create_preconfig( "edgeconnect-preconfig-01", yaml_preconfig=yaml_preconfig, auto_apply=auto_apply, tag="tag value", comment="New preconfig for appliance" ) ``` -------------------------------- ### Run remove-preconfig.py to delete preconfigs Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/generate_preconfig.rst Executes the removal script using the CSV file to identify which preconfigs to delete based on the hostname column. ```bash python remove-preconfig.py -c new_preconfigs.csv ``` -------------------------------- ### Login to EdgeConnect with environment variables or user input Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/update_port_forwarding.rst Sets EdgeConnect login credentials from environment variables EC_USER and EC_PW, or prompts the user. Instantiates EdgeConnect with log_console enabled and verify_ssl disabled, then logs in. ```python # Set EdgeConnect login via environment variable or user input if os.getenv("EC_USER") is not None and os.getenv("EC_PW"): ec_user = os.getenv("EC_USER") ec_pw = os.getenv("EC_PW") else: ec_user = input("EdgeConnect admin user: ") ec_pw = getpass("EdgeConnect admin password: ") # Instantiate EdgeConnect with ``log_console`` enabled for # printing log messages to terminal ec = EdgeConnect( ec_url, log_console=True, verify_ssl=False, ) ec.login(ec_user, ec_pw) ``` -------------------------------- ### Clone the repository Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig_from_existing_appliance/README.md Clones the project repository from GitHub and changes into the repository directory. ```bash git clone https://github.hpe.com/adam-wilkins/PreconfigYAMLFromExistingAppliance.git cd ``` -------------------------------- ### Update deployment interface comments Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/wan_util_95th.rst Run the script to update deployment interface comments. Combines -c and -d flags. ```bash python wan_util_95th.py -c -d ``` -------------------------------- ### Retrieve and print Orchestrator and appliance information Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/basic_examples.rst Retrieves Orchestrator system information and all appliances, then prints them in a formatted table. Logs out of Orchestrator if not using an API key. ```python # retrieve Orchestrator system information orch_info = orch.get_orchestrator_server_info() # print Orchestrator information print( """ Orchestrator Information: ------------------------------------------------------- Hostname: {} Version: {} Uptime: {} ------------------------------------------------------- """.format( orch_info["hostName"], orch_info["release"], orch_info["uptime"], ) ) # retrieve all appliances in Orchestrator appliances = orch.get_appliances() print("Appliance Information:") # print headers for table print( "\n{:^20}|{:^20}|{:^20}|{:^20}|{:^20}|{:^20}|".format( "Hostname", "Appliance ID", "Serial Num", "IP Address", "Software", "Bandwidth", ) ) # print horizontal line before appliance data print("-" * 126) # print row for each appliance with particular info attributes for appliance in appliances: print( "{:^20}|{:^20}|{:^20}|{:^20}|{:^20}|{:^20}|".format( appliance["hostName"], appliance["nePk"], appliance["serial"], appliance["IP"], appliance["softwareVersion"], appliance["systemBandwidth"], ) ) print("\n") # if not using API key, logout of Orchestrator if orchestrator_api_key == "": orch.logout() else: pass ``` -------------------------------- ### Render Dashboard to PNG via cURL (Template) Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Use this cURL command to render a Grafana dashboard or panel to a PNG image. Requires a Grafana API key or Service Account token with viewer permissions. Replace the environment variables (DOCKER_HOST, DASHBOARD_UID, DASHBOARD_NAME, APPLIANCE_HOSTNAME, PEER_TUNNEL_NAME, GRAFANA_API_TOKEN, FILENAME) with actual values. ```bash $ curl "http://${DOCKER_HOST}:3000/render/d/${DASHBOARD_UID}/${DASHBOARD_NAME}?orgId=1&var-db_bucket=ECTELEM&var-ec_hostname=${APPLIANCE_HOSTNAME}&var-tunnel_analysis_peer=${PEER_TUNNEL_NAME}&var-wan_labels=All&var-lan_interfaces=All&from=now-1h&to=now&width=1640&height=5400" -H "Authorization: Bearer ${GRAFANA_API_TOKEN}" --compressed > ${FILENAME} ``` -------------------------------- ### Prompt for Orchestrator FQDN or IP Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Prompts the user to enter the Orchestrator FQDN or IP and prints the entered value. ```python orch_url = input("Please enter FQDN or IP of Orchestrator: ") print(orch_url) ``` -------------------------------- ### Authenticate to Orchestrator Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/auth_example.rst This script demonstrates how to connect to an Orchestrator instance by prioritizing environment variables, command-line arguments, or interactive user input. It supports both API key authentication and username/password authentication with optional MFA. ```python import argparse import getpass import os from pyedgeconnect import Orchestrator # Parse runtime arguments to specify an Orchestrator IP or FQDN parser = argparse.ArgumentParser() parser.add_argument( "-o", "--orch", help="specify Orchestrator URL", type=str, ) args = parser.parse_args() # Set Orchestrator FQDN/IP via arguments, environment variable, # or user input if neither in argument or environment variable if vars(args)["orch"] is not None: orch_url = vars(args)["orch"] elif os.getenv("ORCH_URL") is not None: orch_url = os.getenv("ORCH_URL") else: orch_url = input("Orchstrator IP or FQDN: ") # Set Orchestrator API Key via environment variable or user input # Skipping will fallback to user/password authentication if os.getenv("ORCH_API_KEY") is not None: orch_api_key = os.getenv("ORCH_API_KEY") else: orch_api_key_input = input("Orchstrator API Key (enter to skip): ") if len(orch_api_key_input) == 0: orch_api_key = None # Set user and password if present in environment variable orch_user = os.getenv("ORCH_USER") orch_pw = os.getenv("ORCH_PASSWORD") else: orch_api_key = orch_api_key_input # Instantiate Orchestrator with ``log_console`` enabled for # printing log messages to terminal, and ``verify_ssl`` to False # which will not verify the web https certificate on Orchestrator orch = Orchestrator( orch_url, api_key=orch_api_key, log_console=True, verify_ssl=False, ) # If not using API key, login to Orchestrator with username/password if orch_api_key is None: # If username/password not in environment variables, prompt user if orch_user is None: orch_user = input("Enter Orchestrator username: ") orch_pw = getpass.getpass("Enter Orchestrator password: ") # Check if multi-factor authentication required mfa_prompt = input("Are you using MFA for this user (y/n)?: ") if mfa_prompt == "y": orch.send_mfa(orch_user, orch_pw, temp_code=False) token = input("Enter MFA token: ") else: token = "" # Login to Orchestrator with user/password to check auth before # proceeding confirm_auth = orch.login(orch_user, orch_pw, mfacode=token) if confirm_auth: pass else: print("Authentication to Orchestrator Failed") exit() # If API key specified, check that key is valid before proceeding else: confirm_auth = orch.get_orchestrator_hello() if confirm_auth != "There was an internal server error.": pass else: print("Authentication to Orchestrator Failed") exit() ``` -------------------------------- ### Rebuild containers with --build after changes Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Use this command to rebuild the containers after making changes to scripts or files in the app/ec-telemetry directory (e.g., limit_appliances.json). The --build option forces a rebuild. ```bash $ docker-compose up -d --build ``` -------------------------------- ### Clean up containers and volumes with demo_cleanup.sh Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Stops all containers and removes volumes using the included demo_cleanup.sh script. ```bash $ bash demo_cleanup.sh ``` -------------------------------- ### POST /Location Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_sse_orchestration.rst Creates a new Location in the SSE service. ```APIDOC ## POST /Location ### Description Creates new Location in SSE service. ### Method POST ### Endpoint /Location ``` -------------------------------- ### Run script to push rules to an appliance Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/upload_security_policy.rst Command to run the Python script, specifying the CSV file and the appliance hostname. This applies the security policy directly to the named appliance. ```bash python upload_security_policy.py -c security_policy.csv -a MY-APPLIANCE-01 ``` -------------------------------- ### Original get_api_key implementation Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/release-notes/0.16.0-a1.rst The original source code for the get_api_key function using a simple inline path. ```default return self._get(f"/apiKey/{name}") ``` -------------------------------- ### Automate SSE platform commit Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_sse_orchestration.rst Automates the commit process on the SSE platform using the SSE admin token. ```bash python sse_commit.py ``` -------------------------------- ### Import Orchestrator and EdgeConnect classes Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/quickstart.rst Import the Orchestrator and EdgeConnect classes from pyedgeconnect to begin using the library. ```python from pyedgeconnect import Orchestrator # or from pyedgeconnect import EdgeConnect ``` -------------------------------- ### Import EdgeConnect Class Source: https://github.com/aruba/pyedgeconnect/blob/main/README.md Import the EdgeConnect class to begin interacting with the EdgeConnect API. ```python from pyedgeconnect import EdgeConnect ``` -------------------------------- ### Login and logout with username/password Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/quickstart.rst Use the login method to authenticate and logout to end the session for both Orchestrator and EdgeConnect instances. ```python orch.login("username", "password") orch.logout() # or ec.login("username", "password") ec.logout() ``` -------------------------------- ### Instantiate Orchestrator with custom timeout Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/release-notes/0.15.3-a1.rst Configure the Orchestrator class with custom connect and read timeout values using the timeout tuple parameter. ```python # Instantiate Orchestrator with shorter timeout values of # 3.05 seconds for connect and 10 seconds for read orch = Orchestrator( url="192.0.2.100", api_key="abc123", timeout=(3.05,10) ) ``` -------------------------------- ### Check Orchestrator version and set self.orch_version Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/sdk_logic.rst Checks if an API key is provided and retrieves the Orchestrator version to set self.orch_version. On failure, prints an error and defaults to pre-9.3 API endpoints. ```python if api_key != "": try: orch_info = self.get_orchestrator_server_brief() release = orch_info["release"] major = int(release.split(".")[0]) minor = int(release.split(".")[1]) self.orch_version = major + minor / 10 except Exception as e: print(e) print( """ Attempt to retrieve Orchestrator version failed Defaulting logic to pre-9.3 API endpoints """ ) # Orch Version not found, default to pre-9.3 self.orch_version = 0.0 ``` -------------------------------- ### Stop all containers Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Stops all running containers in the demo. ```bash $ docker-compose stop ``` -------------------------------- ### Environment Variables Configuration (.env) Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Environment variable keys referenced by the containers. Host environment variables take precedence over values in the .env file. Sensitive values like ORCH_API_KEY, EC_PW, DB_TOKEN, and DB_PW should be set on the host to avoid committing them. DB_PW must be longer than 8 characters. ```default # It is recommended to not store sensitive auth/token information # in a static file, the below values are only present to document # the envrionment variable keys the containers will reference. # Environment variables on the host itself will take precedence # over any included here # Orch and EdgeConnect Connection Details ORCH_URL= ORCH_API_KEY= EC_USER= EC_PW= # Token for Grafana/InfluxDB Communication # DB_USER and DB_PW used to login to both Grafana/InfluxDB DB_TOKEN= DB_USER=admin # DB_PW must be > 8 characters to meet minimum requirements DB_PW= # Number of replica containers for ec-telemetry-worker WORKER_COUNT=4 # OPTIONAL SETTINGS, KEEP DEFAULTS IF UNSURE # Project name and local logging settings COMPOSE_PROJECT_NAME=EC-Telemetry LOG_LEVEL=WARNING LOG_MAX_BYTES=1000000 LOG_MAX_BACKUPS=5 # Timeout to check reachability to EdgeConnect EC_TIMEOUT=2 # Database Connection Details DB_ORG=ECTELEM DB_URL=http://influxdb:8086 DB_BUCKET=ECTELEM DB_RETENTION=3d # OPTIONAL CUSTOM DNS SERVER FOR CONTAINERS # To use, un-comment the `dns:` option for containers in docker-compose.yml # DNS_SERVER=8.8.8.8 ``` -------------------------------- ### Run script to push rules to a Template Group with merge and log level Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/upload_security_policy.rst Command to run the Python script, specifying the CSV file, a new Template Group name, and enabling merge and setting the default log level to 3. ```bash python upload_security_policy.py -c security_policy.csv -tg Group-Sec-Policy -m -dll 3 ``` -------------------------------- ### Calculate Estimated Kbps Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/boost_timeseries.rst Calculates the average Kbps of Boosted traffic for a minute by multiplying the bytes value by 0.0001333. ```python point.append(point[2] * 0.0001333) ``` -------------------------------- ### Create Orchestrator object Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Creates an Orchestrator object using the provided URL and API key, with SSL verification disabled. ```python orch = Orchestrator(orch_url, api_key=orch_api_key, verify_ssl=False) ``` -------------------------------- ### Import Orchestrator Class Source: https://github.com/aruba/pyedgeconnect/blob/main/README.md Import the Orchestrator class to begin interacting with the Orchestrator API. ```python from pyedgeconnect import Orchestrator ``` -------------------------------- ### Default limit_appliances.json Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst Default contents of the limit_appliances.json file. The appliance_subset list is empty by default, meaning telemetry is collected from the first four reachable appliances returned by pyedgeconnect.Orchestrator.get_appliances(). ```python { "appliance_subset": [], "example": [ "Hostname-01", "SITE-HQ-02", "MyAppliance-A" ], "comment": "List of appliance hostnames to limit telemetry collection to" } ``` -------------------------------- ### Print Orchestrator version Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Prints the Orchestrator version to verify data access from the Orchestrator object. ```python print(f"Orchestrator version: {orch.orch_version}") ``` -------------------------------- ### Update port forwarding rules with current WAN IP Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/update_port_forwarding.rst If a WAN IP is found, retrieves existing port forwarding rules and compares each rule's destination subnet with the WAN IP. If different, updates the destination subnet to the WAN IP with /32 and sets the updated rules on the appliance. ```python # If WAN IP found, get existing inbound port forwarding rules and update if wan_ip is not None: pfw_rules = ec.get_port_forwarding_rules() # If WAN IP is different than the destination subnet in existing # port forwarded rules, update with the current WAN IP from # deployment rule_update = False for rule in pfw_rules: if rule["destSubnet"].split("/")[0] == wan_ip: print("WAN IP is correct in PFW rule, no change") else: rule["destSubnet"] = wan_ip + "/32" print("WAN IP is different in PFW rule, updating") rule_update = True if rule_update: ec.set_port_forwarding_rules(pfw_rules=pfw_rules) ``` -------------------------------- ### Environment variables for logging configuration Source: https://github.com/aruba/pyedgeconnect/blob/main/docs/source/examples/ec_telemetry_demo.rst These environment variables control the log level, maximum file size, and number of backup log files for the telemetry containers. Defaults are ERROR, 1000000 bytes (1MB), and 5 backups. ```default LOG_LEVEL=ERROR LOG_MAX_BYTES=1000000 LOG_MAX_BACKUPS=5 ``` -------------------------------- ### Prompt for Orchestrator API key Source: https://github.com/aruba/pyedgeconnect/blob/main/examples/generate_preconfig/JupyterLab_Notebook/Generate_PreConfigs.ipynb Prompts the user to enter the Orchestrator API key. ```python orch_api_key = input("Please enter Orchestrator API key: ") ```