Build a Read-Only Kubernetes Capacity Report with Python

Before changing a Kubernetes cluster, platform teams need to know what workloads have requested and what nodes can allocate. A read-only Python report can inventory declared CPU and memory requests per node, identify unscheduled pods, and produce a CSV for review. It cannot measure actual CPU or memory use, and it is not a full replacement for the Kubernetes scheduler or a metrics system.

This guide builds that report with the official Kubernetes Python client. It is designed for SREs, platform engineers, and Linux administrators who want a repeatable capacity snapshot without granting the script permission to change workloads. The use cases below are realistic patterns; they are examples, not claims of a verified production deployment.

What the report measures

Kubernetes schedules pods using declared resource requests and node allocatable resources. Requests are scheduling reservations, not live utilization. Limits are separate constraints that affect runtime behavior. A node can have low current CPU use and still have little schedulable capacity if workloads have reserved most of its allocatable CPU through requests.

The example reads nodes and pods, sums CPU and memory requests from regular containers by the node where each pod is currently assigned, compares those totals with node allocatable values, and writes a CSV file. It also counts pods without an assigned node. It deliberately performs no create, patch, update, or delete operation.

Read-only Python capacity report flow: platform engineer, least-privilege client, Kubernetes API node and pod data, then CSV results for human review.
A capacity snapshot informs a review; it does not make a production change.

Real-world industry use cases

  • Release readiness: a platform team reviews declared reservations before a high-traffic application rollout and checks whether a node pool has room for the expected replicas.
  • Pending pod triage: an SRE compares node allocatable CPU and memory with existing requests while investigating scheduler events. The report narrows the investigation; pod events and scheduling constraints still explain the exact decision.
  • Rightsizing review: a FinOps or capacity team compares request reservations with time-series metrics, then asks service owners to validate proposed request changes. The CSV alone is not a rightsizing recommendation.
  • Cluster consolidation planning: a platform group inventories scheduled reservations before considering a node-pool reduction. They also account for disruption budgets, topology, spare capacity, and peak demand.
  • Audit evidence: an operations team stores timestamped, access-controlled snapshots alongside change tickets to show what requests and allocatable values were visible during a review.

Prerequisites

  • Python 3.10 or later on a trusted Linux workstation or approved reporting host.
  • kubectl access to the target cluster through an approved kubeconfig context.
  • Permission to list nodes and pods. The script needs read-only API access; it does not need access to Secrets.
  • A protected location for the generated CSV, because node and workload names may be operationally sensitive.

Start with the cluster your current context targets. Confirm it before running a cluster-wide read:

kubectl config current-context
kubectl get nodes
kubectl auth can-i list nodes
kubectl auth can-i list pods --all-namespaces

Create a Python virtual environment

mkdir -p k8s-capacity-report
cd k8s-capacity-report
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install kubernetes

Save the following program as capacity_report.py. It uses the active kubeconfig context and writes a node-level CSV snapshot. The Kubernetes quantity parser understands common CPU and memory units such as cores, millicores, bytes, and binary memory suffixes.

from __future__ import annotations

import argparse
import csv
from collections import defaultdict
from decimal import Decimal
from pathlib import Path

from kubernetes import client, config
from kubernetes.utils.quantity import parse_quantity


def quantity(value: str | None) -> Decimal:
    """Parse a Kubernetes quantity; absent requests count as zero in this report."""
    return Decimal(0) if value is None else Decimal(parse_quantity(str(value)))


def percentage(requested: Decimal, allocatable: Decimal) -> str:
    if allocatable == 0:
        return ""
    return f"{(requested / allocatable * 100):.1f}"


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Read-only inventory of scheduled Kubernetes CPU and memory requests."
    )
    parser.add_argument(
        "--output",
        default="capacity-report.csv",
        help="CSV output path (default: capacity-report.csv)",
    )
    args = parser.parse_args()

    # This script uses only the current kubeconfig; it does not change cluster state.
    config.load_kube_config()
    v1 = client.CoreV1Api()

    nodes = v1.list_node().items
    pods = v1.list_pod_for_all_namespaces(watch=False).items

    totals = defaultdict(lambda: {"cpu": Decimal(0), "memory": Decimal(0), "pods": 0})
    pending_pods = 0

    for pod in pods:
        node_name = pod.spec.node_name
        if not node_name:
            pending_pods += 1
            continue

        totals[node_name]["pods"] += 1
        for container in pod.spec.containers or []:
            resources = container.resources
            requests = resources.requests if resources and resources.requests else {}
            totals[node_name]["cpu"] += quantity(requests.get("cpu"))
            totals[node_name]["memory"] += quantity(requests.get("memory"))

    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    fields = [
        "node",
        "pods_assigned",
        "cpu_requests_cores",
        "cpu_allocatable_cores",
        "cpu_request_percent",
        "memory_requests_bytes",
        "memory_allocatable_bytes",
        "memory_request_percent",
        "pending_unassigned_pods",
    ]

    with output_path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()

        for node in sorted(nodes, key=lambda item: item.metadata.name):
            name = node.metadata.name
            allocatable = node.status.allocatable or {}
            cpu_alloc = quantity(allocatable.get("cpu"))
            memory_alloc = quantity(allocatable.get("memory"))
            cpu_req = totals[name]["cpu"]
            memory_req = totals[name]["memory"]

            writer.writerow(
                {
                    "node": name,
                    "pods_assigned": totals[name]["pods"],
                    "cpu_requests_cores": f"{cpu_req:.3f}",
                    "cpu_allocatable_cores": f"{cpu_alloc:.3f}",
                    "cpu_request_percent": percentage(cpu_req, cpu_alloc),
                    "memory_requests_bytes": int(memory_req),
                    "memory_allocatable_bytes": int(memory_alloc),
                    "memory_request_percent": percentage(memory_req, memory_alloc),
                    "pending_unassigned_pods": pending_pods,
                }
            )

    print(f"Wrote {len(nodes)} node rows to {output_path}")
    print(f"Pods without an assigned node: {pending_pods}")
    print("Review the result; this is a request inventory, not live utilization.")


if __name__ == "__main__":
    main()

Run the report and inspect its output

python capacity_report.py --output reports/capacity-$(date +%F).csv
head -n 5 reports/capacity-$(date +%F).csv

The CSV contains one row per node, assigned pod count, summed CPU and memory requests for regular containers, allocatable capacity, request percentages, and the cluster-wide count of pods that have no assigned node. Your values depend on the cluster and workload definitions. Protect and date the report if it will be attached to an incident or change record.

Grant only the permissions the report needs

When the report must run inside a cluster, use a dedicated service account and a read-only ClusterRole. Listing nodes is a cluster-scoped operation; listing pods across namespaces is broad visibility, even though the verbs are read-only. Confirm that this scope is allowed by your organization. Do not bind the service account to the default service account or a cluster-admin role.

apiVersion: v1
kind: ServiceAccount
metadata:
  name: capacity-report
  namespace: observability
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: capacity-report-reader
rules:
  - apiGroups: [""]
    resources: ["nodes", "pods"]
    verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: capacity-report-reader
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: capacity-report-reader
subjects:
  - kind: ServiceAccount
    name: capacity-report
    namespace: observability

Review this manifest with the cluster owner before applying it. It grants read access to pod objects across namespaces; pod specifications can reveal internal workload metadata. If the report can run from an administrator-approved workstation with narrower access, use that instead. The code shown above loads kubeconfig, so an in-cluster version must explicitly load in-cluster configuration and use the dedicated service account.

Important limitations before making a capacity decision

  • The report sums regular application containers. Kubernetes calculates effective Pod requests with additional rules for init containers, restartable init sidecars, Pod-level resource settings, and Pod overhead. The example is therefore an inventory aid, not an exact scheduler simulation.
  • It reports requests, not live CPU or memory usage. Compare with a metrics system and examine peaks, not only a single snapshot.
  • It groups pods by their current node assignment. A Pending pod is counted but has no node to assign in this report.
  • It does not calculate fit for a new pod. Affinity, taints, topology spread, volume constraints, extended resources, ephemeral storage, priorities, and scheduling policies can all affect placement.
  • Request percentages above 100 percent can occur in the simplified report because of missing scheduling details, overlapping container assumptions, or unusual cluster features. Investigate the source data before interpreting the result.

Troubleshooting

SymptomLikely causeNext step
Forbidden when listing nodes or podsThe current identity lacks read permission.Check kubectl auth can-i and request the narrow read-only role through the normal access process.
Connection refused or timeoutWrong kubeconfig context, expired authentication, VPN issue, or unavailable API endpoint.Confirm the current context, test kubectl get nodes, and follow your cluster login process.
ImportError for KubernetesThe package was installed outside the active virtual environment.Activate .venv and run python -m pip show kubernetes.
Quantity parser errorA resource value uses a format or resource type not handled by the simple CPU/memory path.Inspect the raw request; keep the report limited to CPU and memory or add explicit handling with unit tests.
CSV percentages look too high or lowThe report is an approximate regular-container request inventory and omits scheduler-specific accounting details.Compare a sample node with Kubernetes API data and scheduler events; use a full scheduler-aware tool for placement analysis.
Many unassigned podsPods may be Pending, unscheduled, or otherwise have no node name.Inspect kubectl get pods -A and kubectl describe pod Events to identify the actual scheduling reason.

Frequently asked questions

Does this script change the cluster?

No. It calls list operations for nodes and pods and writes a local CSV file. The recommended permissions are only get and list for those API resources.

Does a 70% request value mean the node is 70% busy?

No. It means the simplified sum of declared requests is 70% of the node’s allocatable value. Live workload utilization must come from metrics.

Can I use the report to remove a node?

Not by itself. Use it as one input to a reviewed capacity plan that includes observed peaks, failure headroom, placement constraints, disruption budgets, and a tested rollback path.

Summary

A read-only Python report can make Kubernetes resource requests easier to review across nodes and namespaces. Its value is as a repeatable snapshot for platform engineering, release planning, and incident investigation. Keep its permissions narrow, protect its output, compare requests with real metrics, and consult scheduler events before recommending a production change.

Official references

Following a series? Find the reading order in Learning Paths and Technical Series.