Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/commands/k8s.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-23
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Design

## Decisions
- Use `tomllib.load` and Pydantic `TypeAdapter` over a file model to validate data and build existing frozen dataclasses.
- Re-use the existing dataclasses (`ClusterSecret`, `SecretEntry`, `SecretGenerator`, etc.) as the only row model.
- Resolve `cluster-secrets.toml` via `EnvironmentTree` using `--k8s-dir`, project profile facts, or `infra.repos`.
- Keep only product rows in `CLUSTER_SECRETS` in `cluster_secrets.py`.
- Append product rows to loaded environment rows when resolving the full cluster secrets table.

## Rejected alternatives
- Hand-written TOML parser: Adds bespoke parser logic and does not validate the file schema.
- Second row model: Duplicates dataclasses and creates two row models in product code.
- Hardcoded homelab path: Breaks custom environment trees and profile-based resolution.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Proposal: #6685

## Why
The environment Secret rows live in homelab `k8s/cluster-secrets.toml` and in `src/devops_cli/k8s/cluster_secrets.py`. The duplicate rows create two sources of truth. The change reads the homelab file into the existing dataclasses, removes the moved rows from product code, and keeps only the product rows in `cluster_secrets.py`. The readers load the file from the environment tree.

## What Changes
- Add a TOML loader using `tomllib` and a Pydantic `TypeAdapter` that reads `cluster-secrets.toml` into existing `ClusterSecret` dataclasses.
- Add `cluster_secrets` property to `EnvironmentTree` resolving `cluster-secrets.toml`.
- Update `push-secrets` and other readers to load environment rows from `cluster-secrets.toml` and append product rows.
- Remove moved environment Secret rows from `src/devops_cli/k8s/cluster_secrets.py`, leaving only product rows (`valkey-devops-auth`, `valkey-runs-auth`, and `devops` stack rows).
- Add fixture file `tests/fixtures/cluster-secrets.toml`.
- Add unit tests verifying loader behavior, removed stack rows, and environment tree push planning.

## Capabilities
- Read `cluster-secrets.toml` into existing frozen dataclasses for `ClusterSecret`, `SecretEntry`, `SecretGenerator`, and sources.
- Support `--k8s-dir` in `push-secrets` to read environment Secret definitions from an environment tree.

## Impact
- Eliminates duplicate secret definitions between devops-cli and homelab.
- Existing dataclass interfaces and CLI behaviors remain intact.

## Feasibility
Confirmed against repository code and tests: `EnvironmentTree` resolves environment paths, and existing dataclasses match the TOML schema.

## Existing Tool Considered
The alternatives check records `not-applicable` for a refactor with no search and `Tool: none found`. The change uses the existing pydantic `TypeAdapter` and standard library `tomllib`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# cluster-secrets-loader Specification

## Purpose
The cluster Secrets loader reads `cluster-secrets.toml` into existing frozen dataclasses and combines environment rows with product rows.

## ADDED Requirements

### Requirement: File rows load into existing dataclasses
The loader SHALL build the existing `ClusterSecret` dataclasses from `cluster-secrets.toml`.

#### Scenario: One row of each source kind
- **WHEN** the test `tests/k8s/test_cluster_secrets_file.py` loads `tests/fixtures/cluster-secrets.toml` with one keyring, setting, literal and derived row
- **THEN** each loaded object equals the equal `ClusterSecret` Python row and `uv run pytest tests/k8s -q -k cluster_secret` passes.

### Requirement: Generator and adopt_from tables load
The file model SHALL read the generator and `adopt_from` tables for each row.

#### Scenario: A generated row and an adopted row
- **WHEN** the fixture file holds a generator table and an `adopt_from` table
- **THEN** the loaded `SecretEntry` has the same `SecretGenerator` and `SecretKeyRef` as the equal Python row, and `uv run pytest tests/k8s -q -k cluster_secret` passes.

### Requirement: Environment rows removed from code
The module `src/devops_cli/k8s/cluster_secrets.py` MUST contain no environment Secret rows after the change.

#### Scenario: No moved stack rows remain
- **WHEN** the test `tests/k8s/test_cluster_secret_source.py` runs `git grep -n -E 'stack=(BASE_STACK|"(chat|gitea|infra)")' src/`
- **THEN** the command finds no match, and `git grep -n 'name="valkey-' src/devops_cli/k8s/cluster_secrets.py` finds only `valkey-devops-auth` and `valkey-runs-auth`.

### Requirement: Push-secrets uses the environment file
`devops k8s push-secrets` MUST load the environment rows from `cluster-secrets.toml` and append the product rows.

#### Scenario: A fixture environment tree
- **WHEN** the test `tests/k8s/test_cluster_secret_push.py` runs with `--k8s-dir` pointing at a fixture environment tree
- **THEN** the plan contains each fixture row and each product row, and `uv run pytest tests/k8s -q -k cluster_secret` passes.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Tasks

## 1. Behavior

- [x] 1.1 Write failing test
- Verification: `$ uv run pytest tests/k8s/test_cluster_secrets_file.py tests/k8s/test_cluster_secret_source.py`
- [x] 1.2 Implement the TOML loader and file model
- Verification: `$ uv run pytest tests/k8s/test_cluster_secrets_file.py`
- [x] 1.3 Remove moved environment rows from cluster_secrets.py
- Verification: `$ uv run pytest tests/k8s/test_cluster_secret_source.py`
- [x] 1.4 Wire readers to load environment rows from cluster-secrets.toml
- Verification: `$ uv run pytest tests/k8s -q -k cluster_secret`

## 2. Verification

- [x] 2.1 Run scoped CI checks
- Verification: `$ uv run devops ci --check --only test,lint,typecheck`
34 changes: 34 additions & 0 deletions openspec/specs/cluster-secrets-loader/spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# cluster-secrets-loader Specification

## Purpose
The cluster Secrets loader reads `cluster-secrets.toml` into existing frozen dataclasses and combines environment rows with product rows.

## Requirements

### Requirement: File rows load into existing dataclasses
The loader SHALL build the existing `ClusterSecret` dataclasses from `cluster-secrets.toml`.

#### Scenario: One row of each source kind
- **WHEN** the test `tests/k8s/test_cluster_secrets_file.py` loads `tests/fixtures/cluster-secrets.toml` with one keyring, setting, literal and derived row
- **THEN** each loaded object equals the equal `ClusterSecret` Python row and `uv run pytest tests/k8s -q -k cluster_secret` passes.

### Requirement: Generator and adopt_from tables load
The file model SHALL read the generator and `adopt_from` tables for each row.

#### Scenario: A generated row and an adopted row
- **WHEN** the fixture file holds a generator table and an `adopt_from` table
- **THEN** the loaded `SecretEntry` has the same `SecretGenerator` and `SecretKeyRef` as the equal Python row, and `uv run pytest tests/k8s -q -k cluster_secret` passes.

### Requirement: Environment rows removed from code
The module `src/devops_cli/k8s/cluster_secrets.py` MUST contain no environment Secret rows after the change.

#### Scenario: No moved stack rows remain
- **WHEN** the test `tests/k8s/test_cluster_secret_source.py` runs `git grep -n -E 'stack=(BASE_STACK|"(chat|gitea|infra)")' src/`
- **THEN** the command finds no match, and `git grep -n 'name="valkey-' src/devops_cli/k8s/cluster_secrets.py` finds only `valkey-devops-auth` and `valkey-runs-auth`.

### Requirement: Push-secrets uses the environment file
`devops k8s push-secrets` MUST load the environment rows from `cluster-secrets.toml` and append the product rows.

#### Scenario: A fixture environment tree
- **WHEN** the test `tests/k8s/test_cluster_secret_push.py` runs with `--k8s-dir` pointing at a fixture environment tree
- **THEN** the plan contains each fixture row and each product row, and `uv run pytest tests/k8s -q -k cluster_secret` passes.
11 changes: 8 additions & 3 deletions src/devops_cli/commands/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,11 +264,16 @@ def _store_generated(key: str, *, rotate: bool, dry_run: bool) -> None:
keyring: no argument, file, log record or output holds it. A dry run prints the kind, the
byte count and a masked placeholder, and reads nothing.
"""
from devops_cli.k8s.cluster_secrets import generator_for_option, generator_option_names
from devops_cli.k8s.cluster_secrets import (
generator_for_option,
generator_option_names,
load_cluster_secrets_table,
)

generator = generator_for_option(key)
table = load_cluster_secrets_table()
generator = generator_for_option(key, table=table)
if generator is None:
options = ", ".join(generator_option_names())
options = ", ".join(generator_option_names(table=table))
print_error(
MESSAGES.config.generate_no_generator.format(key=key, options=options),
prefix=False,
Expand Down
54 changes: 40 additions & 14 deletions src/devops_cli/commands/k8s/cluster_secret_push.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@

from __future__ import annotations

from collections.abc import Sequence
from typing import Annotated
from collections.abc import Iterable, Sequence
from pathlib import Path
from typing import Annotated, Any

import typer

Expand All @@ -21,9 +22,9 @@
from devops_cli.exceptions.k8s import ClusterSecretPushError, ClusterSecretWriteError
from devops_cli.k8s.cluster_secrets import (
BASE_STACK,
CLUSTER_SECRETS,
DETACHED_STACKS,
ClusterSecret,
load_cluster_secrets_table,
secret_names,
secrets_by_ref,
secrets_for_stacks,
Expand All @@ -46,33 +47,43 @@
from devops_cli.output import print_error, print_info, print_warning


def _push_stacks() -> tuple[str, ...]:
def _push_stacks(table: tuple[ClusterSecret, ...] | None = None) -> tuple[str, ...]:
"""The stacks `--stack` accepts: the table's, deploy-stack's and `all`."""
return tuple(dict.fromkeys((BASE_STACK, *VALID_STACKS, *DETACHED_STACKS, *table_stacks())))
t = table if table is not None else load_cluster_secrets_table()
return tuple(dict.fromkeys((BASE_STACK, *VALID_STACKS, *DETACHED_STACKS, *table_stacks(t))))


def _select(stack: str, only: Sequence[str]) -> tuple[ClusterSecret, ...]:
def _select(
stack: str, only: Sequence[str], table: tuple[ClusterSecret, ...] | None = None
) -> tuple[ClusterSecret, ...]:
"""The rows `--only` names, else the rows of `--stack`; an unknown name exits 2."""
current_table = table if table is not None else load_cluster_secrets_table()
if only:
selected, unknown = secrets_by_ref(only)
selected, unknown = secrets_by_ref(only, table=current_table)
if unknown:
print_error(
MESSAGES.k8s.push_unknown_secret.format(
names=", ".join(unknown), known=", ".join(secret_names())
names=", ".join(unknown), known=", ".join(secret_names(current_table))
),
prefix=False,
safe=True,
)
raise typer.Exit(2)
return selected
if stack not in _push_stacks():
if stack not in _push_stacks(current_table):
print_error(
MESSAGES.k8s.push_unknown_stack.format(stack=stack, known=", ".join(_push_stacks())),
MESSAGES.k8s.push_unknown_stack.format(
stack=stack, known=", ".join(_push_stacks(current_table))
),
prefix=False,
safe=True,
)
raise typer.Exit(2)
return CLUSTER_SECRETS if stack == CONST_K8S_ALL_STACKS else secrets_for_stacks([stack])
return (
current_table
if stack == CONST_K8S_ALL_STACKS
else secrets_for_stacks([stack], table=current_table)
)


def _render(plan: PushPlan, options: PushOptions, *, preview: bool) -> None:
Expand Down Expand Up @@ -174,9 +185,22 @@ def run_push(
return PushResult(mode, plan)


def push_for_stacks(stacks: Sequence[str], context: str | None) -> None:
def push_for_stacks(
stacks: Sequence[str],
context: str | None,
table: Iterable[ClusterSecret] | None = None,
k8s_dir: Path | None = None,
env: Any = None,
) -> None:
"""deploy-stack's push: its stacks' rows with `--stack` semantics, no rotation, restarts on."""
run_push(secrets_for_stacks(stacks), PushOptions(context=context), mode=PushMode.PUSH)
full_table = (
tuple(table) if table is not None else load_cluster_secrets_table(env=env, k8s_dir=k8s_dir)
)
run_push(
secrets_for_stacks(stacks, table=full_table),
PushOptions(context=context),
mode=PushMode.PUSH,
)


@dry_run_class("request-plan")
Expand All @@ -196,6 +220,7 @@ def push_secrets(
] = None,
plan: Annotated[bool, typer.Option("--plan", help=HELP.k8s.push_plan)] = False,
dry_run: Annotated[bool, typer.Option("--dry-run", help=HELP.k8s.push_dry_run)] = False,
k8s_dir: Annotated[Path | None, typer.Option("--k8s-dir", help=HELP.k8s.k8s_dir)] = None,
) -> None:
"""Write the cluster's Secrets from the OS keyring: workstation keyring → cluster.

Expand All @@ -205,7 +230,8 @@ def push_secrets(
effective_context = runtime.resolve_effective_context(context)
if effective_context:
runtime._validate_kubeconfig_context_name(effective_context, "context")
selected = _select(stack, only or [])
table = load_cluster_secrets_table(k8s_dir=k8s_dir)
selected = _select(stack, only or [], table=table)
options = PushOptions(
context=effective_context,
rotate=rotate,
Expand Down
23 changes: 17 additions & 6 deletions src/devops_cli/commands/k8s/stack_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
from devops_cli.k8s.cluster_secrets import (
BASE_STACK,
DETACHED_STACKS,
load_cluster_secrets_table,
secrets_for_stacks,
)
from devops_cli.k8s.configmap import (
Expand Down Expand Up @@ -915,7 +916,8 @@ def _post_deploy_credentials(
if "infra" in selected_stacks:
from devops_cli.k8s.credentials import sync_k8s_credentials

_report_credential_sync(sync_k8s_credentials(context=effective_context, stack="infra"))
infra_stack = "infra"
_report_credential_sync(sync_k8s_credentials(context=effective_context, stack=infra_stack))
print_info(
"[dim]Tempo HTTP API: http://localhost:3200 (namespace: otel)[/dim]",
prefix=False,
Expand Down Expand Up @@ -969,7 +971,9 @@ def _push_stacks_for(selected_stacks: Sequence[str], context: str | None) -> lis
return [BASE_STACK, *selected_stacks, *detached]


def _dry_run_secrets(selected_stacks: Sequence[str], push_secrets: bool) -> list[str]:
def _dry_run_secrets(
selected_stacks: Sequence[str], push_secrets: bool, env: EnvironmentTree | None = None
) -> list[str]:
"""The Secrets and key names a deploy would push, from the table alone, running nothing.

A detached stack's rows are pushed only where its namespace exists, which a dry run does
Expand All @@ -978,10 +982,11 @@ def _dry_run_secrets(selected_stacks: Sequence[str], push_secrets: bool) -> list
if not push_secrets:
return []
detached = set(DETACHED_STACKS) - set(selected_stacks)
table = load_cluster_secrets_table(env=env)
return [
f"{secret.ref}: {', '.join(entry.key for entry in secret.entries)}"
+ (f" (if namespace {secret.namespace} exists)" if secret.stack in detached else "")
for secret in secrets_for_stacks([BASE_STACK, *selected_stacks, *detached])
for secret in secrets_for_stacks([BASE_STACK, *selected_stacks, *detached], table=table)
]


Expand Down Expand Up @@ -1504,6 +1509,7 @@ def _handle_argo_managed_deployment(
sandbox_config_map: str | None,
domain: str | None = None,
revision: str | None = None,
env: EnvironmentTree | None = None,
) -> None:
"""Supply the values git never holds, and leave every manifest to Argo CD.

Expand All @@ -1515,7 +1521,9 @@ def _handle_argo_managed_deployment(
overrides = _homelab_host_overrides(selected_stacks, domain, revision, kubectl_ctx)
if push_secrets:
print_info(MESSAGES.k8s.pushing_secrets, prefix=False)
push_for_stacks(_push_stacks_for(selected_stacks, effective_context), effective_context)
push_for_stacks(
_push_stacks_for(selected_stacks, effective_context), effective_context, env=env
)
if config_map is not None:
_apply_rendered(config_map, f"ConfigMap {CONST_K8S_DEVOPS_CONFIGMAP}", kubectl_ctx)
if sandbox_config_map is not None:
Expand Down Expand Up @@ -1630,7 +1638,7 @@ def _render_deploy_stack_dry_run(
"port_forward": port_forward,
"configure_urls": configure_urls,
"config_writes": config_writes,
"secrets": _dry_run_secrets(selected_stacks, push_secrets),
"secrets": _dry_run_secrets(selected_stacks, push_secrets, env=env),
"helm_releases": [r["name"] for r in all_releases],
"helm_commands": helm_commands,
"source_fetches": [list(command) for command in source_fetches],
Expand Down Expand Up @@ -1784,6 +1792,7 @@ def deploy_stack(
sandbox_config_map,
domain=domain,
revision=argocd_revision,
env=env,
)
return

Expand All @@ -1796,7 +1805,9 @@ def deploy_stack(
# 5. Push the stacks' Secrets before anything reads them
if push_secrets:
print_info(MESSAGES.k8s.pushing_secrets, prefix=False)
push_for_stacks(_push_stacks_for(selected_stacks, effective_context), effective_context)
push_for_stacks(
_push_stacks_for(selected_stacks, effective_context), effective_context, env=env
)

# 5b. Verify Helm version requirement before Helm operations
is_v4 = _check_helm_version_for_deploy(all_releases)
Expand Down
Loading