loft-cli 0.6.3__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.
- loft_cli/__init__.py +3 -0
- loft_cli/_builtins.py +269 -0
- loft_cli/addons/__init__.py +12 -0
- loft_cli/addons/goss/__init__.py +1 -0
- loft_cli/addons/goss/generator.py +202 -0
- loft_cli/addons/goss/renderer.py +207 -0
- loft_cli/addons/goss/shipper.py +174 -0
- loft_cli/agent_installer.py +65 -0
- loft_cli/checks/__init__.py +0 -0
- loft_cli/checks/compose.py +147 -0
- loft_cli/checks/container.py +24 -0
- loft_cli/checks/http.py +30 -0
- loft_cli/checks/nginx.py +21 -0
- loft_cli/checks/ports.py +24 -0
- loft_cli/checks/postgres.py +21 -0
- loft_cli/checks/ssh.py +66 -0
- loft_cli/checks/wireguard.py +21 -0
- loft_cli/cli.py +1161 -0
- loft_cli/compiler/__init__.py +0 -0
- loft_cli/compiler/normalizer.py +420 -0
- loft_cli/compiler/parser.py +42 -0
- loft_cli/compiler/planner.py +2543 -0
- loft_cli/local/__init__.py +0 -0
- loft_cli/local/ddl/__init__.py +0 -0
- loft_cli/local/ddl/bootstrap_tables.py +75 -0
- loft_cli/local/ddl/versionize_system.py +374 -0
- loft_cli/local/inventory.py +449 -0
- loft_cli/local/inventory_db.py +255 -0
- loft_cli/local/keys.py +45 -0
- loft_cli/local/remove.py +135 -0
- loft_cli/local/ssh_config.py +118 -0
- loft_cli/local/tunnel.py +228 -0
- loft_cli/local/wireguard_store.py +138 -0
- loft_cli/logs/__init__.py +0 -0
- loft_cli/logs/reader.py +55 -0
- loft_cli/logs/writer.py +58 -0
- loft_cli/runtime/__init__.py +0 -0
- loft_cli/runtime/agent_transport.py +115 -0
- loft_cli/runtime/executor.py +798 -0
- loft_cli/runtime/fabric_transport.py +68 -0
- loft_cli/runtime/secret_rotation.py +99 -0
- loft_cli/runtime/ssh.py +147 -0
- loft_cli/runtime/steps/__init__.py +0 -0
- loft_cli/runtime/steps/backup.py +72 -0
- loft_cli/runtime/steps/bootstrap.py +227 -0
- loft_cli/runtime/steps/compose.py +43 -0
- loft_cli/runtime/steps/container.py +40 -0
- loft_cli/runtime/steps/docker.py +15 -0
- loft_cli/runtime/steps/file_template.py +25 -0
- loft_cli/runtime/steps/nginx.py +126 -0
- loft_cli/runtime/steps/postgres.py +101 -0
- loft_cli/runtime/steps/postgres_ensure.py +141 -0
- loft_cli/runtime/steps/systemd.py +131 -0
- loft_cli/runtime/steps/wireguard.py +76 -0
- loft_cli/runtime/transport.py +43 -0
- loft_cli/updater.py +208 -0
- loft_cli-0.6.3.dist-info/METADATA +19 -0
- loft_cli-0.6.3.dist-info/RECORD +61 -0
- loft_cli-0.6.3.dist-info/WHEEL +5 -0
- loft_cli-0.6.3.dist-info/entry_points.txt +5 -0
- loft_cli-0.6.3.dist-info/top_level.txt +1 -0
loft_cli/cli.py
ADDED
|
@@ -0,0 +1,1161 @@
|
|
|
1
|
+
"""loft-cli CLI — commands wiring the full pipeline.
|
|
2
|
+
|
|
3
|
+
validate <spec.yaml>
|
|
4
|
+
plan <spec.yaml>
|
|
5
|
+
docs <spec.yaml> [--output FILE] [--mode guide|commands]
|
|
6
|
+
diff <spec.yaml>
|
|
7
|
+
doctor <spec.yaml> — drift detection
|
|
8
|
+
reconcile <spec.yaml> — bring server back to desired state
|
|
9
|
+
apply <spec.yaml> [--dry-run]
|
|
10
|
+
inspect run <run-id>
|
|
11
|
+
inventory list | show <server-id>
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import TYPE_CHECKING
|
|
19
|
+
|
|
20
|
+
import typer
|
|
21
|
+
from rich.console import Console
|
|
22
|
+
from rich.panel import Panel
|
|
23
|
+
from rich.table import Table
|
|
24
|
+
from rich.text import Text
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from loft_cli.local.inventory_db import InventoryDB
|
|
28
|
+
|
|
29
|
+
app = typer.Typer(
|
|
30
|
+
name="loft-cli",
|
|
31
|
+
help=(
|
|
32
|
+
"Securely bootstrap Linux servers into production-ready nodes — "
|
|
33
|
+
"with auditable plans, generated ops docs, and encrypted local inventory."
|
|
34
|
+
),
|
|
35
|
+
no_args_is_help=True,
|
|
36
|
+
add_completion=True,
|
|
37
|
+
)
|
|
38
|
+
inventory_app = typer.Typer(help="Manage local server inventory.", no_args_is_help=True)
|
|
39
|
+
inspect_app = typer.Typer(help="Inspect apply runs.", no_args_is_help=True)
|
|
40
|
+
tunnel_app = typer.Typer(help="Manage WireGuard tunnels.", no_args_is_help=True)
|
|
41
|
+
app.add_typer(inventory_app, name="inventory")
|
|
42
|
+
app.add_typer(inspect_app, name="inspect")
|
|
43
|
+
app.add_typer(tunnel_app, name="tunnel")
|
|
44
|
+
|
|
45
|
+
console = Console()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@app.callback()
|
|
49
|
+
def _startup() -> None:
|
|
50
|
+
"""Load built-in kinds and any installed addons before running a command."""
|
|
51
|
+
from loft_cli_core.registry import load_addons
|
|
52
|
+
|
|
53
|
+
load_addons()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# ------------------------------------------------------------------ #
|
|
57
|
+
# version
|
|
58
|
+
# ------------------------------------------------------------------ #
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@app.command()
|
|
62
|
+
def version(
|
|
63
|
+
host: str | None = typer.Option(
|
|
64
|
+
None, "--host", help="Also check agent version on a remote host"
|
|
65
|
+
),
|
|
66
|
+
port: int = typer.Option(22, "--port", help="SSH port for remote agent check"),
|
|
67
|
+
user: str = typer.Option("root", "--user", help="SSH user for remote agent check"),
|
|
68
|
+
key: str | None = typer.Option(None, "--key", help="SSH key path for remote agent check"),
|
|
69
|
+
) -> None:
|
|
70
|
+
"""Print client version (and optionally agent version on a remote host)."""
|
|
71
|
+
from loft_cli import __version__
|
|
72
|
+
|
|
73
|
+
console.print(f"loft-cli client: {__version__}")
|
|
74
|
+
|
|
75
|
+
if host:
|
|
76
|
+
from loft_cli.agent_installer import detect_agent
|
|
77
|
+
from loft_cli.runtime.fabric_transport import FabricTransport
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
transport = FabricTransport(host=host, user=user, port=port, key_path=key)
|
|
81
|
+
agent_version = detect_agent(transport)
|
|
82
|
+
if agent_version:
|
|
83
|
+
console.print(f"loft-cli agent: {agent_version} (on {host})")
|
|
84
|
+
else:
|
|
85
|
+
console.print(f"loft-cli agent: [dim]not installed[/dim] (on {host})")
|
|
86
|
+
transport.close()
|
|
87
|
+
except Exception as e:
|
|
88
|
+
console.print(f"loft-cli agent: [red]unreachable[/red] ({e})")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# ------------------------------------------------------------------ #
|
|
92
|
+
# update
|
|
93
|
+
# ------------------------------------------------------------------ #
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@app.command()
|
|
97
|
+
def update() -> None:
|
|
98
|
+
"""Check for updates and self-update the loft-cli client."""
|
|
99
|
+
from loft_cli.updater import self_update
|
|
100
|
+
|
|
101
|
+
self_update(console=console)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@app.command(name="agent-update")
|
|
105
|
+
def agent_update(
|
|
106
|
+
host: str = typer.Argument(..., help="Target host to update the agent on"),
|
|
107
|
+
port: int = typer.Option(22, "--port", help="SSH port"),
|
|
108
|
+
user: str = typer.Option("root", "--user", help="SSH user"),
|
|
109
|
+
key: str | None = typer.Option(None, "--key", help="SSH key path"),
|
|
110
|
+
) -> None:
|
|
111
|
+
"""Update the loft-cli-agent binary on a remote host."""
|
|
112
|
+
from loft_cli.runtime.fabric_transport import FabricTransport
|
|
113
|
+
from loft_cli.updater import update_agent
|
|
114
|
+
|
|
115
|
+
transport = FabricTransport(host=host, user=user, port=port, key_path=key)
|
|
116
|
+
try:
|
|
117
|
+
update_agent(transport, console=console)
|
|
118
|
+
finally:
|
|
119
|
+
transport.close()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _build_pipeline(
|
|
123
|
+
spec_path: Path,
|
|
124
|
+
ensure_keys: bool = False,
|
|
125
|
+
*,
|
|
126
|
+
strict_env: bool = True,
|
|
127
|
+
env_file: list[Path] | None = None,
|
|
128
|
+
):
|
|
129
|
+
"""Run Parse → Validate → (KeyGen) → Normalize → Plan.
|
|
130
|
+
|
|
131
|
+
Returns (spec, ctx, plan, issues) for single-document specs.
|
|
132
|
+
Returns (specs, ctxs, plans, all_issues) for multi-document specs.
|
|
133
|
+
"""
|
|
134
|
+
from loft_cli.compiler.normalizer import normalize
|
|
135
|
+
from loft_cli.compiler.parser import parse
|
|
136
|
+
from loft_cli.compiler.planner import plan as make_plan
|
|
137
|
+
from loft_cli_core.registry import get_kind_hooks
|
|
138
|
+
from loft_cli_core.specs.validators import validate_spec
|
|
139
|
+
|
|
140
|
+
parsed = parse(spec_path, strict_env=strict_env, env_files=env_file)
|
|
141
|
+
|
|
142
|
+
# Multi-document support: process each spec independently
|
|
143
|
+
if isinstance(parsed, list):
|
|
144
|
+
specs = []
|
|
145
|
+
ctxs = []
|
|
146
|
+
plans = []
|
|
147
|
+
all_issues = []
|
|
148
|
+
for spec in parsed:
|
|
149
|
+
issues = validate_spec(spec)
|
|
150
|
+
all_issues.extend(issues)
|
|
151
|
+
if ensure_keys and get_kind_hooks(spec.kind).needs_key_generation:
|
|
152
|
+
from loft_cli.local.keys import ensure_admin_keys
|
|
153
|
+
|
|
154
|
+
ensure_admin_keys(spec, console=console)
|
|
155
|
+
ctx = normalize(spec, spec_dir=spec_path.resolve().parent)
|
|
156
|
+
p = make_plan(ctx)
|
|
157
|
+
specs.append(spec)
|
|
158
|
+
ctxs.append(ctx)
|
|
159
|
+
plans.append(p)
|
|
160
|
+
return specs, ctxs, plans, all_issues
|
|
161
|
+
|
|
162
|
+
# Single document (backward compatible)
|
|
163
|
+
spec = parsed
|
|
164
|
+
issues = validate_spec(spec)
|
|
165
|
+
|
|
166
|
+
if ensure_keys and get_kind_hooks(spec.kind).needs_key_generation:
|
|
167
|
+
from loft_cli.local.keys import ensure_admin_keys
|
|
168
|
+
|
|
169
|
+
ensure_admin_keys(spec, console=console)
|
|
170
|
+
|
|
171
|
+
ctx = normalize(spec, spec_dir=spec_path.resolve().parent)
|
|
172
|
+
p = make_plan(ctx)
|
|
173
|
+
return spec, ctx, p, issues
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _print_issues(issues, stop_on_error: bool = True) -> None:
|
|
177
|
+
from loft_cli_core.specs.validators import has_errors
|
|
178
|
+
|
|
179
|
+
for issue in issues:
|
|
180
|
+
color = "red" if issue.severity == "error" else "yellow"
|
|
181
|
+
console.print(f" [{color}]{issue}[/{color}]")
|
|
182
|
+
|
|
183
|
+
if stop_on_error and has_errors(issues):
|
|
184
|
+
console.print("\n[bold red]Validation errors found. Fix before applying.[/bold red]")
|
|
185
|
+
raise typer.Exit(1)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
# ------------------------------------------------------------------ #
|
|
189
|
+
# validate
|
|
190
|
+
# ------------------------------------------------------------------ #
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
@app.command()
|
|
194
|
+
def validate(
|
|
195
|
+
spec: Path = typer.Argument(..., help="Path to YAML spec file", exists=True),
|
|
196
|
+
env_file: list[Path] | None = typer.Option(
|
|
197
|
+
None, "--env-file", help="Load environment variables from .env file(s) (repeatable)"
|
|
198
|
+
),
|
|
199
|
+
passthrough: bool = typer.Option(
|
|
200
|
+
False,
|
|
201
|
+
"--passthrough",
|
|
202
|
+
help="Leave unresolved ${VAR} references unchanged instead of erroring",
|
|
203
|
+
),
|
|
204
|
+
) -> None:
|
|
205
|
+
"""Validate a YAML spec file against its schema."""
|
|
206
|
+
from loft_cli.compiler.parser import parse
|
|
207
|
+
from loft_cli_core.specs.validators import has_errors, validate_spec
|
|
208
|
+
|
|
209
|
+
console.print(f"[bold]Validating:[/bold] {spec}")
|
|
210
|
+
try:
|
|
211
|
+
parsed = parse(spec, strict_env=not passthrough, env_files=env_file)
|
|
212
|
+
except Exception as e:
|
|
213
|
+
console.print(f"[bold red]Parse error:[/bold red] {e}")
|
|
214
|
+
raise typer.Exit(1) from None
|
|
215
|
+
|
|
216
|
+
# Handle multi-document specs
|
|
217
|
+
specs_list = parsed if isinstance(parsed, list) else [parsed]
|
|
218
|
+
all_issues = []
|
|
219
|
+
for i, s in enumerate(specs_list):
|
|
220
|
+
if len(specs_list) > 1:
|
|
221
|
+
console.print(f"\n[bold]Document {i + 1}:[/bold] {s.meta.name} ({s.kind})")
|
|
222
|
+
issues = validate_spec(s)
|
|
223
|
+
all_issues.extend(issues)
|
|
224
|
+
|
|
225
|
+
if not all_issues:
|
|
226
|
+
doc_label = f"{len(specs_list)} document(s)" if len(specs_list) > 1 else "Spec"
|
|
227
|
+
console.print(f"[bold green]✓ {doc_label} valid.[/bold green]")
|
|
228
|
+
else:
|
|
229
|
+
_print_issues(all_issues, stop_on_error=False)
|
|
230
|
+
if has_errors(all_issues):
|
|
231
|
+
raise typer.Exit(1)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
# ------------------------------------------------------------------ #
|
|
235
|
+
# plan
|
|
236
|
+
# ------------------------------------------------------------------ #
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
@app.command()
|
|
240
|
+
def plan(
|
|
241
|
+
spec: Path = typer.Argument(..., help="Path to YAML spec file", exists=True),
|
|
242
|
+
env_file: list[Path] | None = typer.Option(
|
|
243
|
+
None, "--env-file", help="Load environment variables from .env file(s) (repeatable)"
|
|
244
|
+
),
|
|
245
|
+
passthrough: bool = typer.Option(
|
|
246
|
+
False,
|
|
247
|
+
"--passthrough",
|
|
248
|
+
help="Leave unresolved ${VAR} references unchanged instead of erroring",
|
|
249
|
+
),
|
|
250
|
+
) -> None:
|
|
251
|
+
"""Show the execution plan for a spec without applying it."""
|
|
252
|
+
from loft_cli_core.plan.render_text import render_plan
|
|
253
|
+
|
|
254
|
+
try:
|
|
255
|
+
result = _build_pipeline(spec, strict_env=not passthrough, env_file=env_file)
|
|
256
|
+
except Exception as e:
|
|
257
|
+
console.print(f"[bold red]Error:[/bold red] {e}")
|
|
258
|
+
raise typer.Exit(1) from None
|
|
259
|
+
|
|
260
|
+
specs_r, _, plans_r, issues = result
|
|
261
|
+
|
|
262
|
+
if issues:
|
|
263
|
+
console.print("[bold yellow]Validation warnings:[/bold yellow]")
|
|
264
|
+
_print_issues(issues, stop_on_error=True)
|
|
265
|
+
|
|
266
|
+
# Handle multi-doc: plans_r may be a list or a single Plan
|
|
267
|
+
plans_list = plans_r if isinstance(plans_r, list) else [plans_r]
|
|
268
|
+
for p in plans_list:
|
|
269
|
+
render_plan(p, console=console)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
# ------------------------------------------------------------------ #
|
|
273
|
+
# diff
|
|
274
|
+
# ------------------------------------------------------------------ #
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
@app.command(name="diff")
|
|
278
|
+
def diff_cmd(
|
|
279
|
+
spec: Path = typer.Argument(..., help="Path to YAML spec file", exists=True),
|
|
280
|
+
env_file: list[Path] | None = typer.Option(
|
|
281
|
+
None, "--env-file", help="Load environment variables from .env file(s) (repeatable)"
|
|
282
|
+
),
|
|
283
|
+
passthrough: bool = typer.Option(
|
|
284
|
+
False,
|
|
285
|
+
"--passthrough",
|
|
286
|
+
help="Leave unresolved ${VAR} references unchanged instead of erroring",
|
|
287
|
+
),
|
|
288
|
+
) -> None:
|
|
289
|
+
"""Show what would change on the server before applying."""
|
|
290
|
+
from loft_cli.agent_installer import detect_agent
|
|
291
|
+
from loft_cli.runtime.fabric_transport import FabricTransport
|
|
292
|
+
from loft_cli_core.plan.render_diff import render_diff
|
|
293
|
+
from loft_cli_core.state import RuntimeState
|
|
294
|
+
|
|
295
|
+
try:
|
|
296
|
+
parsed_spec, ctx, p, issues = _build_pipeline(
|
|
297
|
+
spec, strict_env=not passthrough, env_file=env_file
|
|
298
|
+
)
|
|
299
|
+
except Exception as e:
|
|
300
|
+
console.print(f"[bold red]Error:[/bold red] {e}")
|
|
301
|
+
raise typer.Exit(1) from None
|
|
302
|
+
|
|
303
|
+
if issues:
|
|
304
|
+
_print_issues(issues, stop_on_error=True)
|
|
305
|
+
|
|
306
|
+
# Try to retrieve runtime state from the target
|
|
307
|
+
current_state = None
|
|
308
|
+
try:
|
|
309
|
+
login = parsed_spec.login
|
|
310
|
+
key_path = (
|
|
311
|
+
str(ctx.login_key_path) if ctx.login_key_path and ctx.login_key_path.exists() else None
|
|
312
|
+
)
|
|
313
|
+
transport = FabricTransport(
|
|
314
|
+
host=parsed_spec.host.address,
|
|
315
|
+
user=login.user,
|
|
316
|
+
port=login.port,
|
|
317
|
+
key_path=key_path,
|
|
318
|
+
password=ctx.login_password,
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
agent_version = detect_agent(transport)
|
|
322
|
+
if agent_version:
|
|
323
|
+
state_content = transport.download("/var/lib/loft-cli/runtime-state.json")
|
|
324
|
+
current_state = RuntimeState.model_validate_json(state_content)
|
|
325
|
+
console.print(f"[dim]Agent v{agent_version} — loaded runtime state[/dim]")
|
|
326
|
+
else:
|
|
327
|
+
console.print("[dim]No agent installed — showing full plan as new[/dim]")
|
|
328
|
+
transport.close()
|
|
329
|
+
except Exception:
|
|
330
|
+
console.print("[dim]Could not retrieve runtime state — showing full plan as new[/dim]")
|
|
331
|
+
|
|
332
|
+
render_diff(p, current_state, console=console)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
# ------------------------------------------------------------------ #
|
|
336
|
+
# doctor
|
|
337
|
+
# ------------------------------------------------------------------ #
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
@app.command()
|
|
341
|
+
def doctor(
|
|
342
|
+
spec: Path = typer.Argument(..., help="Path to YAML spec file", exists=True),
|
|
343
|
+
env_file: list[Path] | None = typer.Option(
|
|
344
|
+
None, "--env-file", help="Load environment variables from .env file(s) (repeatable)"
|
|
345
|
+
),
|
|
346
|
+
passthrough: bool = typer.Option(
|
|
347
|
+
False,
|
|
348
|
+
"--passthrough",
|
|
349
|
+
help="Leave unresolved ${VAR} references unchanged instead of erroring",
|
|
350
|
+
),
|
|
351
|
+
) -> None:
|
|
352
|
+
"""Report drift between desired spec and actual server state.
|
|
353
|
+
|
|
354
|
+
Generates a plan from the spec, sends it to the agent's doctor
|
|
355
|
+
command, and displays which resources have drifted, are missing,
|
|
356
|
+
or are orphaned.
|
|
357
|
+
"""
|
|
358
|
+
from loft_cli.agent_installer import detect_agent
|
|
359
|
+
from loft_cli.runtime.fabric_transport import FabricTransport
|
|
360
|
+
|
|
361
|
+
try:
|
|
362
|
+
parsed_spec, ctx, p, issues = _build_pipeline(
|
|
363
|
+
spec, strict_env=not passthrough, env_file=env_file
|
|
364
|
+
)
|
|
365
|
+
except Exception as e:
|
|
366
|
+
console.print(f"[bold red]Error:[/bold red] {e}")
|
|
367
|
+
raise typer.Exit(1) from None
|
|
368
|
+
|
|
369
|
+
if issues:
|
|
370
|
+
_print_issues(issues, stop_on_error=True)
|
|
371
|
+
|
|
372
|
+
# Connect to agent and run doctor
|
|
373
|
+
try:
|
|
374
|
+
login = parsed_spec.login
|
|
375
|
+
key_path = (
|
|
376
|
+
str(ctx.login_key_path) if ctx.login_key_path and ctx.login_key_path.exists() else None
|
|
377
|
+
)
|
|
378
|
+
transport = FabricTransport(
|
|
379
|
+
host=parsed_spec.host.address,
|
|
380
|
+
user=login.user,
|
|
381
|
+
port=login.port,
|
|
382
|
+
key_path=key_path,
|
|
383
|
+
password=ctx.login_password,
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
agent_version = detect_agent(transport)
|
|
387
|
+
if not agent_version:
|
|
388
|
+
console.print(
|
|
389
|
+
"[bold red]No agent installed on the target server.[/bold red]\n"
|
|
390
|
+
"Install the agent first: loft-cli apply <spec.yaml>"
|
|
391
|
+
)
|
|
392
|
+
transport.close()
|
|
393
|
+
raise typer.Exit(1)
|
|
394
|
+
|
|
395
|
+
# Upload the current plan as the desired state
|
|
396
|
+
from loft_cli_core.agent_paths import AGENT_BINARY_PATH, AGENT_DESIRED_DIR
|
|
397
|
+
|
|
398
|
+
plan_json = p.model_dump_json(indent=2)
|
|
399
|
+
plan_remote_path = f"{AGENT_DESIRED_DIR}/doctor-plan.json"
|
|
400
|
+
transport.upload_content(plan_json, plan_remote_path, sudo=True)
|
|
401
|
+
|
|
402
|
+
# Invoke agent doctor
|
|
403
|
+
result = transport.run(
|
|
404
|
+
f"{AGENT_BINARY_PATH} doctor {plan_remote_path}",
|
|
405
|
+
sudo=True,
|
|
406
|
+
warn=True,
|
|
407
|
+
)
|
|
408
|
+
|
|
409
|
+
# Print the agent's output
|
|
410
|
+
if result.stdout:
|
|
411
|
+
console.print(result.stdout.rstrip())
|
|
412
|
+
if result.stderr:
|
|
413
|
+
console.print(result.stderr.rstrip())
|
|
414
|
+
|
|
415
|
+
# Download and display the doctor result
|
|
416
|
+
import json as _json
|
|
417
|
+
|
|
418
|
+
try:
|
|
419
|
+
doctor_json = transport.download("/var/lib/loft-cli/doctor-result.json")
|
|
420
|
+
doctor_data = _json.loads(doctor_json)
|
|
421
|
+
healthy = doctor_data.get("healthy", False)
|
|
422
|
+
if not healthy:
|
|
423
|
+
console.print(
|
|
424
|
+
f"\n[bold yellow]Drift detected on {parsed_spec.host.address}.[/bold yellow]"
|
|
425
|
+
"\nRun 'loft-cli reconcile' to bring the server back to desired state."
|
|
426
|
+
)
|
|
427
|
+
except Exception:
|
|
428
|
+
pass # agent output already shown
|
|
429
|
+
|
|
430
|
+
transport.close()
|
|
431
|
+
|
|
432
|
+
if result.return_code != 0:
|
|
433
|
+
raise typer.Exit(1)
|
|
434
|
+
|
|
435
|
+
except typer.Exit:
|
|
436
|
+
raise
|
|
437
|
+
except Exception as e:
|
|
438
|
+
console.print(f"[bold red]Doctor failed:[/bold red] {e}")
|
|
439
|
+
raise typer.Exit(1) from None
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
# ------------------------------------------------------------------ #
|
|
443
|
+
# reconcile
|
|
444
|
+
# ------------------------------------------------------------------ #
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
@app.command()
|
|
448
|
+
def reconcile(
|
|
449
|
+
spec: Path = typer.Argument(..., help="Path to YAML spec file", exists=True),
|
|
450
|
+
env_file: list[Path] | None = typer.Option(
|
|
451
|
+
None, "--env-file", help="Load environment variables from .env file(s) (repeatable)"
|
|
452
|
+
),
|
|
453
|
+
passthrough: bool = typer.Option(
|
|
454
|
+
False,
|
|
455
|
+
"--passthrough",
|
|
456
|
+
help="Leave unresolved ${VAR} references unchanged instead of erroring",
|
|
457
|
+
),
|
|
458
|
+
) -> None:
|
|
459
|
+
"""Bring server back to desired state defined in the spec.
|
|
460
|
+
|
|
461
|
+
This is equivalent to 'loft-cli apply' but communicates the intent:
|
|
462
|
+
the server has drifted and needs to be reconciled. Only changed
|
|
463
|
+
resources are re-applied (idempotent).
|
|
464
|
+
"""
|
|
465
|
+
console.print("[bold]Reconciling server to desired state...[/bold]\n")
|
|
466
|
+
|
|
467
|
+
# Reconcile is semantically identical to apply --mode agent
|
|
468
|
+
# The agent's idempotent executor handles partial apply automatically.
|
|
469
|
+
try:
|
|
470
|
+
result = _build_pipeline(
|
|
471
|
+
spec, ensure_keys=True, strict_env=not passthrough, env_file=env_file
|
|
472
|
+
)
|
|
473
|
+
except Exception as e:
|
|
474
|
+
console.print(f"[bold red]Error:[/bold red] {e}")
|
|
475
|
+
raise typer.Exit(1) from None
|
|
476
|
+
|
|
477
|
+
specs_r, ctxs_r, plans_r, issues = result
|
|
478
|
+
|
|
479
|
+
if issues:
|
|
480
|
+
_print_issues(issues, stop_on_error=True)
|
|
481
|
+
|
|
482
|
+
# Normalize to lists for uniform handling
|
|
483
|
+
if isinstance(specs_r, list):
|
|
484
|
+
spec_list = list(zip(specs_r, ctxs_r, plans_r, strict=True))
|
|
485
|
+
else:
|
|
486
|
+
spec_list = [(specs_r, ctxs_r, plans_r)]
|
|
487
|
+
|
|
488
|
+
for parsed_spec, ctx, p in spec_list:
|
|
489
|
+
_apply_single(parsed_spec, ctx, p, "agent", False, console)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
# ------------------------------------------------------------------ #
|
|
493
|
+
# docs
|
|
494
|
+
# ------------------------------------------------------------------ #
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
@app.command()
|
|
498
|
+
def docs(
|
|
499
|
+
spec: Path = typer.Argument(..., help="Path to YAML spec file", exists=True),
|
|
500
|
+
output: Path | None = typer.Option(
|
|
501
|
+
None, "--output", "-o", help="Output file (default: stdout)"
|
|
502
|
+
),
|
|
503
|
+
mode: str = typer.Option("guide", "--mode", "-m", help="Output mode: guide or commands"),
|
|
504
|
+
env_file: list[Path] | None = typer.Option(
|
|
505
|
+
None, "--env-file", help="Load environment variables from .env file(s) (repeatable)"
|
|
506
|
+
),
|
|
507
|
+
passthrough: bool = typer.Option(
|
|
508
|
+
False,
|
|
509
|
+
"--passthrough",
|
|
510
|
+
help="Leave unresolved ${VAR} references unchanged instead of erroring",
|
|
511
|
+
),
|
|
512
|
+
) -> None:
|
|
513
|
+
"""Generate Markdown documentation from a spec's execution plan."""
|
|
514
|
+
from loft_cli_core.plan.render_markdown import render_markdown
|
|
515
|
+
|
|
516
|
+
try:
|
|
517
|
+
result = _build_pipeline(spec, strict_env=not passthrough, env_file=env_file)
|
|
518
|
+
except Exception as e:
|
|
519
|
+
console.print(f"[bold red]Error:[/bold red] {e}")
|
|
520
|
+
raise typer.Exit(1) from None
|
|
521
|
+
|
|
522
|
+
_, _, plans_r, issues = result
|
|
523
|
+
|
|
524
|
+
if issues:
|
|
525
|
+
_print_issues(issues, stop_on_error=True)
|
|
526
|
+
|
|
527
|
+
plans_list = plans_r if isinstance(plans_r, list) else [plans_r]
|
|
528
|
+
md = "\n\n---\n\n".join(render_markdown(p, mode=mode) for p in plans_list)
|
|
529
|
+
|
|
530
|
+
if output:
|
|
531
|
+
output.write_text(md, encoding="utf-8")
|
|
532
|
+
console.print(f"[bold green]✓ Docs written to:[/bold green] {output}")
|
|
533
|
+
else:
|
|
534
|
+
print(md)
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
# ------------------------------------------------------------------ #
|
|
538
|
+
# apply
|
|
539
|
+
# ------------------------------------------------------------------ #
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
@app.command()
|
|
543
|
+
def apply(
|
|
544
|
+
spec: Path = typer.Argument(..., help="Path to YAML spec file", exists=True),
|
|
545
|
+
dry_run: bool = typer.Option(
|
|
546
|
+
False, "--dry-run", help="Show what would be done without executing"
|
|
547
|
+
),
|
|
548
|
+
env_file: list[Path] | None = typer.Option(
|
|
549
|
+
None, "--env-file", help="Load environment variables from .env file(s) (repeatable)"
|
|
550
|
+
),
|
|
551
|
+
passthrough: bool = typer.Option(
|
|
552
|
+
False,
|
|
553
|
+
"--passthrough",
|
|
554
|
+
help="Leave unresolved ${VAR} references unchanged instead of erroring",
|
|
555
|
+
),
|
|
556
|
+
mode: str = typer.Option(
|
|
557
|
+
"auto",
|
|
558
|
+
"--mode",
|
|
559
|
+
help="Execution mode: 'auto' (detect agent), 'agent', or 'client' (Fabric)",
|
|
560
|
+
),
|
|
561
|
+
) -> None:
|
|
562
|
+
"""Apply a spec to provision infrastructure."""
|
|
563
|
+
try:
|
|
564
|
+
result = _build_pipeline(
|
|
565
|
+
spec, ensure_keys=True, strict_env=not passthrough, env_file=env_file
|
|
566
|
+
)
|
|
567
|
+
except Exception as e:
|
|
568
|
+
console.print(f"[bold red]Error:[/bold red] {e}")
|
|
569
|
+
raise typer.Exit(1) from None
|
|
570
|
+
|
|
571
|
+
specs_r, ctxs_r, plans_r, issues = result
|
|
572
|
+
|
|
573
|
+
if issues:
|
|
574
|
+
_print_issues(issues, stop_on_error=True)
|
|
575
|
+
|
|
576
|
+
# Normalize to lists for uniform handling
|
|
577
|
+
if isinstance(specs_r, list):
|
|
578
|
+
spec_list = list(zip(specs_r, ctxs_r, plans_r, strict=True))
|
|
579
|
+
else:
|
|
580
|
+
spec_list = [(specs_r, ctxs_r, plans_r)]
|
|
581
|
+
|
|
582
|
+
for parsed_spec, ctx, p in spec_list:
|
|
583
|
+
_apply_single(parsed_spec, ctx, p, mode, dry_run, console)
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _apply_single(parsed_spec, ctx, p, mode, dry_run, console) -> None:
|
|
587
|
+
"""Apply a single spec. Extracted to support multi-document iteration."""
|
|
588
|
+
from loft_cli.local.inventory_db import InventoryDB
|
|
589
|
+
from loft_cli.logs.writer import write_log
|
|
590
|
+
from loft_cli.runtime.executor import Executor
|
|
591
|
+
from loft_cli.runtime.fabric_transport import FabricTransport
|
|
592
|
+
from loft_cli_core.registry import get_kind_hooks
|
|
593
|
+
|
|
594
|
+
console.print(
|
|
595
|
+
Panel(
|
|
596
|
+
f"[bold]Applying:[/bold] {parsed_spec.meta.name}\n"
|
|
597
|
+
f"[bold]Target:[/bold] {parsed_spec.host.address}\n"
|
|
598
|
+
f"[bold]Steps:[/bold] {len(p.steps)}"
|
|
599
|
+
+ (" [yellow](DRY RUN)[/yellow]" if dry_run else ""),
|
|
600
|
+
title="loft-cli apply",
|
|
601
|
+
border_style="bright_blue",
|
|
602
|
+
)
|
|
603
|
+
)
|
|
604
|
+
|
|
605
|
+
# Build transport (SSH session)
|
|
606
|
+
transport = None
|
|
607
|
+
if not dry_run:
|
|
608
|
+
import socket
|
|
609
|
+
|
|
610
|
+
def _tcp_reachable(host: str, port: int, timeout: float = 2.0) -> bool:
|
|
611
|
+
try:
|
|
612
|
+
with socket.create_connection((host, port), timeout=timeout):
|
|
613
|
+
return True
|
|
614
|
+
except OSError:
|
|
615
|
+
return False
|
|
616
|
+
|
|
617
|
+
login = parsed_spec.login
|
|
618
|
+
key_path = (
|
|
619
|
+
str(ctx.login_key_path) if ctx.login_key_path and ctx.login_key_path.exists() else None
|
|
620
|
+
)
|
|
621
|
+
|
|
622
|
+
# For specs that declare ssh_port_fallback (e.g. bootstrap), if login.port is
|
|
623
|
+
# unreachable try ssh.port as fallback. This allows clean re-runs after a
|
|
624
|
+
# partial apply that already moved SSH to the new port.
|
|
625
|
+
effective_port = login.port
|
|
626
|
+
effective_user = login.user
|
|
627
|
+
effective_key_path = key_path
|
|
628
|
+
effective_password = ctx.login_password
|
|
629
|
+
hooks = get_kind_hooks(parsed_spec.kind)
|
|
630
|
+
if hooks.ssh_port_fallback and not _tcp_reachable(parsed_spec.host.address, login.port):
|
|
631
|
+
fallback_port = parsed_spec.ssh.port
|
|
632
|
+
if fallback_port != login.port and _tcp_reachable(
|
|
633
|
+
parsed_spec.host.address, fallback_port
|
|
634
|
+
):
|
|
635
|
+
console.print(
|
|
636
|
+
f"[yellow]⚠ login.port {login.port} unreachable — "
|
|
637
|
+
f"reconnecting on ssh.port {fallback_port}[/yellow]"
|
|
638
|
+
)
|
|
639
|
+
effective_port = fallback_port
|
|
640
|
+
|
|
641
|
+
# When the port has already changed, the server may be fully
|
|
642
|
+
# hardened (root login disabled, password auth disabled). Try
|
|
643
|
+
# the admin user with key auth on the fallback port first.
|
|
644
|
+
admin_name = (
|
|
645
|
+
parsed_spec.admin_user.name if hasattr(parsed_spec, "admin_user") else None
|
|
646
|
+
)
|
|
647
|
+
admin_key = (
|
|
648
|
+
str(ctx.admin_key_path)
|
|
649
|
+
if ctx.admin_key_path and ctx.admin_key_path.exists()
|
|
650
|
+
else None
|
|
651
|
+
)
|
|
652
|
+
if admin_name and admin_key:
|
|
653
|
+
try:
|
|
654
|
+
probe = FabricTransport(
|
|
655
|
+
host=parsed_spec.host.address,
|
|
656
|
+
user=admin_name,
|
|
657
|
+
port=fallback_port,
|
|
658
|
+
key_path=admin_key,
|
|
659
|
+
)
|
|
660
|
+
if probe.test_connection():
|
|
661
|
+
console.print(
|
|
662
|
+
f"[yellow]⚠ Server already bootstrapped — "
|
|
663
|
+
f"using {admin_name}@{parsed_spec.host.address}:"
|
|
664
|
+
f"{fallback_port} with key auth[/yellow]"
|
|
665
|
+
)
|
|
666
|
+
effective_user = admin_name
|
|
667
|
+
effective_key_path = admin_key
|
|
668
|
+
effective_password = None
|
|
669
|
+
probe.close()
|
|
670
|
+
except Exception:
|
|
671
|
+
pass # fall through to original credentials
|
|
672
|
+
else:
|
|
673
|
+
console.print(
|
|
674
|
+
f"[bold red]✗ Cannot reach {parsed_spec.host.address} "
|
|
675
|
+
f"on port {login.port} or {fallback_port} — "
|
|
676
|
+
f"check that the host is up and reachable.[/bold red]"
|
|
677
|
+
)
|
|
678
|
+
raise typer.Exit(1)
|
|
679
|
+
|
|
680
|
+
transport = FabricTransport(
|
|
681
|
+
host=parsed_spec.host.address,
|
|
682
|
+
user=effective_user,
|
|
683
|
+
port=effective_port,
|
|
684
|
+
key_path=effective_key_path,
|
|
685
|
+
password=effective_password,
|
|
686
|
+
)
|
|
687
|
+
|
|
688
|
+
# Determine execution mode (agent vs client)
|
|
689
|
+
use_agent = False
|
|
690
|
+
if transport and not dry_run:
|
|
691
|
+
if mode == "agent":
|
|
692
|
+
use_agent = True
|
|
693
|
+
elif mode == "auto":
|
|
694
|
+
from loft_cli.agent_installer import detect_agent
|
|
695
|
+
|
|
696
|
+
agent_version = detect_agent(transport)
|
|
697
|
+
if agent_version:
|
|
698
|
+
console.print(
|
|
699
|
+
f"[dim]Agent detected (v{agent_version}) — using agent execution[/dim]"
|
|
700
|
+
)
|
|
701
|
+
use_agent = True
|
|
702
|
+
# mode == "client" → use_agent stays False
|
|
703
|
+
if mode == "client" or (mode == "auto" and not use_agent):
|
|
704
|
+
console.print(
|
|
705
|
+
"[dim]Using direct SSH execution "
|
|
706
|
+
"(install loft-cli-agent on the target for agent mode)[/dim]"
|
|
707
|
+
)
|
|
708
|
+
|
|
709
|
+
# Build inventory DB
|
|
710
|
+
inventory_db = None
|
|
711
|
+
inv_cfg = parsed_spec.local.inventory
|
|
712
|
+
if inv_cfg.enabled:
|
|
713
|
+
inventory_db = InventoryDB(db_path=str(ctx.db_path))
|
|
714
|
+
|
|
715
|
+
if use_agent:
|
|
716
|
+
# Agent execution: upload plan, invoke agent, retrieve results
|
|
717
|
+
from loft_cli.runtime.agent_transport import AgentTransport
|
|
718
|
+
from loft_cli.runtime.executor import ApplyResult, StepResult
|
|
719
|
+
|
|
720
|
+
agent_transport = AgentTransport(
|
|
721
|
+
host=parsed_spec.host.address,
|
|
722
|
+
user=effective_user,
|
|
723
|
+
port=effective_port,
|
|
724
|
+
key_path=effective_key_path,
|
|
725
|
+
password=effective_password,
|
|
726
|
+
)
|
|
727
|
+
p.execution_mode = "agent"
|
|
728
|
+
agent_result = agent_transport.apply_plan(p)
|
|
729
|
+
|
|
730
|
+
# Print agent step results
|
|
731
|
+
icons = {"success": "✓", "failed": "✗", "skipped": "○", "unchanged": "≡"}
|
|
732
|
+
colors = {"success": "green", "failed": "red", "skipped": "dim", "unchanged": "blue"}
|
|
733
|
+
for sr in agent_result.step_results:
|
|
734
|
+
icon = icons.get(sr.status, "?")
|
|
735
|
+
color = colors.get(sr.status, "white")
|
|
736
|
+
duration = f"{sr.duration_seconds:.1f}s" if sr.duration_seconds else ""
|
|
737
|
+
console.print(
|
|
738
|
+
f" [{color}]{icon}[/{color}] [{sr.step_index:>2}] {sr.step_id[:50]}"
|
|
739
|
+
+ (f" [{duration}]" if duration else ""),
|
|
740
|
+
)
|
|
741
|
+
if sr.status == "failed" and sr.error:
|
|
742
|
+
console.print(f" [red]{sr.error[:120]}[/red]")
|
|
743
|
+
|
|
744
|
+
console.print(
|
|
745
|
+
f"\n[dim]Agent: {agent_result.applied_count} applied, "
|
|
746
|
+
f"{agent_result.unchanged_count} unchanged[/dim]"
|
|
747
|
+
)
|
|
748
|
+
|
|
749
|
+
# Run local steps via the regular executor
|
|
750
|
+
local_executor = Executor(
|
|
751
|
+
plan=p,
|
|
752
|
+
transport=transport,
|
|
753
|
+
inventory_db=inventory_db,
|
|
754
|
+
ctx=ctx,
|
|
755
|
+
spec=parsed_spec,
|
|
756
|
+
console=console,
|
|
757
|
+
)
|
|
758
|
+
# Only execute LOCAL-scoped steps
|
|
759
|
+
local_result = local_executor.apply(dry_run=dry_run)
|
|
760
|
+
|
|
761
|
+
# Merge into a single ApplyResult for logging
|
|
762
|
+
result = ApplyResult(
|
|
763
|
+
plan=p,
|
|
764
|
+
step_results=[
|
|
765
|
+
StepResult(
|
|
766
|
+
step_index=sr.step_index,
|
|
767
|
+
step_id=sr.step_id,
|
|
768
|
+
scope=sr.scope,
|
|
769
|
+
status="success" if sr.status in ("success", "unchanged") else sr.status,
|
|
770
|
+
output=sr.output,
|
|
771
|
+
error=sr.error,
|
|
772
|
+
duration_seconds=sr.duration_seconds,
|
|
773
|
+
)
|
|
774
|
+
for sr in agent_result.step_results
|
|
775
|
+
]
|
|
776
|
+
+ local_result.step_results,
|
|
777
|
+
status=agent_result.status if agent_result.status == "failed" else local_result.status,
|
|
778
|
+
aborted_at=agent_result.aborted_at,
|
|
779
|
+
started_at=agent_result.started_at,
|
|
780
|
+
finished_at=local_result.finished_at,
|
|
781
|
+
)
|
|
782
|
+
agent_transport.close()
|
|
783
|
+
else:
|
|
784
|
+
# Client execution: direct SSH via Fabric (original path)
|
|
785
|
+
executor = Executor(
|
|
786
|
+
plan=p,
|
|
787
|
+
transport=transport,
|
|
788
|
+
inventory_db=inventory_db,
|
|
789
|
+
ctx=ctx,
|
|
790
|
+
spec=parsed_spec,
|
|
791
|
+
console=console,
|
|
792
|
+
effective_port=(effective_port if transport and effective_port != login.port else None),
|
|
793
|
+
)
|
|
794
|
+
result = executor.apply(dry_run=dry_run)
|
|
795
|
+
|
|
796
|
+
# Post-apply: record inventory via the kind's registered hook.
|
|
797
|
+
if not dry_run and inventory_db and "success" in result.status:
|
|
798
|
+
try:
|
|
799
|
+
record_fn = get_kind_hooks(parsed_spec.kind).on_inventory_record
|
|
800
|
+
if record_fn is not None:
|
|
801
|
+
record_fn(inventory_db, parsed_spec, result)
|
|
802
|
+
except Exception as e:
|
|
803
|
+
console.print(f"[yellow]⚠ Inventory update failed: {e}[/yellow]")
|
|
804
|
+
finally:
|
|
805
|
+
inventory_db.close()
|
|
806
|
+
|
|
807
|
+
# Write execution log
|
|
808
|
+
if not dry_run:
|
|
809
|
+
try:
|
|
810
|
+
log_path = write_log(result)
|
|
811
|
+
console.print(f"\n[dim]Run log: {log_path}[/dim]")
|
|
812
|
+
except Exception as e:
|
|
813
|
+
console.print(f"[yellow]⚠ Log write failed: {e}[/yellow]")
|
|
814
|
+
|
|
815
|
+
# Close transport
|
|
816
|
+
if transport:
|
|
817
|
+
transport.close()
|
|
818
|
+
|
|
819
|
+
# Summary
|
|
820
|
+
status_color = {
|
|
821
|
+
"success": "green",
|
|
822
|
+
"success_with_local_warnings": "yellow",
|
|
823
|
+
"failed": "red",
|
|
824
|
+
}.get(result.status, "white")
|
|
825
|
+
|
|
826
|
+
console.print(f"\n[bold {status_color}]Status: {result.status}[/bold {status_color}]")
|
|
827
|
+
|
|
828
|
+
if result.status == "failed":
|
|
829
|
+
raise typer.Exit(1)
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
# ------------------------------------------------------------------ #
|
|
833
|
+
# rotate-secret
|
|
834
|
+
# ------------------------------------------------------------------ #
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
@app.command(name="rotate-secret")
|
|
838
|
+
def rotate_secret_cmd(
|
|
839
|
+
spec: Path = typer.Argument(..., help="Path to YAML spec file", exists=True),
|
|
840
|
+
secret: str = typer.Option(..., "--secret", help="Environment variable name to rotate"),
|
|
841
|
+
value: str | None = typer.Option(
|
|
842
|
+
None, "--value", help="New secret value (generated if omitted)"
|
|
843
|
+
),
|
|
844
|
+
env_file: list[Path] | None = typer.Option(
|
|
845
|
+
None, "--env-file", help="Load environment variables from .env file(s) (repeatable)"
|
|
846
|
+
),
|
|
847
|
+
passthrough: bool = typer.Option(
|
|
848
|
+
False,
|
|
849
|
+
"--passthrough",
|
|
850
|
+
help="Leave unresolved ${VAR} references unchanged instead of erroring",
|
|
851
|
+
),
|
|
852
|
+
dry_run: bool = typer.Option(
|
|
853
|
+
False, "--dry-run", help="Show what would change without applying"
|
|
854
|
+
),
|
|
855
|
+
) -> None:
|
|
856
|
+
"""Rotate a secret (password_env) and re-apply affected steps."""
|
|
857
|
+
from loft_cli.compiler.parser import parse
|
|
858
|
+
from loft_cli.runtime.secret_rotation import rotate_secret
|
|
859
|
+
|
|
860
|
+
console.print(f"[bold]Rotating secret:[/bold] {secret}")
|
|
861
|
+
|
|
862
|
+
# Parse the spec first to find references
|
|
863
|
+
try:
|
|
864
|
+
parsed = parse(spec, strict_env=not passthrough, env_files=env_file)
|
|
865
|
+
except Exception as e:
|
|
866
|
+
console.print(f"[bold red]Parse error:[/bold red] {e}")
|
|
867
|
+
raise typer.Exit(1) from None
|
|
868
|
+
|
|
869
|
+
specs_list = parsed if isinstance(parsed, list) else [parsed]
|
|
870
|
+
|
|
871
|
+
# Find and rotate the secret
|
|
872
|
+
all_refs = []
|
|
873
|
+
for s in specs_list:
|
|
874
|
+
result = rotate_secret(s, secret, value)
|
|
875
|
+
all_refs.extend(result.refs_found)
|
|
876
|
+
|
|
877
|
+
if not all_refs:
|
|
878
|
+
console.print(f"[bold red]No references to '{secret}' found in spec.[/bold red]")
|
|
879
|
+
raise typer.Exit(1)
|
|
880
|
+
|
|
881
|
+
console.print(f" Found {len(all_refs)} reference(s):")
|
|
882
|
+
for ref in all_refs:
|
|
883
|
+
console.print(f" • {ref.field_path} (kind: {ref.kind})")
|
|
884
|
+
|
|
885
|
+
generated = value is None
|
|
886
|
+
if generated:
|
|
887
|
+
console.print(" [dim]Generated new password (32 chars)[/dim]")
|
|
888
|
+
|
|
889
|
+
if dry_run:
|
|
890
|
+
console.print("\n[yellow]Dry run — no changes applied.[/yellow]")
|
|
891
|
+
return
|
|
892
|
+
|
|
893
|
+
# Re-run the full pipeline with the new secret in the environment
|
|
894
|
+
console.print("\n[bold]Re-applying with rotated secret...[/bold]")
|
|
895
|
+
try:
|
|
896
|
+
pipeline_result = _build_pipeline(
|
|
897
|
+
spec, ensure_keys=True, strict_env=not passthrough, env_file=env_file
|
|
898
|
+
)
|
|
899
|
+
except Exception as e:
|
|
900
|
+
console.print(f"[bold red]Error:[/bold red] {e}")
|
|
901
|
+
raise typer.Exit(1) from None
|
|
902
|
+
|
|
903
|
+
specs_r, ctxs_r, plans_r, issues = pipeline_result
|
|
904
|
+
|
|
905
|
+
if issues:
|
|
906
|
+
_print_issues(issues, stop_on_error=True)
|
|
907
|
+
|
|
908
|
+
if isinstance(specs_r, list):
|
|
909
|
+
spec_list = list(zip(specs_r, ctxs_r, plans_r, strict=True))
|
|
910
|
+
else:
|
|
911
|
+
spec_list = [(specs_r, ctxs_r, plans_r)]
|
|
912
|
+
|
|
913
|
+
for parsed_spec, ctx, p in spec_list:
|
|
914
|
+
_apply_single(parsed_spec, ctx, p, "agent", False, console)
|
|
915
|
+
|
|
916
|
+
console.print(f"\n[bold green]Secret '{secret}' rotated successfully.[/bold green]")
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
# ------------------------------------------------------------------ #
|
|
920
|
+
# tunnel up | down | status
|
|
921
|
+
# ------------------------------------------------------------------ #
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
@tunnel_app.command("up")
|
|
925
|
+
def tunnel_up_cmd(
|
|
926
|
+
host: str = typer.Argument(..., help="Host name to bring up the tunnel for"),
|
|
927
|
+
) -> None:
|
|
928
|
+
"""Bring up the WireGuard tunnel for a host."""
|
|
929
|
+
from loft_cli.local.tunnel import tunnel_up
|
|
930
|
+
|
|
931
|
+
console.print(f"[bold]Bringing up WireGuard tunnel for {host}...[/bold]")
|
|
932
|
+
ok, msg = tunnel_up(host)
|
|
933
|
+
if ok:
|
|
934
|
+
console.print(f"[bold green]{msg}[/bold green]")
|
|
935
|
+
else:
|
|
936
|
+
console.print(f"[bold red]{msg}[/bold red]")
|
|
937
|
+
raise typer.Exit(1)
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
@tunnel_app.command("down")
|
|
941
|
+
def tunnel_down_cmd(
|
|
942
|
+
host: str = typer.Argument(..., help="Host name to tear down the tunnel for"),
|
|
943
|
+
) -> None:
|
|
944
|
+
"""Tear down the WireGuard tunnel for a host."""
|
|
945
|
+
from loft_cli.local.tunnel import tunnel_down
|
|
946
|
+
|
|
947
|
+
console.print(f"[bold]Tearing down WireGuard tunnel for {host}...[/bold]")
|
|
948
|
+
ok, msg = tunnel_down(host)
|
|
949
|
+
if ok:
|
|
950
|
+
console.print(f"[bold green]{msg}[/bold green]")
|
|
951
|
+
else:
|
|
952
|
+
console.print(f"[bold red]{msg}[/bold red]")
|
|
953
|
+
raise typer.Exit(1)
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
@tunnel_app.command("status")
|
|
957
|
+
def tunnel_status_cmd() -> None:
|
|
958
|
+
"""List all hosts with WireGuard tunnel status."""
|
|
959
|
+
from loft_cli.local.tunnel import tunnel_status
|
|
960
|
+
|
|
961
|
+
hosts = tunnel_status()
|
|
962
|
+
if not hosts:
|
|
963
|
+
console.print("[dim]No WireGuard hosts found.[/dim]")
|
|
964
|
+
return
|
|
965
|
+
|
|
966
|
+
table = Table(show_header=True, header_style="bold", box=None, padding=(0, 1))
|
|
967
|
+
table.add_column("Host", min_width=15)
|
|
968
|
+
table.add_column("Interface", min_width=12)
|
|
969
|
+
table.add_column("VPN IP", min_width=12)
|
|
970
|
+
table.add_column("Endpoint", min_width=20)
|
|
971
|
+
table.add_column("Status", min_width=8)
|
|
972
|
+
table.add_column("Deployed")
|
|
973
|
+
|
|
974
|
+
for h in hosts:
|
|
975
|
+
status_text = (
|
|
976
|
+
Text("active", style="green") if h["active"] else Text("inactive", style="dim")
|
|
977
|
+
)
|
|
978
|
+
table.add_row(
|
|
979
|
+
h["host_name"],
|
|
980
|
+
h["interface"],
|
|
981
|
+
h["vpn_ip"],
|
|
982
|
+
h["endpoint"],
|
|
983
|
+
status_text,
|
|
984
|
+
h["deployed_at"][:19] if h["deployed_at"] else "",
|
|
985
|
+
)
|
|
986
|
+
console.print(table)
|
|
987
|
+
|
|
988
|
+
|
|
989
|
+
# ------------------------------------------------------------------ #
|
|
990
|
+
# remove <host>
|
|
991
|
+
# ------------------------------------------------------------------ #
|
|
992
|
+
|
|
993
|
+
|
|
994
|
+
@app.command()
|
|
995
|
+
def remove(
|
|
996
|
+
host: str = typer.Argument(..., help="Host name to remove all local state for"),
|
|
997
|
+
force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation prompt"),
|
|
998
|
+
) -> None:
|
|
999
|
+
"""Remove all local loft-cli state for a decommissioned machine.
|
|
1000
|
+
|
|
1001
|
+
Tears down any active WireGuard tunnel, removes WG state, SSH config,
|
|
1002
|
+
and marks the inventory record as decommissioned.
|
|
1003
|
+
"""
|
|
1004
|
+
from loft_cli.local.remove import remove_host
|
|
1005
|
+
|
|
1006
|
+
if not force:
|
|
1007
|
+
confirm = typer.confirm(f"Remove all local state for '{host}'?")
|
|
1008
|
+
if not confirm:
|
|
1009
|
+
console.print("[dim]Cancelled.[/dim]")
|
|
1010
|
+
raise typer.Exit(0)
|
|
1011
|
+
|
|
1012
|
+
results = remove_host(host, console=console)
|
|
1013
|
+
|
|
1014
|
+
if any(r["status"] == "error" for r in results):
|
|
1015
|
+
console.print(f"\n[bold yellow]Host '{host}' removed with warnings.[/bold yellow]")
|
|
1016
|
+
else:
|
|
1017
|
+
console.print(f"\n[bold green]Host '{host}' removed successfully.[/bold green]")
|
|
1018
|
+
|
|
1019
|
+
|
|
1020
|
+
# ------------------------------------------------------------------ #
|
|
1021
|
+
# inspect run <run-id>
|
|
1022
|
+
# ------------------------------------------------------------------ #
|
|
1023
|
+
|
|
1024
|
+
|
|
1025
|
+
@inspect_app.command("run")
|
|
1026
|
+
def inspect_run(
|
|
1027
|
+
run_id: str = typer.Argument(..., help="Run ID (or prefix) to inspect"),
|
|
1028
|
+
) -> None:
|
|
1029
|
+
"""Show details of a past apply run."""
|
|
1030
|
+
from loft_cli.logs.reader import find_log, read_log
|
|
1031
|
+
|
|
1032
|
+
log_path = find_log(run_id)
|
|
1033
|
+
if not log_path:
|
|
1034
|
+
from loft_cli_core.registry.local_paths import get_local_paths
|
|
1035
|
+
|
|
1036
|
+
log_dir = get_local_paths().log_dir
|
|
1037
|
+
console.print(f"[red]Run '{run_id}' not found in {log_dir}[/red]")
|
|
1038
|
+
raise typer.Exit(1)
|
|
1039
|
+
|
|
1040
|
+
data = read_log(log_path)
|
|
1041
|
+
|
|
1042
|
+
console.print(
|
|
1043
|
+
Panel(
|
|
1044
|
+
f"[bold]Spec:[/bold] {data.get('spec_name')} ({data.get('spec_kind')})\n"
|
|
1045
|
+
f"[bold]Target:[/bold] {data.get('target_host')}\n"
|
|
1046
|
+
f"[bold]Status:[/bold] {data.get('status')}\n"
|
|
1047
|
+
f"[bold]Started:[/bold] {data.get('started_at')}\n"
|
|
1048
|
+
f"[bold]Finished:[/bold] {data.get('finished_at')}",
|
|
1049
|
+
title=f"Run: {data.get('run_id')}",
|
|
1050
|
+
)
|
|
1051
|
+
)
|
|
1052
|
+
|
|
1053
|
+
table = Table(show_header=True, header_style="bold", box=None, padding=(0, 1))
|
|
1054
|
+
table.add_column("#", width=4)
|
|
1055
|
+
table.add_column("Step", min_width=30)
|
|
1056
|
+
table.add_column("Scope", width=8)
|
|
1057
|
+
table.add_column("Status", width=10)
|
|
1058
|
+
table.add_column("Duration", width=10)
|
|
1059
|
+
|
|
1060
|
+
for step in data.get("steps", []):
|
|
1061
|
+
status = step["status"]
|
|
1062
|
+
color = {"success": "green", "failed": "red", "skipped": "dim"}.get(status, "white")
|
|
1063
|
+
table.add_row(
|
|
1064
|
+
str(step["index"]),
|
|
1065
|
+
step["id"],
|
|
1066
|
+
step["scope"],
|
|
1067
|
+
Text(status, style=color),
|
|
1068
|
+
f"{step['duration_seconds']:.1f}s",
|
|
1069
|
+
)
|
|
1070
|
+
|
|
1071
|
+
console.print(table)
|
|
1072
|
+
|
|
1073
|
+
|
|
1074
|
+
# ------------------------------------------------------------------ #
|
|
1075
|
+
# inventory list | show
|
|
1076
|
+
# ------------------------------------------------------------------ #
|
|
1077
|
+
|
|
1078
|
+
|
|
1079
|
+
def _get_db() -> InventoryDB:
|
|
1080
|
+
from loft_cli.local.inventory_db import InventoryDB
|
|
1081
|
+
from loft_cli_core.registry.local_paths import get_local_paths
|
|
1082
|
+
|
|
1083
|
+
# Explicit LOFT_CLI_DB_PATH takes priority (backward compat),
|
|
1084
|
+
# then fall back to get_local_paths() which respects LOFT_CLI_STATE_DIR.
|
|
1085
|
+
db_path = os.environ.get("LOFT_CLI_DB_PATH") or str(get_local_paths().inventory_db_path)
|
|
1086
|
+
db = InventoryDB(db_path=db_path)
|
|
1087
|
+
db.open()
|
|
1088
|
+
return db
|
|
1089
|
+
|
|
1090
|
+
|
|
1091
|
+
@inventory_app.command("list")
|
|
1092
|
+
def inventory_list() -> None:
|
|
1093
|
+
"""List all provisioned servers from local inventory."""
|
|
1094
|
+
db = _get_db()
|
|
1095
|
+
try:
|
|
1096
|
+
servers = db.list_servers()
|
|
1097
|
+
finally:
|
|
1098
|
+
db.close()
|
|
1099
|
+
|
|
1100
|
+
if not servers:
|
|
1101
|
+
console.print("[dim]No servers in inventory.[/dim]")
|
|
1102
|
+
return
|
|
1103
|
+
|
|
1104
|
+
table = Table(show_header=True, header_style="bold", box=None, padding=(0, 1))
|
|
1105
|
+
table.add_column("Name", min_width=20)
|
|
1106
|
+
table.add_column("Address", min_width=15)
|
|
1107
|
+
table.add_column("Status", min_width=15)
|
|
1108
|
+
table.add_column("SSH", min_width=25)
|
|
1109
|
+
table.add_column("WireGuard")
|
|
1110
|
+
|
|
1111
|
+
for s in servers:
|
|
1112
|
+
ssh_info = f"{s.get('ssh_user', '')}@{s.get('ssh_alias', s.get('name', ''))}:{s.get('ssh_port', '')}"
|
|
1113
|
+
wg = "yes" if s.get("wireguard_enabled") else "no"
|
|
1114
|
+
status_color = "green" if s.get("bootstrap_status") == "bootstrapped" else "yellow"
|
|
1115
|
+
table.add_row(
|
|
1116
|
+
s.get("name", ""),
|
|
1117
|
+
s.get("address", ""),
|
|
1118
|
+
Text(s.get("bootstrap_status", ""), style=status_color),
|
|
1119
|
+
ssh_info,
|
|
1120
|
+
wg,
|
|
1121
|
+
)
|
|
1122
|
+
console.print(table)
|
|
1123
|
+
|
|
1124
|
+
|
|
1125
|
+
@inventory_app.command("show")
|
|
1126
|
+
def inventory_show(
|
|
1127
|
+
server_id: str = typer.Argument(..., help="Server name or ID"),
|
|
1128
|
+
) -> None:
|
|
1129
|
+
"""Show details of a specific server from local inventory."""
|
|
1130
|
+
from loft_cli.local.inventory import show_server
|
|
1131
|
+
|
|
1132
|
+
db = _get_db()
|
|
1133
|
+
try:
|
|
1134
|
+
data = show_server(db, server_id)
|
|
1135
|
+
finally:
|
|
1136
|
+
db.close()
|
|
1137
|
+
|
|
1138
|
+
if data is None:
|
|
1139
|
+
console.print(f"[red]Server '{server_id}' not found in inventory.[/red]")
|
|
1140
|
+
raise typer.Exit(1)
|
|
1141
|
+
|
|
1142
|
+
lines = []
|
|
1143
|
+
for k, v in data.items():
|
|
1144
|
+
if k == "services":
|
|
1145
|
+
continue
|
|
1146
|
+
lines.append(f"[bold]{k}:[/bold] {v}")
|
|
1147
|
+
console.print(Panel("\n".join(lines), title=f"Server: {server_id}"))
|
|
1148
|
+
|
|
1149
|
+
services = data.get("services", [])
|
|
1150
|
+
if services:
|
|
1151
|
+
console.print("\n[bold]Services:[/bold]")
|
|
1152
|
+
for svc in services:
|
|
1153
|
+
console.print(
|
|
1154
|
+
f" • {svc.get('service_type')}: {svc.get('service_name')} [{svc.get('status')}]"
|
|
1155
|
+
)
|
|
1156
|
+
else:
|
|
1157
|
+
console.print("[dim]No services recorded.[/dim]")
|
|
1158
|
+
|
|
1159
|
+
|
|
1160
|
+
if __name__ == "__main__":
|
|
1161
|
+
app()
|