hegemony-steps-netcli 0.46.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hegemony_steps_netcli/__init__.py +39 -0
- hegemony_steps_netcli/collect_evidence.py +365 -0
- hegemony_steps_netcli/docs/netcli.collect_evidence.md +90 -0
- hegemony_steps_netcli/docs/netcli.execute.md +138 -0
- hegemony_steps_netcli/docs/netcli.file_download.md +149 -0
- hegemony_steps_netcli/execute.py +357 -0
- hegemony_steps_netcli/file_download.py +535 -0
- hegemony_steps_netcli-0.46.1.dist-info/METADATA +98 -0
- hegemony_steps_netcli-0.46.1.dist-info/RECORD +12 -0
- hegemony_steps_netcli-0.46.1.dist-info/WHEEL +4 -0
- hegemony_steps_netcli-0.46.1.dist-info/entry_points.txt +3 -0
- hegemony_steps_netcli-0.46.1.dist-info/licenses/LICENSE-AGPL-3.0-or-later.txt +235 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2025-2026 Rexonix s.r.o.
|
|
2
|
+
# SPDX-FileContributor: Jakub Trávník <jakub.travnik@gmail.com>
|
|
3
|
+
#
|
|
4
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
|
|
6
|
+
"""Network-device CLI step handlers for Hegemony.
|
|
7
|
+
|
|
8
|
+
Network-device CLI paradigm: execute command lines, collect outputs as
|
|
9
|
+
evidence, and have a device download a file. Vendor-neutral by design — platform
|
|
10
|
+
dialects and transports (netmiko/scrapli, ssh) are resolved beneath the
|
|
11
|
+
handler layer from device access config.
|
|
12
|
+
|
|
13
|
+
Registers under the ``hegemony.step_handlers`` entry-point group; the entry
|
|
14
|
+
point name is the claimed handler-id namespace prefix (``netcli``).
|
|
15
|
+
Handlers reach every platform facility through ``ctx.services``.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from hegemony_step_sdk import BaseHandler, StepHandlerRegistry
|
|
21
|
+
|
|
22
|
+
from .collect_evidence import CollectEvidenceHandler
|
|
23
|
+
from .execute import ExecuteCLIActionHandler
|
|
24
|
+
from .file_download import FileDownloadHandler
|
|
25
|
+
|
|
26
|
+
ALL_HANDLERS: tuple[type[BaseHandler], ...] = (
|
|
27
|
+
CollectEvidenceHandler,
|
|
28
|
+
ExecuteCLIActionHandler,
|
|
29
|
+
FileDownloadHandler,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def register(registry: StepHandlerRegistry) -> None:
|
|
34
|
+
"""Entry point: register this wheel's handlers with the host registry."""
|
|
35
|
+
for handler_class in ALL_HANDLERS:
|
|
36
|
+
registry.register_handler_type(handler_class)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
__all__ = ["ALL_HANDLERS", "register", *sorted(cls.__name__ for cls in ALL_HANDLERS)]
|
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2025-2026 Rexonix s.r.o.
|
|
2
|
+
# SPDX-FileContributor: Jakub Trávník <jakub.travnik@gmail.com>
|
|
3
|
+
#
|
|
4
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
|
|
6
|
+
"""CollectEvidenceHandler: collect CLI command outputs as evidence."""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from collections import Counter
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from pydantic import ConfigDict, Field
|
|
14
|
+
|
|
15
|
+
from hegemony_step_sdk import (
|
|
16
|
+
MAX_PARALLEL_DEVICES_LIMIT,
|
|
17
|
+
BaseHandler,
|
|
18
|
+
HandlerContext,
|
|
19
|
+
HandlerResult,
|
|
20
|
+
HandlerTargeting,
|
|
21
|
+
StepKind,
|
|
22
|
+
command_label,
|
|
23
|
+
for_each_target_device,
|
|
24
|
+
max_parallel_from_config,
|
|
25
|
+
)
|
|
26
|
+
from hegemony_step_sdk.ssh import SshSecurityConfig, configure_ssh_security
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
_DEFAULT_COMMAND_TIMEOUT_SECONDS = 30
|
|
31
|
+
|
|
32
|
+
#: Characters of one command's output kept in the step's chainable output.
|
|
33
|
+
#: The full text always stays in the command's evidence artifact.
|
|
34
|
+
MAX_OUTPUT_TEXT_CHARS = 16_384
|
|
35
|
+
|
|
36
|
+
#: Characters of command output the whole step hands to later steps. Step
|
|
37
|
+
#: outputs share one response budget per run (the host trims the largest
|
|
38
|
+
#: when they exceed it), so a step keeps well inside it.
|
|
39
|
+
MAX_OUTPUT_TOTAL_CHARS = 49_152
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class CollectEvidenceConfig(SshSecurityConfig):
|
|
43
|
+
"""Config for ``netcli.collect_evidence``."""
|
|
44
|
+
|
|
45
|
+
model_config = ConfigDict(extra="allow")
|
|
46
|
+
|
|
47
|
+
commands: list[str] = Field(
|
|
48
|
+
default_factory=list,
|
|
49
|
+
title="Commands (one per line)",
|
|
50
|
+
description=(
|
|
51
|
+
"Device CLI commands whose outputs are captured as evidence, one "
|
|
52
|
+
"artifact per command per device. Use {{ variable }} syntax for "
|
|
53
|
+
"flow inputs. Leave empty to collect nothing (the step still "
|
|
54
|
+
"succeeds)."
|
|
55
|
+
),
|
|
56
|
+
json_schema_extra={
|
|
57
|
+
"x_widget": "commands",
|
|
58
|
+
"x_placeholder": "show version\nshow interfaces",
|
|
59
|
+
"x_rows": 3,
|
|
60
|
+
"x_col_span": 2,
|
|
61
|
+
},
|
|
62
|
+
)
|
|
63
|
+
max_parallel_devices: int = Field(
|
|
64
|
+
default=1,
|
|
65
|
+
ge=1,
|
|
66
|
+
le=MAX_PARALLEL_DEVICES_LIMIT,
|
|
67
|
+
title="Max Parallel Devices",
|
|
68
|
+
description="Devices processed concurrently (1 = sequential)",
|
|
69
|
+
)
|
|
70
|
+
command_timeout_seconds: int = Field(
|
|
71
|
+
_DEFAULT_COMMAND_TIMEOUT_SECONDS,
|
|
72
|
+
ge=1,
|
|
73
|
+
le=3600,
|
|
74
|
+
title="Command timeout (seconds)",
|
|
75
|
+
description=(
|
|
76
|
+
"How long one command may run on a device before it fails. Raise it "
|
|
77
|
+
"for slow commands such as show tech-support. The step timeout must "
|
|
78
|
+
"still cover every command on every device. Defaults to 30 seconds."
|
|
79
|
+
),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _cli_failure_detail(*, error: str | None, exit_code: int) -> str:
|
|
84
|
+
"""Why a command failed, as the step's error says it (as ``netcli.execute`` does)."""
|
|
85
|
+
if error:
|
|
86
|
+
return error
|
|
87
|
+
return f"CLI command failed with exit code {exit_code}"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _failed_on(failures: list[tuple[str, str]]) -> str:
|
|
91
|
+
"""The step's error: the failed devices, those that failed alike listed together.
|
|
92
|
+
|
|
93
|
+
``failures`` holds ``(device, reason)`` in device order. Devices behind one
|
|
94
|
+
broken jump host all fail with the same message, which is then said once:
|
|
95
|
+
``Failed on: r1, r2 (reason A); r3 (reason B)``.
|
|
96
|
+
"""
|
|
97
|
+
by_reason: dict[str, list[str]] = {}
|
|
98
|
+
for device, reason in failures:
|
|
99
|
+
by_reason.setdefault(reason, []).append(device)
|
|
100
|
+
return "Failed on: " + "; ".join(
|
|
101
|
+
f"{', '.join(devices)} ({reason})" for reason, devices in by_reason.items()
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass
|
|
106
|
+
class _DeviceOutcome:
|
|
107
|
+
"""One device's results, merged in device order after the fan-out.
|
|
108
|
+
|
|
109
|
+
Workers collect into these locals instead of shared lists so aggregation
|
|
110
|
+
stays deterministic when devices run in parallel.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
device_name: str = ""
|
|
114
|
+
device_id: str = ""
|
|
115
|
+
evidence: list[dict] = field(default_factory=list)
|
|
116
|
+
#: Each command's output, keyed by the command as configured.
|
|
117
|
+
texts: dict[str, str] = field(default_factory=dict)
|
|
118
|
+
succeeded: int = 0
|
|
119
|
+
failed: int = 0
|
|
120
|
+
#: Why the device failed: its first failure.
|
|
121
|
+
failure: str | None = None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class CollectEvidenceHandler(BaseHandler):
|
|
125
|
+
"""Handler for collecting CLI evidence from devices."""
|
|
126
|
+
|
|
127
|
+
handler_id = "netcli.collect_evidence"
|
|
128
|
+
supported_kinds = [StepKind.CHECK]
|
|
129
|
+
display_name = "Collect Evidence"
|
|
130
|
+
description = "Capture CLI command outputs from devices as evidence."
|
|
131
|
+
category = "Checks"
|
|
132
|
+
# Devices come from roles only: an additional IP has no login details.
|
|
133
|
+
targeting = HandlerTargeting(roles=True, ips=False)
|
|
134
|
+
config_model = CollectEvidenceConfig
|
|
135
|
+
|
|
136
|
+
async def execute(self, ctx: HandlerContext) -> HandlerResult:
|
|
137
|
+
"""Collect CLI command outputs as evidence from all target devices."""
|
|
138
|
+
target_devices = ctx.get_target_devices()
|
|
139
|
+
if not target_devices:
|
|
140
|
+
return HandlerResult(
|
|
141
|
+
success=False,
|
|
142
|
+
error="No target devices configured",
|
|
143
|
+
summary="Missing target device",
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
# Commands are already resolved by resolve_step_templates() before
|
|
147
|
+
# handler execution — no second Jinja pass needed.
|
|
148
|
+
commands = ctx.config.get("commands", [])
|
|
149
|
+
if not isinstance(commands, list):
|
|
150
|
+
return HandlerResult(
|
|
151
|
+
success=False,
|
|
152
|
+
error="'commands' must be a list of strings",
|
|
153
|
+
summary="Invalid commands configuration",
|
|
154
|
+
)
|
|
155
|
+
if any(not isinstance(command, str) or not command.strip() for command in commands):
|
|
156
|
+
return HandlerResult(
|
|
157
|
+
success=False,
|
|
158
|
+
error="'commands' must contain only non-empty strings",
|
|
159
|
+
summary="Invalid commands configuration",
|
|
160
|
+
)
|
|
161
|
+
if not commands:
|
|
162
|
+
return HandlerResult(
|
|
163
|
+
success=True,
|
|
164
|
+
summary="No commands configured",
|
|
165
|
+
evidence=[],
|
|
166
|
+
output={"devices": {}, "truncated": [], "omitted": []},
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
services = ctx.require_services()
|
|
170
|
+
command_timeout = float(
|
|
171
|
+
ctx.config.get("command_timeout_seconds") or _DEFAULT_COMMAND_TIMEOUT_SECONDS
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
async def _process_device(device: dict) -> _DeviceOutcome:
|
|
175
|
+
device_id = device.get("id", "unknown")
|
|
176
|
+
device_name = device.get("name", device_id)
|
|
177
|
+
outcome = _DeviceOutcome(device_name=device_name, device_id=str(device_id))
|
|
178
|
+
host = device.get("mgmt_host")
|
|
179
|
+
if not host:
|
|
180
|
+
outcome.failed += 1
|
|
181
|
+
outcome.failure = "no mgmt_host configured"
|
|
182
|
+
outcome.evidence.append(
|
|
183
|
+
{
|
|
184
|
+
"kind": "error",
|
|
185
|
+
"name": f"error_{device_name}",
|
|
186
|
+
"device_id": device_id,
|
|
187
|
+
"content_text": f"Device {device_name} has no mgmt_host configured",
|
|
188
|
+
}
|
|
189
|
+
)
|
|
190
|
+
return outcome
|
|
191
|
+
|
|
192
|
+
try:
|
|
193
|
+
# step_run_id registers the session, so cancelling the run
|
|
194
|
+
# closes it.
|
|
195
|
+
ssh = services.connect(
|
|
196
|
+
device,
|
|
197
|
+
platform=device.get("platform"),
|
|
198
|
+
command_timeout=command_timeout,
|
|
199
|
+
step_run_id=ctx.step_run_id,
|
|
200
|
+
)
|
|
201
|
+
configure_ssh_security(ssh, ctx.config.get("allow_legacy_ssh", False))
|
|
202
|
+
# Execute all commands together for efficiency
|
|
203
|
+
results = await ssh.execute_commands(commands)
|
|
204
|
+
for result in results:
|
|
205
|
+
outcome.texts[result.command] = result.output or ""
|
|
206
|
+
if result.output:
|
|
207
|
+
# Live view: per-command output into the Logs tab
|
|
208
|
+
await ctx.emit_output(result.output, device=device, command=result.command)
|
|
209
|
+
outcome.evidence.append(
|
|
210
|
+
{
|
|
211
|
+
"kind": "cli_output",
|
|
212
|
+
"name": f"{device_name}:{command_label(result.command)}",
|
|
213
|
+
"device_id": device_id,
|
|
214
|
+
"content_text": result.output,
|
|
215
|
+
"content_json": {
|
|
216
|
+
"device_id": device_id,
|
|
217
|
+
"device_name": device_name,
|
|
218
|
+
"command": result.command,
|
|
219
|
+
"success": result.exit_code == 0,
|
|
220
|
+
"exit_code": result.exit_code,
|
|
221
|
+
"error": result.error,
|
|
222
|
+
},
|
|
223
|
+
}
|
|
224
|
+
)
|
|
225
|
+
if result.exit_code == 0:
|
|
226
|
+
outcome.succeeded += 1
|
|
227
|
+
else:
|
|
228
|
+
outcome.failed += 1
|
|
229
|
+
if outcome.failure is None:
|
|
230
|
+
outcome.failure = _cli_failure_detail(
|
|
231
|
+
error=result.error, exit_code=result.exit_code
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
except Exception as e:
|
|
235
|
+
if outcome.failure is None:
|
|
236
|
+
outcome.failure = str(e)
|
|
237
|
+
# Add error evidence for this device
|
|
238
|
+
outcome.evidence.append(
|
|
239
|
+
{
|
|
240
|
+
"kind": "error",
|
|
241
|
+
"name": f"{device_name}:connection_error",
|
|
242
|
+
"device_id": device_id,
|
|
243
|
+
"content_json": {
|
|
244
|
+
"device_id": device_id,
|
|
245
|
+
"device_name": device_name,
|
|
246
|
+
"error": str(e),
|
|
247
|
+
},
|
|
248
|
+
}
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
return outcome
|
|
252
|
+
|
|
253
|
+
outcomes = await for_each_target_device(
|
|
254
|
+
target_devices,
|
|
255
|
+
_process_device,
|
|
256
|
+
max_parallel=max_parallel_from_config(ctx.config),
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
all_evidence = [item for outcome in outcomes for item in outcome.evidence]
|
|
260
|
+
total_success = sum(outcome.succeeded for outcome in outcomes)
|
|
261
|
+
total_failure = sum(outcome.failed for outcome in outcomes)
|
|
262
|
+
failed_devices = [
|
|
263
|
+
(outcome.device_name, outcome.failure)
|
|
264
|
+
for outcome in outcomes
|
|
265
|
+
if outcome.failure is not None
|
|
266
|
+
]
|
|
267
|
+
|
|
268
|
+
output = _chain_output(outcomes)
|
|
269
|
+
metrics = {
|
|
270
|
+
"device_count": len(target_devices),
|
|
271
|
+
"command_count": len(commands),
|
|
272
|
+
"total_success": total_success,
|
|
273
|
+
"total_failure": total_failure,
|
|
274
|
+
"failed_devices": len(failed_devices),
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if failed_devices:
|
|
278
|
+
return HandlerResult(
|
|
279
|
+
success=False,
|
|
280
|
+
error=_failed_on(failed_devices),
|
|
281
|
+
summary=f"Evidence collected from {len(target_devices) - len(failed_devices)}/{len(target_devices)} devices",
|
|
282
|
+
metrics=metrics,
|
|
283
|
+
evidence=all_evidence,
|
|
284
|
+
output=output,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
return HandlerResult(
|
|
288
|
+
success=True,
|
|
289
|
+
summary=f"Collected evidence from {len(target_devices)} device(s), {total_success} commands OK",
|
|
290
|
+
metrics=metrics,
|
|
291
|
+
evidence=all_evidence,
|
|
292
|
+
output=output,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _whole_lines(text: str, limit: int) -> str:
|
|
297
|
+
"""``text`` cut to at most ``limit`` characters at the end of a line.
|
|
298
|
+
|
|
299
|
+
The host masks registered secrets by their whole value after the step
|
|
300
|
+
returns; a cut inside a line could keep the start of one, which no longer
|
|
301
|
+
matches. Text with no line end within the limit is left out entirely.
|
|
302
|
+
"""
|
|
303
|
+
if len(text) <= limit:
|
|
304
|
+
return text
|
|
305
|
+
end = text.rfind("\n", 0, limit)
|
|
306
|
+
return text[: end + 1] if end >= 0 else ""
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _device_keys(outcomes: list[_DeviceOutcome]) -> list[str]:
|
|
310
|
+
"""One key per device: its name, or ``name (id)`` for a name used twice.
|
|
311
|
+
|
|
312
|
+
Inventory names are unique per site only, so two targets can share one;
|
|
313
|
+
a key still taken (a device named like that) gets a counter.
|
|
314
|
+
"""
|
|
315
|
+
names = Counter(outcome.device_name for outcome in outcomes)
|
|
316
|
+
keys: list[str] = []
|
|
317
|
+
taken: set[str] = set()
|
|
318
|
+
for outcome in outcomes:
|
|
319
|
+
name = outcome.device_name
|
|
320
|
+
key = base = name if names[name] == 1 else f"{name} ({outcome.device_id})"
|
|
321
|
+
number = 2
|
|
322
|
+
while key in taken:
|
|
323
|
+
key, number = f"{base} #{number}", number + 1
|
|
324
|
+
taken.add(key)
|
|
325
|
+
keys.append(key)
|
|
326
|
+
return keys
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _chain_output(outcomes: list[_DeviceOutcome]) -> dict[str, Any]:
|
|
330
|
+
"""The step's chainable output: every device's command outputs, bounded.
|
|
331
|
+
|
|
332
|
+
``devices`` maps each device (see :func:`_device_keys`) to whether it
|
|
333
|
+
succeeded, why it failed, and its outputs by command, so a later step
|
|
334
|
+
reads ``{{ steps.ID.output.devices['r1'].commands['show version'] }}``.
|
|
335
|
+
One command's text keeps at most :data:`MAX_OUTPUT_TEXT_CHARS` and the
|
|
336
|
+
whole output about :data:`MAX_OUTPUT_TOTAL_CHARS`, names included, cut at
|
|
337
|
+
line ends. A shortened text is named in ``truncated`` as
|
|
338
|
+
``device:command``; once the budget is spent, later devices keep their
|
|
339
|
+
status but no commands and are named in ``omitted``. The artifacts keep
|
|
340
|
+
the whole text either way.
|
|
341
|
+
"""
|
|
342
|
+
budget = MAX_OUTPUT_TOTAL_CHARS
|
|
343
|
+
truncated: list[str] = []
|
|
344
|
+
omitted: list[str] = []
|
|
345
|
+
devices: dict[str, Any] = {}
|
|
346
|
+
for key, outcome in zip(_device_keys(outcomes), outcomes, strict=True):
|
|
347
|
+
budget -= len(key) + len(outcome.failure or "")
|
|
348
|
+
commands: dict[str, str] = {}
|
|
349
|
+
if budget <= 0:
|
|
350
|
+
if outcome.texts:
|
|
351
|
+
omitted.append(key)
|
|
352
|
+
else:
|
|
353
|
+
for command, text in outcome.texts.items():
|
|
354
|
+
budget -= len(command)
|
|
355
|
+
kept = _whole_lines(text, max(0, min(MAX_OUTPUT_TEXT_CHARS, budget)))
|
|
356
|
+
if len(kept) < len(text):
|
|
357
|
+
truncated.append(f"{key}:{command}")
|
|
358
|
+
budget -= len(kept)
|
|
359
|
+
commands[command] = kept
|
|
360
|
+
devices[key] = {
|
|
361
|
+
"success": outcome.failure is None,
|
|
362
|
+
"error": outcome.failure,
|
|
363
|
+
"commands": commands,
|
|
364
|
+
}
|
|
365
|
+
return {"devices": devices, "truncated": truncated, "omitted": omitted}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
SPDX-FileCopyrightText: 2025-2026 Rexonix s.r.o.
|
|
3
|
+
SPDX-FileContributor: Jakub Trávník <jakub.travnik@gmail.com>
|
|
4
|
+
|
|
5
|
+
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
6
|
+
-->
|
|
7
|
+
|
|
8
|
+
# Collect Evidence
|
|
9
|
+
|
|
10
|
+
`netcli.collect_evidence` is a check step that runs CLI commands on each
|
|
11
|
+
target device and captures every command's output as an evidence artifact.
|
|
12
|
+
Use it to record device state — before-and-after snapshots, verification
|
|
13
|
+
output, audit trails. It is meant for read-only show commands, but nothing
|
|
14
|
+
enforces that: a configured command runs as written, so keep anything that
|
|
15
|
+
changes device state in `netcli.execute`.
|
|
16
|
+
|
|
17
|
+
## Using It
|
|
18
|
+
|
|
19
|
+
List the commands one per line, typically show/exec commands such as
|
|
20
|
+
`show version` or `show interfaces`. Command lines accept `{{ variable }}`
|
|
21
|
+
templates for flow inputs and earlier step results, resolved before the
|
|
22
|
+
step runs. On each device all commands are executed together in one
|
|
23
|
+
session, in order, and each command's output becomes its own artifact.
|
|
24
|
+
Targets are chosen with the role-based target picker; there is no
|
|
25
|
+
additional-IP list for this step.
|
|
26
|
+
|
|
27
|
+
Leaving the command list empty is not an error: as long as at least one
|
|
28
|
+
target device is configured, the step succeeds with a "No commands
|
|
29
|
+
configured" summary and collects nothing. Max Parallel Devices
|
|
30
|
+
controls the fan-out: 1 (the default) processes devices strictly one after
|
|
31
|
+
another, higher values run up to that many devices concurrently (capped at
|
|
32
|
+
32). Command output reaches the step's live log per device, once that
|
|
33
|
+
device's whole command batch has finished.
|
|
34
|
+
|
|
35
|
+
Command timeout (30 seconds by default, at most 3600) limits how long one
|
|
36
|
+
command may run on a device; a command that runs longer fails. Raise it for
|
|
37
|
+
slow commands. The step's own timeout still applies to the whole step, so
|
|
38
|
+
it must leave time for every command on every device.
|
|
39
|
+
|
|
40
|
+
## SSH Compatibility
|
|
41
|
+
|
|
42
|
+
Allow legacy SSH algorithms defaults to off. Enable `allow_legacy_ssh` only
|
|
43
|
+
for older devices which require weak algorithms or small host keys; it applies
|
|
44
|
+
to the device and jump host for this step. Host-key verification still applies,
|
|
45
|
+
and a failed secure connection never retries weakly. Prefer upgrading the
|
|
46
|
+
device; use legacy mode only on a trusted network. The override enables only
|
|
47
|
+
algorithms the selected transport library still supports.
|
|
48
|
+
|
|
49
|
+
To allow them for one old device in every step, set `allow_legacy_ssh` in the
|
|
50
|
+
device's SSH access configuration instead (the jump host has its own flag). It
|
|
51
|
+
covers that hop only and needs a Hegemony version that reads it.
|
|
52
|
+
|
|
53
|
+
## Output
|
|
54
|
+
|
|
55
|
+
Later steps read what each device returned from the step's output:
|
|
56
|
+
`devices` maps every device name to `success`, `error` (why it failed, or
|
|
57
|
+
none) and `commands`, each command's output keyed by the command as
|
|
58
|
+
configured, for example
|
|
59
|
+
`{{ steps.ID.output.devices['dlp1-edge-01'].commands['show running-config'] }}`.
|
|
60
|
+
Inventory names are unique per site only: a name two targets share is keyed
|
|
61
|
+
as `name (device id)` for each of them. The output keeps at most 16 384
|
|
62
|
+
characters of one command and about 49 152 of the whole step, names
|
|
63
|
+
included, and cuts a text only at the end of a line, so the platform's
|
|
64
|
+
masking of secrets still sees each line whole. A text cut short is named in
|
|
65
|
+
`truncated` as `device:command`; once the step's share is spent, the
|
|
66
|
+
remaining devices keep `success` and `error` but no `commands`, and are named
|
|
67
|
+
in `omitted`. The evidence always holds the whole text.
|
|
68
|
+
|
|
69
|
+
Each command on each device also yields a `cli_output` artifact
|
|
70
|
+
named `<device>:<command>`, holding the raw output plus the device, the
|
|
71
|
+
command, the exit code, and any error text. A device without a management
|
|
72
|
+
host or one that fails to connect contributes an error artifact with the
|
|
73
|
+
message instead. Metrics record `device_count`, `command_count`,
|
|
74
|
+
`total_success` and `total_failure` (per-command results across devices),
|
|
75
|
+
and `failed_devices`. The summary reports how many devices were collected
|
|
76
|
+
from and how many commands succeeded.
|
|
77
|
+
|
|
78
|
+
## When It Fails
|
|
79
|
+
|
|
80
|
+
The step fails when no target devices are configured, or when the commands
|
|
81
|
+
value is malformed (not a list, or containing empty or non-string entries).
|
|
82
|
+
Per device, it counts as failed when the device has no management host,
|
|
83
|
+
when connecting or executing raises an error, or when any command returns a
|
|
84
|
+
non-zero exit code. Collection continues on the remaining devices either
|
|
85
|
+
way, and all collected evidence is kept — but if any device failed, the
|
|
86
|
+
step fails and its error names each failing device with why it failed
|
|
87
|
+
(its first failure). Devices that failed for the same reason are listed
|
|
88
|
+
together before that reason, for example every device behind a jump host
|
|
89
|
+
that refused the connection: `Failed on: r1, r2 (reason); r3 (other reason)`.
|
|
90
|
+
A command that runs past Command timeout counts as failed.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
SPDX-FileCopyrightText: 2025-2026 Rexonix s.r.o.
|
|
3
|
+
SPDX-FileContributor: Jakub Trávník <jakub.travnik@gmail.com>
|
|
4
|
+
|
|
5
|
+
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
6
|
+
-->
|
|
7
|
+
|
|
8
|
+
# Execute CLI
|
|
9
|
+
|
|
10
|
+
`netcli.execute` runs a list of CLI commands on each target device as an
|
|
11
|
+
action step. It is vendor-neutral: the platform dialect and transport are
|
|
12
|
+
resolved from each device's access configuration, so the same step works
|
|
13
|
+
across device families that speak a command-line interface.
|
|
14
|
+
|
|
15
|
+
## Using It
|
|
16
|
+
|
|
17
|
+
Write the commands one per line; they are sent to each device together in a
|
|
18
|
+
single session, in order. Command lines accept `{{ variable }}` templates
|
|
19
|
+
for flow inputs and earlier step results, resolved before the step runs.
|
|
20
|
+
Targets are chosen with the role-based target picker; there is no
|
|
21
|
+
additional-IP list for this step.
|
|
22
|
+
|
|
23
|
+
When the first line that is not blank is `configure terminal` (or `conf t`
|
|
24
|
+
/ `config t`), the list is a configuration session. `configure terminal`
|
|
25
|
+
starts a configuration block and only `end` closes it. `exit` is sent to the
|
|
26
|
+
device like any other configuration line, so it can leave an interface or
|
|
27
|
+
other sub-mode without ending the block. Lines after `end` and before the
|
|
28
|
+
next `configure terminal`, and `write` or `copy run` save commands, run at
|
|
29
|
+
the exec prompt. Everything runs in the order written. Configuration lines are
|
|
30
|
+
sent one at a time, and each is checked before the next is sent. When a
|
|
31
|
+
command fails, including a configuration line the device rejects, the
|
|
32
|
+
commands after it do not run and are recorded as skipped, so a
|
|
33
|
+
`write memory` never saves a change that failed part way.
|
|
34
|
+
When the run is cancelled part way through, the commands that have not run
|
|
35
|
+
are recorded as skipped because the run was cancelled, not because a command
|
|
36
|
+
failed.
|
|
37
|
+
|
|
38
|
+
With the netmiko and scrapli transports, a copy to `startup-config` (such as
|
|
39
|
+
`copy running-config startup-config` or `copy run start`) answers the
|
|
40
|
+
questions the device asks first with Enter: the destination file name, and
|
|
41
|
+
the `[confirm]` some platforms ask before they overwrite it. It then waits
|
|
42
|
+
for the prompt like any other command.
|
|
43
|
+
|
|
44
|
+
A configuration session's transcript is saved as a single consolidated
|
|
45
|
+
"Configuration" evidence artifact per device, and the recorded command list
|
|
46
|
+
omits `configure terminal`, `end` and the save commands. Any other first
|
|
47
|
+
line that is not blank means show/exec mode: each command gets its own
|
|
48
|
+
evidence artifact, named after the command (first line, shortened to 80
|
|
49
|
+
characters), with the device name appended when more than one device is
|
|
50
|
+
targeted.
|
|
51
|
+
|
|
52
|
+
Max Parallel Devices controls the fan-out: 1 (the default) processes devices
|
|
53
|
+
strictly one after another, higher values run up to that many devices
|
|
54
|
+
concurrently (capped at 32). Results are always aggregated in device order.
|
|
55
|
+
Command output reaches the step's live log per device, once that device's
|
|
56
|
+
whole command batch has finished.
|
|
57
|
+
|
|
58
|
+
Command timeout (30 seconds by default, at most 3600) limits how long one
|
|
59
|
+
command, or one configuration line, may run on a device; a command that runs
|
|
60
|
+
longer fails. The step's own timeout still applies to the whole step, so it
|
|
61
|
+
must leave time for every command on every device. With the netmiko
|
|
62
|
+
transport, a configuration block that holds a `banner`, `macro name` or
|
|
63
|
+
`crypto pki certificate chain` line takes about two seconds a line: free
|
|
64
|
+
text gets no prompt back, so each line waits for the device to go quiet.
|
|
65
|
+
|
|
66
|
+
## Commands That Ask Questions
|
|
67
|
+
|
|
68
|
+
Some commands stop at a question before the device prompt returns, such as
|
|
69
|
+
the file name and `[confirm]` of a `delete`. The step waits for the prompt,
|
|
70
|
+
so such a command runs into the command timeout, and the error then
|
|
71
|
+
suggests listing the question. List the questions a command may ask, and
|
|
72
|
+
what to answer, under `prompts`:
|
|
73
|
+
|
|
74
|
+
```yaml
|
|
75
|
+
commands:
|
|
76
|
+
- delete flash:old-image.bin
|
|
77
|
+
prompts:
|
|
78
|
+
- command: '^delete ' # regular expression on the command text
|
|
79
|
+
expect: 'Delete filename \[.*\]\?' # regular expression on the last line
|
|
80
|
+
answer: '' # empty: Enter alone
|
|
81
|
+
- command: '^delete '
|
|
82
|
+
expect: '\[confirm\]'
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Each entry applies to the commands its `command` pattern finds (an empty
|
|
86
|
+
`command` applies it to every command), and is matched against the last line
|
|
87
|
+
the device printed. It answers once per command; set `repeat: true` to answer
|
|
88
|
+
it every time it is asked, such as the per-file confirmations of a
|
|
89
|
+
`delete /recursive`, up to 50 answers. Only listed questions are answered: a
|
|
90
|
+
question nobody listed, or a question asked again after its one answer, fails
|
|
91
|
+
the command with the line the device is waiting at. The command timeout
|
|
92
|
+
applies to each wait, from the command or an answer to the next question or
|
|
93
|
+
the prompt. An answer can hold a `{{ secret(...) }}` reference; it is masked
|
|
94
|
+
like other secret values.
|
|
95
|
+
|
|
96
|
+
In the step form, Answers to questions has one row per entry: the command
|
|
97
|
+
pattern, the question, the answer and "Every time" (`repeat`). Prompts apply
|
|
98
|
+
to commands run at the exec prompt, not to configuration lines, and need the
|
|
99
|
+
netmiko or scrapli transport; with another transport the step fails rather
|
|
100
|
+
than skip them.
|
|
101
|
+
|
|
102
|
+
## SSH Compatibility
|
|
103
|
+
|
|
104
|
+
Allow legacy SSH algorithms defaults to off. Enable `allow_legacy_ssh` only
|
|
105
|
+
for older devices which require weak algorithms or small host keys; it applies
|
|
106
|
+
to the device and jump host for this step. Host-key verification still applies,
|
|
107
|
+
and a failed secure connection never retries weakly. Prefer upgrading the
|
|
108
|
+
device; use legacy mode only on a trusted network. The override enables only
|
|
109
|
+
algorithms the selected transport library still supports.
|
|
110
|
+
|
|
111
|
+
To allow them for one old device in every step, set `allow_legacy_ssh` in the
|
|
112
|
+
device's SSH access configuration instead (the jump host has its own flag). It
|
|
113
|
+
covers that hop only and needs a Hegemony version that reads it.
|
|
114
|
+
|
|
115
|
+
## Output
|
|
116
|
+
|
|
117
|
+
Later steps can read `steps.NODE_ID.output.stdout` — the combined output of all
|
|
118
|
+
commands across all devices, capped at 4096 characters. Full outputs are
|
|
119
|
+
preserved in the `cli_output` evidence artifacts described above, which also
|
|
120
|
+
record the device, the command(s), the exit code, and any error text. A
|
|
121
|
+
device that throws an error contributes an "Error" artifact with the message
|
|
122
|
+
instead. Metrics record `command_count` (configured commands),
|
|
123
|
+
`device_count`, and `total_executions` (commands actually run across
|
|
124
|
+
devices).
|
|
125
|
+
|
|
126
|
+
## When It Fails
|
|
127
|
+
|
|
128
|
+
The step fails immediately when no target devices or no commands are
|
|
129
|
+
configured. Per device, it fails when the device has no management host,
|
|
130
|
+
when the connection or execution raises an error, or when any command
|
|
131
|
+
returns a non-zero exit code. With the netmiko and scrapli transports, a
|
|
132
|
+
device error message in the output, such as `% Invalid input detected`, also
|
|
133
|
+
counts as a failed command. One failing device does not stop the others:
|
|
134
|
+
every device is still processed and its evidence kept, but all devices must
|
|
135
|
+
succeed for the step to succeed. In a configuration session the error
|
|
136
|
+
text lists each failing device with its first failure detail; in show/exec
|
|
137
|
+
mode every failing command contributes its own entry. A command that runs
|
|
138
|
+
past Command timeout counts as failed.
|