Skip to main content

LogicVein Script Sandbox Utils

Convenience helpers for Python scripts that LogicVein Playbooks run in the Script Sandbox container. They wrap the sandbox's file-and-stdout contract: a Playbook hands your script its inputs in in.json, and your script returns results by printing JSON to stdout.

Installation

From PyPI:

pip install lvi-script-sandbox-utils

From TestPyPI (pre-release / testing):

pip install \
  --index-url https://test.pypi.org/simple/ \
  --extra-index-url https://pypi.org/simple/ \
  lvi-script-sandbox-utils

The sandbox runs scripts in a container, so the package has to be available inside it. If your sandbox mounts a packages directory (for example ./packages:/packages), install into it:

pip install --target ./packages lvi-script-sandbox-utils

The library has no third-party dependencies (standard library only).

Usage

import lvi_script_sandbox_utils as lvi

text = lvi.get_result()                       # the previous node's output
lvi.log("checking", lvi.device.hostname)      # debugging message

lvi.set_globals(
    line_count=len(text.splitlines()),
    **lvi.device.to_globals(["hostname", "model"]),
)

Read the previous node's output

lvi.get_result() returns the previous node's result, such as a CLI command's text. In a Playbook's first script node there is none, and it returns "" (or get_result(default=...)).

Read the device

lvi.device is the Playbook's device. Its properties use LogicVein's names: hostname, ipAddress, model, osVersion, serialNumber, custom1 .. custom5, uuid, and so on (your editor can list them). It's built the first time you use it, and is the same object every time.

  • Unset values are None.
  • End-of-life/sale fields (endOfLife, endOfSale, softwareEndOfLife, softwareEndOfSale) are YYYY-MM-DD dates, and lastBackup, lastChange, lastDiscovery, lastTelemetry are YYYY-MM-DDTHH:MM:SSZ timestamps, all in UTC.
  • traits lists the device's capabilities (ssh, snmp, ncm, ...).
  • lvi.device.to_dict() gives all properties as a dict.

Read other Playbook variables

lvi.get_global("hostname")             # KeyError, listing what is set, if missing
lvi.get_global("site", default="")
lvi.get_globals()                      # all of them, as a dict
lvi.metadata.playbook                  # details of this run: playbook, executor,
lvi.metadata.execution_id              # execution_id, job_id, node, started_at, ...

Return results

Call lvi.set_globals(...) once, at the end of the script, with everything the Playbook should get back as global variables. Calling it (or set_raw()) a second time raises RuntimeError, so build up results in a dict and pass **results.

Playbook globals are strings. Numbers and booleans are fine, None is sent as "", and a list, dict, device or metadata object is sent as its JSON text, which a later script node can read back with json.loads(lvi.get_global(name)). For a different format, convert it yourself, e.g. traits=", ".join(lvi.device.traits).

To return device properties, use lvi.device.to_globals(), all of them, or to_globals(["hostname", "model"]) for some. It names hostname and network device_hostname and device_network, so they don't overwrite the Playbook's own hostname and network globals.

lvi.set_raw(text) returns text as the node's raw output instead.

Fail the node

When the script can't do its job, call lvi.fail("why") instead of set_globals(). The Playbook marks the node failed with that message, and the script stops there. Any log() messages are still returned.

An uncaught exception does the same automatically: the node fails with the error, e.g. ValueError: invalid literal for int() ... (line 4 of script.py), instead of a traceback on stderr, which would fail the run with no message.

Call the ThirdEye API and get device credentials

Once the sandbox has an API key (ssh -p 2022 root@<sandbox> setkey <key>), scripts can call the ThirdEye server's JSON-RPC API:

configs = lvi.call_api("Credentials.getAllCredentialConfigs", network="Default")

creds = lvi.get_credentials()          # what LogicVein last logged in to lvi.device with
creds.username, creds.password, creds.enablePassword, creds.protocols
lvi.get_credentials("192.0.2.12", "Default")   # another device

get_credentials() raises LookupError if LogicVein has never logged in to the device. Printing or logging a Credentials object hides its passwords, keys and community strings, and set_globals() refuses to send one. Any script in the sandbox can read every device's credentials this way, so treat the API key accordingly.

The server's TLS certificate is verified. If ThirdEye uses a self-signed certificate, save it (PEM) as thirdeye-ca.pem in the scripts volume, which the sandbox mounts at /shared, or set API_CA_FILE to its path. To run a script outside a Playbook, set API_HOST and API_KEY yourself.

Run an Ansible playbook against the device

With Ansible installed in the sandbox, a script can run a playbook against the Playbook's device, logging in with the device's LogicVein credentials:

ssh -p 2022 root@<sandbox> pip install ansible-core paramiko
ansible-galaxy collection install -p ./packages ansible.netcommon cisco.ios   # on the host
result = lvi.run_playbook("vlans.yml", {"vlan_id": 120})
if not result.ok:
    lvi.fail(result.message)
lvi.set_globals(**result.to_globals())
  • The inventory has one host, the device, so the playbook uses hosts: all. It connects with network_cli to the device's IP address, with the ansible_network_os for its adapter (Cisco::IOS is cisco.ios.ios; pass network_os= for others), and become uses the enable password.
  • A relative playbook path not in the working directory is looked for in the scripts volume (/shared). The playbook runs from its own directory, so an ansible.cfg next to it applies. Ansible checks host keys as configured there; each run starts with an empty known_hosts.
  • check=True and diff=True add --check and --diff; host_vars= adds or overrides inventory variables ({"ansible_port": 2222}).
  • result.ok, result.changed, result.message (why it failed), result.stats, result.tasks (each task's status, msg and module result), and result.task("Show version")["result"]["stdout"]. result.output is Ansible's usual text output.
  • Ansible's output is captured, so it can't break the Playbook's results. It has to finish within the sandbox's script timeout (120 s by default); run_playbook() gives up after timeout=90 seconds.

Debugging

A script can't print while it runs in a Playbook: stdout carries the results the Playbook reads, and the Script Sandbox fails the run if the script writes anything to stderr. That includes Python warnings, which go to stderr too.

Use lvi.log(...) instead. It takes the same arguments as print(), keeps the message, and set_globals() returns all of them, one per line, as the script_log global, so they show up with the node's results. Messages are lost if the script never reaches set_globals(), and set_raw() doesn't return them.

lvi.log("parsed", len(lines), "lines")
lvi.set_globals(total="61 MB")      # also sends script_log="parsed 12 lines"

To run a script outside a Playbook, save an in.json from a run and point the package at it:

LVI_SANDBOX_INPUT=./samples/in.json python my_script.py

When LVI_SANDBOX_INPUT is set, lvi.log() also prints each message to the terminal (stderr) as it happens.

lvi.load_input() returns the whole in.json as a dict, if you need something the functions above don't cover. Treat it as read-only.

Upgrading from 0.6 or earlier

0.7.0 renamed the API so that it reads the way scripts use it:

Before From 0.7.0
from logicvein import lvi_script_sandbox_utils as lvi (0.1.x) import lvi_script_sandbox_utils as lvi
get_input("cli_output") get_result()
get_input("device") load_input()["device"]
get_device(), get_full_device(), device_full device (every property)
device.device_hostname, device.device_network device.hostname, device.network
"" for unset device properties None (still sent as "" by set_globals())
get_metadata() metadata
flush_output(**values), set_output(key, value) set_globals(**values), once
flush_output(**vars(device)) set_globals(**device.to_globals())
flush_string_output(text) set_raw(text)

The package stopped shipping a logicvein/ directory in 0.2.0: it collided with lvi-api-client's, so pip install --target skipped whichever was installed second (or, with --upgrade, deleted the first).

Development and releases

See CONTRIBUTING.md for development setup and PUBLISHING.md for how releases are published.

Metadata

Release files for lvi-script-sandbox-utils 0.9.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lvi-script-sandbox-utils 0.9.0
File Size Uploaded Provenance Actions
lvi_script_sandbox_utils-0.9.0.tar.gz 31.1 kB Without provenance Details for lvi_script_sandbox_utils-0.9.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for lvi-script-sandbox-utils 0.9.0
File Interpreter ABI Platform Actions
lvi_script_sandbox_utils-0.9.0-py3-none-any.whl Python 3 none any Details for lvi_script_sandbox_utils-0.9.0-py3-none-any.whl

Total release size: 53.8 kB

Release files / lvi_script_sandbox_utils-0.9.0.tar.gz

Download URL lvi_script_sandbox_utils-0.9.0.tar.gz
Size 31.1 kB
Tags Source
SHA-256 checksum
How to use checksums
58ca5903af49d7279b114d836f6d18183ce284cd450623a0b50f7234c7ecf563
BLAKE2b-256 checksum
How to use checksums
659035ebf09f71d30941084472df417606e762c53aa2f3e1a28c9590f0e2e6dd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.10

Release files / lvi_script_sandbox_utils-0.9.0-py3-none-any.whl

Download URL lvi_script_sandbox_utils-0.9.0-py3-none-any.whl
Size 22.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a54e63c1a81859bf9fb3e415615ed33c7dbb2e9d4e6698c0738f3a92eddc2320
BLAKE2b-256 checksum
How to use checksums
28f927f1cde027cee4353b013e0519eefce0cca064939873b28033a10c0cfcfb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.10

Security for lvi-script-sandbox-utils 0.9.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page