devops

Build a Kubernetes Orphaned ConfigMap and Secret Agent: Find the Unused Ones, Prove Nothing Reads Them with Pod Templates and Audit Logs, and Delete Them Without Breaking a Rollback

Build an agent that finds unused ConfigMaps and Secrets in Kubernetes, proves nothing reads them with pod templates and audit logs, then deletes them safely.

December 4, 2026·12 min read·
#ai#devops#kubernetes#security#automation#gitops#platform-engineering

What This Agent Does

To find unused ConfigMaps and Secrets in Kubernetes, you list every ConfigMap and Secret, subtract everything a pod template, Ingress, or ServiceAccount refers to, and then check the API server audit log for anything that reads the rest by name. What survives all three checks is an orphan candidate. This agent runs that pipeline on a schedule, sorts the survivors into tiers, and removes them through a Git pull request or a two-week quarantine. It never deletes on the first pass.

The popular one-liner for this job compares kubectl get configmaps against the volumes and env of running pods. It is wrong in three ways that cause outages:

  • It only looks at running pods. A CronJob that runs on the first of the month has no pod today. Its ConfigMap looks unused for 29 days out of 30.
  • It ignores rollback history. A Deployment keeps 10 old ReplicaSets by default. Each one may point at an older ConfigMap. Delete that ConfigMap, run kubectl rollout undo during an incident, and the new pods sit in CreateContainerConfigError.
  • It cannot see API readers. Argo CD finds its repository credentials by Secret label. The Grafana sidecar loads dashboards from labelled ConfigMaps. ingress-nginx takes a ConfigMap name from a command-line flag. None of these appear in any volume.

This is a hygiene and security job, not a cost job. An orphaned ConfigMap costs nothing on the bill. An orphaned Secret is a working credential that nobody owns, and fourteen ConfigMaps named app-config-something slow down whoever is debugging at night.

The Five Tiers

TierEvidenceWhat the agent does
Live referenceNamed by a pod template, Ingress TLS block, or ServiceAccountNothing
Rollback onlyNamed only by a ReplicaSet at 0 replicas or a ControllerRevisionKeeps it, reports the age of the history
Read through the APIA named get or watch in the audit log from a service accountKeeps it, records the reader
Name mentionedThe name appears in some other object, such as a custom resource or a container argumentHands it to a human with the location
Orphan candidateNone of the above, and older than 30 daysPR or quarantine

Step 1: Inventory Without Reading Secret Values

The agent needs Secret names, labels, types, and owners. It does not need the values, and an LLM pipeline should never hold them. The API server can return metadata only if you ask for a PartialObjectMetadataList:

# orphans/inventory.py
import json
from kubernetes import client, config

config.load_incluster_config()
api = client.ApiClient()
META = "application/json;as=PartialObjectMetadataList;g=meta.k8s.io;v=v1"

def metadata_only(resource: str) -> list[dict]:
    resp = api.call_api(f"/api/v1/{resource}", "GET",
                        query_params=[("limit", "500")],
                        header_params={"Accept": META},
                        auth_settings=["BearerToken"],
                        _preload_content=False)[0]
    return json.loads(resp.data)["items"]   # add `continue` paging for big clusters

Be honest about what this protects. The RBAC permission is still list on Secrets, and that permission can read values. The header keeps values out of the agent's memory and logs. It is discipline, not enforcement. One side effect: the Secret type field is not metadata, so the agent recognises system Secrets by name and label instead.

Next, drop everything that is managed by something else:

SYSTEM_NS = {"kube-system", "kube-public", "kube-node-lease"}
DISCOVERY_LABELS = ("argocd.argoproj.io/secret-type", "grafana_dashboard",
                    "grafana_datasource")

def excluded(resource: str, m: dict) -> str | None:
    labels, notes = m.get("labels") or {}, m.get("annotations") or {}
    if m["namespace"] in SYSTEM_NS:              return "system namespace"
    if m.get("ownerReferences"):                 return "owned by a controller"
    if m["name"] == "kube-root-ca.crt":          return "published by kube-controller-manager"
    if labels.get("owner") == "helm":            return "helm release history"
    if "kubernetes.io/service-account.name" in notes:
        return "service account token"
    if any(k in labels for k in DISCOVERY_LABELS):
        return "found by label, not by reference"
    return None

ownerReferences covers Secrets written by External Secrets and Sealed Secrets, which the garbage collector already cleans up. It does not cover cert-manager: by default a TLS Secret outlives its Certificate. Check the cert-manager.io/certificate-name annotation, and if the Certificate it names is gone, the Secret stays in the candidate list.

Step 2: Collect References from Pod Templates, Not Pods

Every workload kind buries its pod spec at a different path: spec.template.spec for a Deployment, spec.jobTemplate.spec.template.spec for a CronJob, data.spec.template.spec for a ControllerRevision. Rather than encode each path, walk the object and treat any dict with a containers list as a pod spec. This also picks up custom resources that embed a pod template, such as an Argo Rollout.

# orphans/refs.py
import json, subprocess

WORKLOADS = ("pods,deployments,replicasets,statefulsets,daemonsets,"
             "jobs,cronjobs,controllerrevisions,rollouts.argoproj.io")

def kget(resource: str) -> list[dict]:
    out = subprocess.run(["kubectl", "get", resource, "-A", "-o", "json"],
                         capture_output=True, text=True, check=True).stdout
    return json.loads(out)["items"]

def pod_specs(node):
    if isinstance(node, dict):
        if isinstance(node.get("containers"), list):
            yield node
        for v in node.values():
            yield from pod_specs(v)
    elif isinstance(node, list):
        for v in node:
            yield from pod_specs(v)

def spec_refs(spec: dict) -> set[tuple[str, str]]:
    refs = set()
    for kind in ("containers", "initContainers", "ephemeralContainers"):
        for c in spec.get(kind) or []:
            for e in c.get("envFrom") or []:
                if "configMapRef" in e: refs.add(("configmaps", e["configMapRef"]["name"]))
                if "secretRef" in e:    refs.add(("secrets", e["secretRef"]["name"]))
            for e in c.get("env") or []:
                src = e.get("valueFrom") or {}
                if "configMapKeyRef" in src: refs.add(("configmaps", src["configMapKeyRef"]["name"]))
                if "secretKeyRef" in src:    refs.add(("secrets", src["secretKeyRef"]["name"]))
    for v in spec.get("volumes") or []:
        for s in [v] + ((v.get("projected") or {}).get("sources") or []):
            if "configMap" in s:
                refs.add(("configmaps", s["configMap"]["name"]))
            if "secret" in s:   # plain volumes say secretName, projected sources say name
                refs.add(("secrets", s["secret"].get("secretName") or s["secret"].get("name")))
    for p in spec.get("imagePullSecrets") or []:
        refs.add(("secrets", p["name"]))
    return refs

def collect() -> dict[tuple, set[str]]:
    seen: dict[tuple, set[str]] = {}
    for obj in kget(WORKLOADS):
        ns = obj["metadata"]["namespace"]
        history = obj["kind"] == "ControllerRevision" or (
            obj["kind"] == "ReplicaSet" and obj["spec"].get("replicas") == 0)
        for spec in pod_specs(obj):
            for resource, name in spec_refs(spec):
                seen.setdefault((resource, ns, name), set()).add(
                    "history" if history else "live")
    for ing in kget("ingresses"):
        for tls in ing["spec"].get("tls") or []:
            if tls.get("secretName"):
                key = ("secrets", ing["metadata"]["namespace"], tls["secretName"])
                seen.setdefault(key, set()).add("live")
    for sa in kget("serviceaccounts"):
        for ref in (sa.get("imagePullSecrets") or []) + (sa.get("secrets") or []):
            key = ("secrets", sa["metadata"]["namespace"], ref["name"])
            seen.setdefault(key, set()).add("live")
    return seen

Remove rollouts.argoproj.io from the list if the CRD is not installed, or kubectl exits non-zero.

A reference whose only tag is history lands in the rollback-only tier. That tier is where most real clutter lives. Kustomize's configMapGenerator appends a content hash to the name, so every config change creates a new ConfigMap such as app-config-7g2k9d8m4t, and without pruning the old ones stay forever. The correct move is to wait: once the ReplicaSet that names it rotates out of revisionHistoryLimit, the ConfigMap drops to the candidate tier by itself on a later run.

Step 3: Catch References You Have No Schema For

Custom resources point at Secrets in dozens of shapes: a cert-manager Issuer's privateKeySecretRef, a ServiceMonitor's basicAuth, a Gateway's certificateRefs. Controllers also take names in arguments, like --configmap=ingress-nginx/tcp-services. Writing a parser per CRD does not scale, so use a blunt check instead. Dump every listable resource except Secrets, ConfigMaps, and Events, split the text into name-shaped tokens, and see whether the candidate's name appears anywhere.

import re

SKIP = {"secrets", "configmaps", "events", "events.events.k8s.io"}

def mention_tokens() -> set[str]:
    kinds = subprocess.run(["kubectl", "api-resources", "--verbs=list", "-o", "name"],
                           capture_output=True, text=True, check=True).stdout.split()
    tokens: set[str] = set()
    for kind in kinds:
        if kind in SKIP:
            continue
        r = subprocess.run(["kubectl", "get", kind, "-A", "-o", "json"],
                           capture_output=True, text=True)
        if r.returncode == 0:
            tokens |= set(re.findall(r"[a-z0-9-]+", r.stdout))
    return tokens

This over-matches on purpose. A Secret named redis will match any object that says "redis" anywhere. That is fine, because a match only moves the object to the "name mentioned" tier for a human, and a false keep is cheap. A hashed name like app-config-7g2k9d8m4t matches nothing unless something truly refers to it.

Step 4: Ask the Audit Log Who Reads It

The last class is code that calls the Kubernetes API at runtime with a name that exists only in its own source or config. Only the audit log can see it. On EKS with audit logging turned on, the query in CloudWatch Logs Insights is:

fields @timestamp
| filter @logStream like /kube-apiserver-audit/
| filter objectRef.resource in ["configmaps", "secrets"]
| filter verb in ["get", "watch"] and ispresent(objectRef.name)
| filter user.username != "system:serviceaccount:platform:orphan-agent"
| stats count() as reads, max(@timestamp) as last_read
    by objectRef.resource, objectRef.namespace, objectRef.name, user.username
| limit 10000

Run it per namespace over 30 days. Logs Insights bills per GB scanned and audit logs are large, so a 30-day cluster-wide scan is not free. The CloudWatch Logs cost agent covers how to see what that log group costs you. The same log source powers the RBAC right-sizing agent, so you can share one export between the two.

Read the results by identity:

  • system:node:... is a kubelet fetching the object for a pod. Step 2 should already have it. If it does not, your reference walker has a gap, and you should fix that before trusting anything else.
  • system:serviceaccount:... is a controller or an app reading through the API. Keep the object and record the reader.
  • A human user means somebody looked at it. That is not a consumer, but it is the right person to ask.

One blind spot remains. A controller that lists or watches every Secret in a namespace produces audit events with no object name, so this query cannot tell which objects it actually uses. Run the same query for list and watch events without a name, grouped by user and namespace. If a candidate carries labels beyond the standard app.kubernetes.io set and a namespace-wide watcher exists, send it to a human with the watcher's name attached.

Step 5: Where the LLM Fits

Steps 1 to 4 are set arithmetic, and an LLM adds nothing to them. It earns its place on the survivors, where the question changes from "is this referenced" to "what was this, and who do I ask". The model gets metadata only:

SYSTEM = """You triage Kubernetes ConfigMaps and Secrets that no workload references.
For each candidate return JSON with:
  category: superseded_version | leftover_of_deleted_workload | manual_debug_artifact
            | possibly_read_at_runtime | unknown
  evidence: one sentence that cites fields from the input only
  ask: the team or person to confirm with, taken from labels, annotations, or creator
You can only make a candidate MORE protected. If the name or labels suggest
leader election, feature flags, licence keys, or break-glass credentials,
use possibly_read_at_runtime. Never invent a workload name."""

candidate = {
    "resource": "configmaps", "namespace": "payments", "name": "checkout-flags-old",
    "age_days": 212, "labels": {"app.kubernetes.io/part-of": "checkout"},
    "created_by": "jane@acme.io",                     # from the audit log, if in range
    "similar_live_objects": ["checkout-flags"],       # same prefix, still referenced
    "gitops_tracked": False, "last_human_read": None,
}

Send it through whatever gateway your agents already use. Ours go through the LiteLLM proxy under a per-agent budget. The rule that matters is in the prompt and is also enforced in code: possibly_read_at_runtime and unknown move a candidate to the human tier, and no model output can move anything toward deletion. The model writes the PR description and the message to the owner. It does not decide.

Step 6: Remove with an Undo

Kubernetes has no recycle bin, so the agent builds the undo first.

Tracked in Git. If the object carries an Argo CD tracking annotation or the label app.kubernetes.io/managed-by: Helm, deleting it in the cluster is pointless because the next sync recreates it. The agent opens a PR that removes it from the repo, following the same pull requests, not kubectl rule as every other agent in this series. git revert is the undo.

Created by hand. The agent annotates the object and waits:

kubectl annotate configmap checkout-flags-old -n payments \
  cleanup.acme.io/candidate-since=2026-12-04 \
  cleanup.acme.io/reason="no pod template, mention, or API read in 30d"

After 14 days it re-runs every check from scratch. If the object is still clean and a human has approved the batch, a separate job with delete on only these two resources removes it. For a ConfigMap, the YAML is committed to a graveyard/ folder first. For a Secret, the job confirms that the object is in the latest verified Velero backup and does not export it anywhere.

The delete call carries preconditions, so it fails if anyone touched the object after it was evaluated:

from kubernetes import client

def guarded_delete(ns: str, name: str, uid: str, resource_version: str) -> None:
    opts = client.V1DeleteOptions(preconditions=client.V1Preconditions(
        uid=uid, resource_version=resource_version))
    client.CoreV1Api().delete_namespaced_config_map(name, ns, body=opts)

If someone edits the ConfigMap or recreates it under the same name during the window, the API returns 409 Conflict and the object goes back to the start of the queue.

Honest Limits

  • Thirty days is a guess. A quarterly billing job or a disaster-recovery script reads its Secret four times a year or never until the bad day. Tie the look-back to your longest scheduled job, and treat anything labelled for DR as permanent.
  • Audit logs must exist. On a cluster with audit logging off, step 4 is missing and every candidate should go to a human. Do not let the agent quarantine on steps 2 and 3 alone.
  • Readers outside the cluster are partly visible. A CI job that runs kubectl get secret shows up in the audit log under its own identity. A script that fetched the value once and cached it does not.
  • Deleting an orphaned Secret does not revoke the credential. The database password inside it still works. Pair the delete with the credential rotation agent so that the key is disabled at the source.
  • The token match is noisy for short names. Expect objects called config or redis to sit in the human tier forever. That is the price of the conservative default.

Summary

Finding unused ConfigMaps and Secrets is a subtraction problem with four terms: pod templates in every workload kind including history, the references held by Ingresses and ServiceAccounts, name mentions in everything else, and named reads in the audit log. Most scripts stop after the first half of the first term, and that is how a rollback breaks. Build the references from templates, let rollback history age out instead of forcing it, use the LLM only to explain the survivors and find their owners, and make every removal a PR or a 14-day quarantine with a guarded delete at the end.

#ai#devops#kubernetes#security#automation#gitops#platform-engineering
D
DevToCashAuthor

Senior DevOps/SRE Engineer · 10+ years · Professional Trader (IDX, Crypto, US Equities)

I write about real infrastructure patterns and trading strategies I use in production and in live markets. No courses, no affiliate hype — just documentation of what actually works.

More about me →