TExcelTAD
Home › Platform Engineering: Internal Developer Platforms › OpenCost & Cost Labels in Practice

OpenCost & Cost Labels in Practice

OpenCost (a CNCF incubating project, started by Kubecost) implements the allocation model from the previous lesson for real clusters. It reads resource requests and usage from Prometheus, prices nodes, volumes and load balancers from the cloud provider's pricing APIs (or a custom price sheet for on-premises clusters), and serves the result per container, Pod, namespace, controller or label through an API and a UI. This lesson covers running it (sample), querying it, and the CI check that keeps its numbers meaningful.

Running it

OpenCost needs Prometheus (it reads cAdvisor and kube-state-metrics series). With the Prometheus from the Observability stack in place, it installs from its Helm chart (sample session; check opencost.io for the current chart values):

bash
$ helm repo add opencost https://opencost.github.io/opencost-helm-chart
$ helm install opencost opencost/opencost --namespace opencost --create-namespace \
    --set opencost.prometheus.internal.serviceName=prometheus-server \
    --set opencost.prometheus.internal.namespaceName=monitoring
$ kubectl -n opencost port-forward deployment/opencost 9003 9090

Port 9090 serves the UI, port 9003 the API. It also exports Prometheus metrics, such as per-node hourly prices, so Grafana dashboards and alerts can use cost data directly.

The allocation API

GET /allocation takes a window (7d, lastweek, or an RFC 3339 range), an aggregate (namespace, controller, label:team, or a comma-separated combination), an optional step and flags for idle cost (includeIdle, shareIdle). Aggregating by the team label for the last week, with a trimmed sample response:

bash
$ curl -s "http://localhost:9003/allocation?window=7d&aggregate=label:team&includeIdle=true"
json
{"code": 200, "data": [{
  "growth":          {"name": "growth",  "cpuCost": 18.42, "ramCost": 6.10, "pvCost": 2.40, "totalCost": 26.92, "cpuEfficiency": 0.27, "totalEfficiency": 0.31},
  "links":           {"name": "links",   "cpuCost": 14.10, "ramCost": 4.85, "pvCost": 1.20, "totalCost": 20.15, "cpuEfficiency": 0.81, "totalEfficiency": 0.74},
  "__unallocated__": {"name": "__unallocated__", "cpuCost": 2.30, "ramCost": 0.90, "pvCost": 0.00, "totalCost": 3.20, "cpuEfficiency": 0.55, "totalEfficiency": 0.52},
  "__idle__":        {"name": "__idle__", "cpuCost": 31.80, "ramCost": 11.60, "pvCost": 0.00, "totalCost": 43.40}
}]}

The fields follow the model: costs per resource type, __unallocated__ for workloads without the label, __idle__ for unreserved capacity, and efficiency (usage ÷ what was paid for). The response shape here is trimmed to the fields used below; the real one has more (windows, properties, GPU, network and load-balancer costs).

Turning the response into a weekly report

The platform's weekly cost report for the portal or a chat channel is a jq one-pager over that response. The session saves the sample response above and builds it:

bash · try it yourself
cat > allocation.json <<'EOF'
{"code": 200, "data": [{
  "growth":          {"name": "growth",  "cpuCost": 18.42, "ramCost": 6.10, "pvCost": 2.40, "totalCost": 26.92, "cpuEfficiency": 0.27, "totalEfficiency": 0.31},
  "links":           {"name": "links",   "cpuCost": 14.10, "ramCost": 4.85, "pvCost": 1.20, "totalCost": 20.15, "cpuEfficiency": 0.81, "totalEfficiency": 0.74},
  "__unallocated__": {"name": "__unallocated__", "cpuCost": 2.30, "ramCost": 0.90, "pvCost": 0.00, "totalCost": 3.20, "cpuEfficiency": 0.55, "totalEfficiency": 0.52},
  "__idle__":        {"name": "__idle__", "cpuCost": 31.80, "ramCost": 11.60, "pvCost": 0.00, "totalCost": 43.40}
}]}
EOF
jq -r '
  def money: (. * 100 | round) as $c | "$\($c / 100 | floor).\($c % 100 | tostring | if length < 2 then "0" + . else . end)";
  def pad($n): . + " " * ($n - length);
  def pct: . * 100 | round | tostring + "%";
  .data[0] | to_entries | map(.value) as $all
  | ($all | map(.totalCost) | add) as $total
  | "cluster, last 7 days: \($total | money)",
    ($all | sort_by(-.totalCost)[]
      | "  \(.name | pad(16)) \(.totalCost | money | pad(7)) \(.totalCost / $total | pct | pad(4))"
        + (if .totalEfficiency then "  efficiency \(.totalEfficiency | pct)" else "" end)),
    "actions:",
    ($all[] | select(.totalEfficiency != null and .totalEfficiency < 0.5 and (.name | startswith("__") | not))
      | "  \(.name): efficiency \(.totalEfficiency | pct), review requests (could save ~\(.totalCost * (1 - .totalEfficiency) * 0.7 | money)/week)"),
    ($all[] | select(.name == "__unallocated__")
      | "  label the unallocated workloads: \(.totalCost | money) a week has no owner"),
    ($all[] | select(.name == "__idle__")
      | "  idle is \(.totalCost / $total | pct) of the cluster: platform team to review node sizes")
' allocation.json
cluster, last 7 days: $93.67
  __idle__         $43.40  46%
  growth           $26.92  29%   efficiency 31%
  links            $20.15  22%   efficiency 74%
  __unallocated__  $3.20   3%    efficiency 52%
actions:
  growth: efficiency 31%, review requests (could save ~$13.00/week)
  label the unallocated workloads: $3.20 a week has no owner
  idle is 46% of the cluster: platform team to review node sizes

(The "could save" line assumes requests can come down to cover 70% of the waste, which is the kind of assumption a report should state.)

Keeping labels honest in CI

Allocation by label:team is only as good as the labels. The cheapest enforcement is in the pull request: render the chart and fail if any workload's Pod template misses a required label (OpenCost and Prometheus see Pod labels, not the Deployment's own metadata.labels):

bash · try it yourself
mkdir -p chart/templates
cat > chart/Chart.yaml <<'EOF'
apiVersion: v2
name: shortlinks
version: 0.1.0
EOF
cat > chart/values.yaml <<'EOF'
team: growth
costCenter: cc-4410
EOF
cat > chart/templates/workloads.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shortlinks
  labels: {team: {{ .Values.team }}}
spec:
  selector: {matchLabels: {app: shortlinks}}
  template:
    metadata:
      labels: {app: shortlinks, team: {{ .Values.team }}, cost-center: {{ .Values.costCenter }}}
    spec:
      containers: [{name: app, image: "ghcr.io/acme/shortlinks:0.1.0"}]
---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: shortlinks-cleanup
spec:
  schedule: "0 3 * * *"
  jobTemplate:
    spec:
      template:
        metadata:
          labels: {app: shortlinks-cleanup}
        spec:
          restartPolicy: OnFailure
          containers: [{name: cleanup, image: "ghcr.io/acme/shortlinks:0.1.0", args: [cleanup]}]
EOF
helm template shortlinks chart > rendered.yaml
kubeconform -n 1 -strict -summary rendered.yaml
yq -N '
  select(.kind == "Deployment" or .kind == "StatefulSet" or .kind == "DaemonSet" or .kind == "CronJob")
  | (.spec.template // .spec.jobTemplate.spec.template) as $pod
  | .kind + "/" + .metadata.name + " " + ((["team", "cost-center"] - ($pod.metadata.labels | keys)) | join(","))
' rendered.yaml | while read -r workload missing; do
  if [ -n "$missing" ]; then echo "FAIL $workload: pod template lacks $missing"; else echo "ok   $workload"; fi
done
Summary: 2 resources found in 1 file - Valid: 2, Invalid: 0, Errors: 0, Skipped: 0
ok   Deployment/shortlinks
FAIL CronJob/shortlinks-cleanup: pod template lacks team,cost-center

The CronJob's Pods would land in __unallocated__. The real fix belongs in the golden path: a _helpers.tpl with a labels template that every workload template includes, so new workloads get the labels without anyone remembering (Helm: named templates). In the cluster, a Kyverno or Gatekeeper policy can enforce the same rule at admission (Secrets & Policy: admission policies).

Showing costs where teams look

  • In the portal, on each service's and team's page (Backstage has OpenCost and cloud-cost plugins).
  • In pull requests, for infrastructure changes: tools such as Infracost estimate the monthly cost difference of a Terraform plan and comment it on the PR.
  • In the weekly report, with actions, not just numbers.
  • In budgets and alerts per team and per cloud account, so surprises are found in days, not at month end.

Test yourself

Which OpenCost API parameter gives costs per value of the team label?

  1. window=team
  2. aggregate=label:team
  3. filter=team
  4. step=team

Why does the CI check look at the Pod template's labels instead of the Deployment's metadata.labels?

  1. Deployments can't have labels
  2. Cost tools allocate by the labels on the running Pods, which come from the Pod template
  3. kubeconform requires it
  4. Pod labels are cheaper

What does a low totalEfficiency for a team mean?

  1. The team's code is slow
  2. The team pays for much more capacity (requests) than it uses: a rightsizing opportunity
  3. The cluster is full
  4. Prometheus is missing data