Skip to main content

OpenCost — Kubernetes Cost Tracking

OpenCost (CNCF incubating) breaks down your Kubernetes cluster costs by namespace, deployment, pod, and custom labels. See exactly which teams and services are consuming your cloud budget.

✓ CNCF open-source ✓ Namespace cost breakdown ✓ REST API ✓ Prometheus compatible

Helm Installation

# Add the OpenCost Helm repo
helm repo add opencost https://opencost.github.io/opencost-helm-chart
helm repo update

# Install OpenCost in the opencost namespace
helm install opencost opencost/opencost \
  --namespace opencost \
  --create-namespace \
  --set opencost.exporter.cloudProviderApiKey="AIzaSyD-9tSrke72..." \  # GCP only
  --set opencost.prometheus.internal.enabled=true

# For AWS, set the cluster region and node pricing
helm install opencost opencost/opencost \
  --namespace opencost \
  --create-namespace \
  --set opencost.exporter.aws.region=us-east-1 \
  --set opencost.prometheus.internal.enabled=true

# Access the UI (port-forward)
kubectl port-forward -n opencost svc/opencost 9090:9090 9003:9003 &
open http://localhost:9090

REST API — Query Namespace Costs

# Cost by namespace, last 7 days, accumulated total
curl "http://localhost:9090/model/allocation?window=7d&aggregate=namespace&accumulate=true" \
  | jq '.data[0] | to_entries | map({namespace: .key, cost: .value.totalCost}) | sort_by(-.cost)'

# Cost by deployment in a specific namespace
curl "http://localhost:9090/model/allocation?window=30d&aggregate=deployment&accumulate=true&filter=namespace:production" \
  | jq '.data[0] | to_entries[] | {deployment: .key, cost: .value.totalCost}'

# Cost by team label (requires pods to have label app.kubernetes.io/team)
curl "http://localhost:9090/model/allocation?window=7d&aggregate=label:team&accumulate=true"

# Daily cost breakdown for a namespace (accumulate=false)
curl "http://localhost:9090/model/allocation?window=14d&aggregate=namespace&accumulate=false&filter=namespace:staging" \
  | jq '.data[] | {date: .window.start, cost: .["staging"].totalCost}'

# Assets API — raw node/disk costs
curl "http://localhost:9090/model/assets?window=7d&aggregate=type&accumulate=true"

Python Script — Weekly Cost Report

import requests
import json

OPENCOST_URL = "http://localhost:9090"

def get_namespace_costs(window="7d"):
    resp = requests.get(f"{OPENCOST_URL}/model/allocation", params={
        "window": window,
        "aggregate": "namespace",
        "accumulate": "true"
    })
    data = resp.json()["data"][0]
    costs = [
        {"namespace": k, "cost": round(v["totalCost"], 2), "cpu": round(v["cpuCost"], 2), "memory": round(v["ramCost"], 2)}
        for k, v in data.items()
    ]
    return sorted(costs, key=lambda x: x["cost"], reverse=True)

def print_report():
    costs = get_namespace_costs("30d")
    total = sum(c["cost"] for c in costs)
    print(f"\\n=== Kubernetes Cost Report (Last 30 Days) ===")
    print(f"Total cluster cost: ${total:.2f}\\n")
    print(f"{'Namespace':<30} {'Total':>10} {'CPU':>10} {'Memory':>10}")
    print("-" * 65)
    for c in costs[:15]:
        print(f"{c['namespace']:<30} ${c['cost']:>9.2f} ${c['cpu']:>9.2f} ${c['memory']:>9.2f}")

print_report()

OpenCost vs Kubecost Comparison

Feature OpenCost (free) Kubecost Free
Cost allocation API✓ Full REST API✓ Full REST API
Basic UI✓ Minimal dashboard✓ Rich dashboard
Savings recommendations✗ Not included✓ Basic rightsizing
Multi-clusterManual aggregation✗ Paid only
Metric retentionPrometheus-backed15 days free
RBAC / SSO✗✗ Paid only
LicenseApache 2.0BSL / proprietary

Frequently Asked Questions

What is OpenCost and how is it different from Kubecost?▼

OpenCost is the open-source, CNCF-incubating project that originated as Kubecost's core cost allocation engine. Kubecost is the commercial product built on top of it. OpenCost provides the core cost allocation logic — breaking down cluster costs by namespace, deployment, pod, and label — and exposes a REST API and basic UI. Kubecost adds a richer UI, multi-cluster support, savings recommendations, RBAC, SSO, and 15-day metric retention in the free tier. For teams that want open-source with no vendor dependency, OpenCost is the right choice. For teams that need the recommendations engine and multi-cluster UI, Kubecost free tier (or commercial) is better.

How does OpenCost calculate the cost of each pod?▼

OpenCost models costs by allocating node costs proportionally to each pod's resource requests (CPU and memory). It queries the cloud provider's pricing API (or a custom on-prem price sheet) to get the hourly cost of each node. Then it divides that cost proportionally: if your pod requests 0.5 of a 2-CPU node, it's allocated 25% of the node's cost. Network and storage costs are also tracked. The key insight is that OpenCost uses requests (not actual utilization) for allocation, which means over-provisioned pods show up as expensive even if idle — a feature, not a bug.

How do I query OpenCost for namespace costs via the API?▼

OpenCost exposes a REST API at /model/allocation on port 9090. The key parameters are: window (time range, e.g., '7d' or 'lastmonth'), aggregate (dimension to group by: namespace, pod, deployment, label:team), and accumulate (true to sum the window, false for daily breakdown). Example: GET http://localhost:9090/model/allocation?window=7d&aggregate=namespace&accumulate=true returns total cost per namespace for the last 7 days. Add &filter=namespace:production to scope to one namespace. The API is the foundation for building custom dashboards in Grafana.

Can OpenCost track costs for on-premises Kubernetes clusters?▼

Yes. For on-prem clusters, OpenCost uses a custom pricing configuration instead of cloud pricing APIs. You define CPU and RAM costs per core/GB-hour in a ConfigMap, and OpenCost uses those rates for allocation. This is useful for bare-metal or private cloud environments where you want to do internal chargeback — showing each team their 'bill' based on resource consumption even if it's not a real cloud bill. Set pricingModel.defaultSpotCPUCoreHours and similar fields in the OpenCost ConfigMap.

Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$9/mo after trial · Cancel anytime

Want the full toolkit?

Get DevPlaybook Pro

Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →