FinOps & Cloud Cost Engineering
Stop guessing and start governing. Master Kubecost per-namespace chargeback, Infracost PR cost gates, Karpenter Spot automation, right-sizing with VPA, Reserved Instance strategy, and real enterprise techniques that save $100K+/month. Every command, every query, every decision a senior engineer makes.
Lesson objective
- What it teaches
- FinOps Architecture & Toolchain · Kubecost: Per-Namespace Chargeback · Infracost: Pre-Deploy Cost Gates in CI · Karpenter: Intelligent Spot Automation · Right-Sizing: VPA + AWS Compute Optimizer · RI/SP Strategy: Commitment Purchasing · Hands-On Enterprise Labs · Troubleshooting & Gotchas
- Why it matters
- A required lesson for FinOps / Cloud Optimization, DevOps / Platform Architect. Recommended for Cloud Engineer. See the role paths
- What you demonstrate
-
- Simulated lab: How we found it in 10 minutes with Kubecost CLI. Recorded as lab evidence.
- Predict 3 results this lesson prints. You mark each one yourself.
- Optional, real environment: 12 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
Real Incident: The $54,000 Monthly Surprise
Context: E-commerce platform, 200-node EKS cluster. AWS bill arrives: $54K over budget. CFO calls VP Engineering at 9pm.
Root Cause (discovered in 3 hours): A data engineering team had launched 40× r5.4xlarge On-Demand nodes for a Spark job — and forgotten to terminate them 6 weeks ago. No tagging, no namespace quotas, no budget alerts.
Blast Radius: $54,200 wasted. 6-week billing cycle. Team only noticed when CFO escalated.
# How we found it in 10 minutes with Kubecost CLI $ kubectl cost namespace --window 30d --show-cpu --show-memory --show-efficiency +-------------------+----------+-------+--------+------------+ | Namespace | CPU Cost | Mem | Total | Efficiency | +-------------------+----------+-------+--------+------------+ | spark-jobs | $41,200 | $9,800| $51,000| 3.2% | ← HERE | production | $12,400 | $3,100| $15,500| 67.4% | | staging | $1,200 | $400| $1,600| 54.1% | +-------------------+----------+-------+--------+------------+ $ kubectl get nodes -l spark=true --no-headers | wc -l 40 $ kubectl get nodes -l spark=true -o jsonpath='{.items[0].metadata.creationTimestamp}' 2024-12-03T14:22:00Z ← 6 weeks ago
Prevention implemented: ResourceQuota per namespace, Kubecost Budget alerts at 80% threshold, Karpenter TTL on Spark NodePool, mandatory cost-center tags enforced via OPA Gatekeeper.
FinOps Architecture & Toolchain 15.1
Enterprise FinOps operates across three layers: Visibility (what are we spending?), Optimization (how do we reduce waste?), and Governance (how do we prevent overspend?). The toolchain maps directly to these layers.
Daily billing breakdown] Kubecost[Kubecost
Per namespace/pod cost] Cloudwatch[CloudWatch
Resource utilization] end subgraph "OPTIMIZATION" Karpenter[Karpenter
Spot + consolidation] VPA[VPA
Right-size containers] Infracost[Infracost
Pre-deploy cost estimate] RightSizing[AWS Compute
Optimizer + Graviton] end subgraph "GOVERNANCE" Budgets[AWS Budgets
Alert + SNS → Slack] OPA[OPA Gatekeeper
Enforce cost labels] ResourceQuota[K8s ResourceQuota
Namespace spend caps] RISP[RI/SP Automation
Commitment purchasing] end CostExplorer --> Kubecost Kubecost --> Karpenter Kubecost --> Budgets Infracost --> ResourceQuota
Visibility First
You cannot optimize what you cannot see. Kubecost gives you per-Pod, per-Deployment, per-Namespace cost breakdown with CPU/Memory/Network/Storage split. Enable cost allocation tags in AWS before anything else.
Governance = Prevention
OPA policies that block untagged resources, K8s ResourceQuotas per team namespace, and Infracost PR gates are the only way to prevent the next $54K surprise. Reactive alerting alone is not enough.
Kubecost: Per-Namespace Chargeback 15.2
Kubecost is the de-facto standard for Kubernetes cost allocation. It runs as a Deployment in your cluster, scrapes Prometheus metrics, and maps CPU/memory requests to node pricing from cloud APIs.
# Install Kubecost on EKS with Spot node support $ helm repo add kubecost https://kubecost.github.io/cost-analyzer/ $ helm repo update $ helm install kubecost kubecost/cost-analyzer \ --namespace kubecost --create-namespace \ --set kubecostProductConfigs.productKey.enabled=true --set kubecostProductConfigs.productKey.secretname=kubecost-product-key \ --set global.prometheus.enabled=true \ --set global.grafana.enabled=true \ --set clusterName="prod-eks-us-east-1" \ --set serviceAccount.annotations."eks\.amazonaws\.com/role-arn"=arn:aws:iam::123456789:role/kubecost-sa # Unexecuted secret-backed installation; verify rollout and Settings privately. # Port-forward to access UI $ kubectl port-forward svc/kubecost-cost-analyzer 9090:9090 -n kubecost # Install kubectl-cost plugin $ kubectl krew install cost
# Query via kubectl-cost (CLI) — daily cost per namespace
kubectl cost namespace \
--window 7d \
--show-cpu --show-memory --show-network --show-efficiency \
--show-pv
# Query via Kubecost HTTP API — last 30 days, by deployment
curl "http://localhost:9090/model/allocation?window=30d&aggregate=deployment&accumulate=false" \
| jq '.data[0] | to_entries | sort_by(-.value.totalCost) | .[:10]'
# Get cost per label (e.g., team=payments)
kubectl cost label --label team=payments --window 30d
# Show idle (wasted) resources per namespace
kubectl cost namespace --show-efficiency --window 30d \
| awk 'NR>2 && $NF < 0.30 {print "LOW EFFICIENCY: "$0}'apiVersion: v1
kind: ConfigMap
metadata:
name: kubecost-alerts
namespace: kubecost
data:
alerts.json: |
{
"alerts": [
{
"type": "budget",
"threshold": 5000,
"window": "30d",
"aggregation": "namespace",
"filter": "namespace=payments",
"alertNames": ["payments-namespace-budget"]
},
{
"type": "efficiency",
"efficiencyThreshold": 0.25,
"window": "7d",
"aggregation": "deployment"
}
]
}#!/bin/bash
# Monthly chargeback report — send to finance team
KUBECOST_URL="http://kubecost-cost-analyzer.kubecost:9090"
MONTH=$(date -d "last month" +%Y-%m)
START="${MONTH}-01T00:00:00Z"
END=$(date -d "${MONTH}-01 +1 month -1 second" +%Y-%m-%dT%H:%M:%SZ)
curl -s "${KUBECOST_URL}/model/allocation?window=${START},${END}&aggregate=namespace&accumulate=true" \
| jq -r '
.data[0] | to_entries[] |
{
namespace: .key,
team: (.value.properties.labels.team // "untagged"),
cost_center: (.value.properties.labels."cost-center" // "UNKNOWN"),
total_usd: (.value.totalCost | . * 100 | round / 100),
cpu_usd: (.value.cpuCost | . * 100 | round / 100),
memory_usd: (.value.ramCost | . * 100 | round / 100),
efficiency_pct: ((.value.totalEfficiency // 0) * 100 | round)
}' | \
jq -r '[.namespace, .team, .cost_center, .total_usd, .efficiency_pct] | @csv' \
> /tmp/chargeback-${MONTH}.csv
echo "Chargeback report: /tmp/chargeback-${MONTH}.csv"
# Upload to S3 for Finance
aws s3 cp /tmp/chargeback-${MONTH}.csv s3://finops-reports/chargeback/- Install Kubecost on kind/EKS and access the UI dashboard
- Run
kubectl cost namespace --window 7dand identify the highest-cost namespace - Configure a Kubecost budget alert to fire when namespace cost exceeds $1000/month
- Generate and export a monthly chargeback CSV report
Secret references and exposure recovery
Unexecuted configuration review. Assumptions: Kubecost self-hosted 2.x, Helm 3, Kubernetes v1 Secret volumes and an existing installation; not a free local installation exercise. The trial token is not a product key. For licensed deployments the documented values are productKey.enabled and productKey.secretname; omit both for an unlicensed installation. The Secret must already contain productkey.json with a JSON key property, provisioned privately by your secret manager. Do not commit a Secret with data or stringData: base64 is reversible.
kubecostProductConfigs:
productKey:
enabled: true
secretname: kubecost-product-keyThe legacy budget/efficiency policy above is a policy sketch, not an automatically consumed ConfigMap. Do not add a fictional Slack secret-name field to Kubecost. This alternative receiver uses Alertmanager 0.28.x; it requires an existing alert producer that evaluates namespace spend and efficiency and sends alerts to Alertmanager. Wiring that producer is unvalidated here.
# Fragment of an existing Alertmanager Deployment pod spec.
# Secret kubecost-alert-secrets is provisioned privately with key slack-webhook.
volumes:
- name: slack-secret
secret:
secretName: kubecost-alert-secrets
containers:
- name: alertmanager
volumeMounts:
- name: slack-secret
mountPath: /etc/alertmanager/secrets
readOnly: trueroute:
receiver: finops-slack
receivers:
- name: finops-slack
slack_configs:
- api_url_file: /etc/alertmanager/secrets/slack-webhook
channel: '#finops'
send_resolved: trueExposure: literal CLI values can enter shell history, process arguments (ps and /proc), CI logs and Helm release values. ConfigMaps provide no secret protection. Kubernetes Secrets need encryption at rest and least-privilege RBAC; readers of a Secret or privileged pods can still expose it. A Slack URL authorizes posting and can be abused to spoof alerts.
Recover: revoke an exposed Slack webhook and issue a replacement; rotate the vendor key through its issuer, update the private store (Vault or AWS Secrets Manager through an already configured External Secrets Operator), wait for synchronization and volume refresh, and restart consumers if they cache credentials. Never print decoded Secrets. Check expected key names and mount references, validate Alertmanager configuration with amtool check-config alertmanager-finops.yaml, and send one approved synthetic alert to a sandbox channel. Verify the old webhook is revoked and new delivery succeeds without logging either URL. Remove exposed values from history/logs and investigate access; deleting a commit alone does not revoke a credential.
Official references: Kubecost 2.x product key, Alertmanager 0.28 configuration, Kubernetes v1 Secrets, Slack incoming webhooks and ESO overview (existing installation; verify its installed CRD version).
Infracost: Pre-Deploy Cost Gates in CI 15.3
Infracost parses Terraform plans and calculates the monthly cost delta before any infrastructure is deployed. Integrate it as a PR gate — block merges that increase cost by more than a threshold.
name: Infracost Cost Check
on:
pull_request:
paths:
- '**.tf'
- '**.tfvars'
jobs:
infracost:
name: Estimate infrastructure cost
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v4
# Generate plan for baseline (base branch)
- name: Setup Infracost
uses: infracost/actions/setup@v3
with:
api-key: ${{ secrets.INFRACOST_API_KEY }}
- name: Checkout base branch
uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.base.ref }}
path: base
- name: Generate Infracost baseline
run: |
infracost breakdown --path=base/terraform \
--format=json \
--out-file=/tmp/infracost-base.json
- name: Generate Infracost for PR
run: |
infracost breakdown --path=terraform \
--format=json \
--out-file=/tmp/infracost-pr.json
- name: Generate diff and post PR comment
run: |
infracost diff \
--path=/tmp/infracost-pr.json \
--compare-to=/tmp/infracost-base.json \
--format=json \
--out-file=/tmp/infracost-diff.json
infracost comment github \
--path=/tmp/infracost-diff.json \
--repo=$GITHUB_REPOSITORY \
--pull-request=${{ github.event.pull_request.number }} \
--github-token=${{ github.token }} \
--behavior=update
- name: Enforce cost policy
run: |
infracost comment github \
--path=/tmp/infracost-diff.json \
--policy-path=infracost-policy.rego \
--github-token=${{ github.token }} \
--repo=$GITHUB_REPOSITORY \
--pull-request=${{ github.event.pull_request.number }}version: 0.1
# Custom price overrides for reserved instances
# or private pricing agreements
projects:
- path: terraform/
name: prod-eks-cluster
terraform_vars:
environment: prod
region: us-east-1
# Exclude resources from cost check (e.g., tagging-only changes)
exclude_resources:
- aws_iam_role
- aws_iam_policy
- aws_s3_bucket_policypackage infracost
# Block PRs that increase monthly cost by more than $500
deny[msg] {
monthlyCostDelta := input.diffTotalMonthlyCost
to_number(monthlyCostDelta) > 500
msg := sprintf(
"PR increases monthly cost by $%v (limit: $500). Requires FinOps team approval.",
[monthlyCostDelta]
)
}
# Warn on any new On-Demand instance larger than r5.2xlarge
warn[msg] {
resource := input.projects[_].breakdownDiff.resources[_]
resource.resourceType == "aws_instance"
contains(resource.name, "r5.4xlarge")
resource.monthlyCost > 0
msg := sprintf(
"New large On-Demand instance %v may be a candidate for Spot or Reserved Instance.",
[resource.name]
)
}Karpenter: Intelligent Spot Automation 15.4
Karpenter replaces the Cluster Autoscaler with a faster, smarter node provisioner. It provisions the exact right instance type for your workload — using Spot first, falling back to On-Demand, and consolidating idle nodes automatically.
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: general-spot
spec:
template:
metadata:
labels:
billing-team: platform
spec:
nodeClassRef:
apiVersion: karpenter.k8s.aws/v1
kind: EC2NodeClass
name: default
requirements:
# Prefer Spot, fall back to On-Demand automatically
- key: karpenter.sh/capacity-type
operator: In
values: ["spot", "on-demand"]
# Allow multiple instance families for better Spot availability
- key: node.kubernetes.io/instance-type
operator: In
values:
- m5.xlarge
- m5.2xlarge
- m5a.xlarge
- m5a.2xlarge
- m6i.xlarge
- m6i.2xlarge
- m6a.xlarge
- key: kubernetes.io/arch
operator: In
values: ["amd64", "arm64"] # Include Graviton for ~20% savings
- key: topology.kubernetes.io/zone
operator: In
values: ["us-east-1a", "us-east-1b", "us-east-1c"]
limits:
cpu: "1000" # Max 1000 vCPUs in this NodePool
memory: 4000Gi
disruption:
consolidationPolicy: WhenEmptyOrUnderutilized
consolidateAfter: 60s
budgets:
- nodes: "10%" # Never disrupt more than 10% of nodes at once
---
apiVersion: karpenter.k8s.aws/v1
kind: EC2NodeClass
metadata:
name: default
spec:
amiFamily: AL2023
role: "KarpenterNodeRole-prod"
subnetSelectorTerms:
- tags:
karpenter.sh/discovery: prod-eks-cluster
securityGroupSelectorTerms:
- tags:
karpenter.sh/discovery: prod-eks-cluster
blockDeviceMappings:
- deviceName: /dev/xvda
ebs:
volumeSize: 100Gi
volumeType: gp3
iops: 3000
throughput: 125
tags:
Environment: prod
ManagedBy: karpenter
CostCenter: platform# NodePool for Spark/batch jobs with auto-TTL
# Nodes self-terminate after job completion
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: spark-batch
spec:
template:
metadata:
labels:
billing-team: data-engineering
workload-type: batch
spec:
nodeClassRef:
apiVersion: karpenter.k8s.aws/v1
kind: EC2NodeClass
name: compute-optimized
requirements:
- key: karpenter.sh/capacity-type
operator: In
values: ["spot"] # Batch is always Spot
- key: node.kubernetes.io/instance-type
operator: In
values: ["c5.4xlarge", "c5.8xlarge", "c5a.4xlarge", "c6i.4xlarge"]
taints:
- key: workload-type
value: batch
effect: NoSchedule
limits:
cpu: "500"
disruption:
consolidationPolicy: WhenEmpty
consolidateAfter: 30s # Aggressive consolidation for batch nodes
expireAfter: 24h # Hard TTL — nodes die after 24h max# Karpenter v1 Disruption Budget — protect critical workloads
# during Spot consolidation
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: general-spot
spec:
disruption:
budgets:
# During business hours (9-5 UTC): very conservative
- schedule: "0 9 * * mon-fri"
duration: 8h
nodes: "5%"
# Off-hours: aggressive consolidation for savings
- schedule: "0 17 * * mon-fri"
duration: 16h
nodes: "20%"
# Weekends: most aggressive
- schedule: "0 0 * * sat"
duration: 48h
nodes: "30%"
# Also add PodDisruptionBudget for critical services
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: payments-api-pdb
namespace: production
spec:
minAvailable: "80%"
selector:
matchLabels:
app: payments-apiTypical Spot Savings
- → On-Demand
m5.2xlarge: ~$276/month - → Spot
m5.2xlarge: ~$83/month (70% savings) - → 100-node cluster: $19,300/month saved
- → + Graviton arm64 additional 20%: $23,000/month saved
Spot Interruption Handling
AWS Spot Interruption Handler (helm chart) watches for 2-minute interruption notices and gracefully cordons/drains the node before reclamation. Use karpenter.sh/interruption-queue SQS integration for zero-data-loss workloads.
Build two architectures and canary Graviton
Unexecuted build and rollout. No container engine, builder, registry push or cloud resources started. Assumptions: Docker Buildx 0.17+, docker-container driver, preconfigured emulation or native amd64/arm64 builders, a multi-platform Dockerfile and approved registry. Rollout requires existing Graviton nodes and Kubernetes apps/v1 Deployments. Emulation verifies packaging, not native performance.
# Example registry: replace with approved registry and immutable release.
IMAGE=registry.example.com/team/payments:finops-canary
# Separately authorized build only: these start a builder and push an image.
docker buildx version
docker buildx create --name finops-multi --driver docker-container --use
docker buildx inspect --bootstrap
docker buildx build --builder finops-multi --platform linux/amd64,linux/arm64 --tag "$IMAGE" --push .
docker buildx imagetools inspect "$IMAGE"
# Verify both manifests and record the index digest; remove only this dedicated builder.
docker buildx rm finops-multi# Replace image digest; existing namespace, arm64 capacity and /ready endpoint required.
apiVersion: apps/v1
kind: Deployment
metadata:
name: payments-arm-canary
namespace: payments
spec:
replicas: 1
selector:
matchLabels: {app: payments-arm-canary}
template:
metadata:
labels: {app: payments-arm-canary}
spec:
nodeSelector:
kubernetes.io/arch: arm64
containers:
- name: payments
image: registry.example.com/team/payments@sha256:REPLACE_WITH_VERIFIED_INDEX_DIGEST
ports: [{containerPort: 8080}]
readinessProbe:
httpGet: {path: /ready, port: 8080}
resources:
requests: {cpu: 100m, memory: 128Mi}
limits: {memory: 256Mi}# Existing-environment checks only, not executed.
kubectl get nodes -L kubernetes.io/arch,node.kubernetes.io/instance-type
kubectl -n payments rollout status deployment/payments-arm-canary --timeout=120s
kubectl -n payments get pods -l app=payments-arm-canary -o wide
kubectl -n payments exec deployment/payments-arm-canary -- uname -m
kubectl -n payments logs deployment/payments-arm-canary --all-containers=true
kubectl -n payments get events --sort-by=.metadata.creationTimestamp
# Failed UPDATE with a known-good prior revision only:
kubectl -n payments rollout history deployment/payments-arm-canary
kubectl -n payments rollout undo deployment/payments-arm-canary
kubectl -n payments rollout status deployment/payments-arm-canary --timeout=120sVerify: inspect both linux/amd64 and linux/arm64 manifests. Correlate pod node with arm64 and a Graviton instance type; arm64 alone is not proof of Graviton. Expect aarch64 from a Linux container containing uname (expectation, not output); distroless images require runtime image-ID/platform checks instead. Investigate exec format error, native dependencies and readiness failures. Compare error rate, p95 latency, throughput and cost per request with x86 under the same load/SLO.
Recover: keep the existing x86 production Deployment and route canary traffic back if SLOs regress. First creation has no previous revision; restore a reviewed prior manifest or disable the new canary through GitOps. Rollout undo cannot move an arm64-only workload to x86 without changing its selector. Expand service by service only after native load tests.
Official references: Docker multi-platform builds, Buildx manifest inspection, Kubernetes apps/v1 rollout and AWS Graviton migration guide (rolling guide checked 2026-10-14).
Simulate a Spot interruption
Simulated diagnostic exercise, not live controller output. No instances, queue, node drain or cloud resources created. Assumptions: Karpenter 1.0.x, existing EKS cluster, configured interruption queue, EventBridge rules and SQS IAM permissions per that release. Kubernetes v1 pods and policy/v1 PDBs. Standard termination commonly gives about two minutes, but notice delivery is best effort; hibernation starts immediately. A 120s grace period cannot guarantee completion.
SIMULATED fixture — relative timestamps, no recorded events
T+000s EC2 termination notice: worker-a; nominal reclaim T+120s
T+004s EventBridge delivers to configured SQS queue
T+008s Karpenter receives message, taints/drains node and seeks replacement
T+012s Batch receives SIGTERM and starts durable idempotent checkpoint
T+060s Replacement Pending: permitted Spot offerings unavailable
T+090s Checkpoint finishes (scenario assumption, not a deadline guarantee)
T+120s EC2 reclaims worker-a; unfinished work resumes from last checkpoint# Existing batch pod template fragment, not a complete runnable workload.
spec:
terminationGracePeriodSeconds: 90
containers:
- name: batch
# Application handles SIGTERM and durably checkpoints within this budget.
image: registry.example.com/team/batch:reviewed-multiarch-releaseInterpret: predict: can a PDB prevent reclaim? Does a Pending replacement prove queue failure? Answer: neither. Check queue receipt/controller actions separately from available capacity. PDBs may delay eviction but do not extend the EC2 deadline. Never weaken a production PDB merely to finish an exercise.
Recover: checkpoint durably, budget shutdown overhead and retry idempotently. At T+60 consider an already approved, bounded On-Demand fallback with budget alerts. If capacity or budget is unavailable, pause batch submissions. Replay only from the last committed checkpoint and reject duplicate results; do not promise replacement readiness before reclaim.
# Existing-environment diagnostics only; not executed.
kubectl -n kube-system logs deployment/karpenter --since=10m
kubectl get nodes -L karpenter.sh/capacity-type
kubectl get nodeclaims
kubectl -n batch get pods -o wide
kubectl -n batch get events --sort-by=.metadata.creationTimestamp
kubectl -n batch get pdb
# In approved tooling also inspect SQS oldest-message age,
# EventBridge failed invocations, IAM permissions and durable checkpoint IDs.Verify and fallback: walk the fixture with the application owner: T+60 capacity shortage, T+90 checkpoint durability, after T+120 each result committed once. Missing notices require rule/queue/IAM checks; failed checkpoints require recovery from an earlier checkpoint. No host fault injection is needed. Real notice delivery, drain and replay remain unvalidated.
Official references: Karpenter 1.0 disruption, Karpenter 1.0 queue prerequisites, EC2 Spot notice contract (rolling API) and Kubernetes v1 pod termination.
Right-Sizing: VPA + AWS Compute Optimizer 15.5
# VPA in Recommendation-only mode (safe for production)
# Never auto-apply without testing Off mode first
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: payments-api-vpa
namespace: production
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: payments-api
updatePolicy:
updateMode: "Off" # "Off" = recommend only; "Auto" = apply + evict
resourcePolicy:
containerPolicies:
- containerName: "*"
minAllowed:
cpu: 50m
memory: 64Mi
maxAllowed:
cpu: 4
memory: 8Gi
controlledResources: ["cpu", "memory"]
---
# Query VPA recommendations
# kubectl get vpa -n production -o json | jq '.items[].status.recommendation'# List EC2 right-sizing recommendations $ aws compute-optimizer get-ec2-instance-recommendations \ --region us-east-1 \ --filters name=Finding,values=OVER_PROVISIONED \ --query 'instanceRecommendations[*].{ Instance:instanceArn, Current:currentInstanceType, Recommended:recommendationOptions[0].instanceType, Savings:recommendationOptions[0].estimatedMonthlySavings.value }' --output table +------------------+-------------+--------------+---------+ | Instance | Current | Recommended | Savings | +------------------+-------------+--------------+---------+ | i-0a1b2c3d4e | m5.4xlarge | m5.2xlarge | $142.50 | | i-0f1e2d3c4b | r5.2xlarge | r5.xlarge | $98.00 | +------------------+-------------+--------------+---------+ # Get RDS right-sizing recommendations $ aws compute-optimizer get-rds-database-recommendations \ --region us-east-1 \ --filters name=Finding,values=OVER_PROVISIONED # Export all recommendations to S3 for monthly review $ aws compute-optimizer export-ec2-instance-recommendations \ --s3-destination-config bucket=finops-reports,keyPrefix=optimizer/
package kubernetes.admission
# OPA Gatekeeper ConstraintTemplate — enforce cost labels on all pods
# Required labels: team, cost-center, environment
deny[msg] {
input.request.kind.kind == "Pod"
pod := input.request.object
required_labels := {"team", "cost-center", "environment"}
provided := {label | pod.metadata.labels[label]}
missing := required_labels - provided
count(missing) > 0
msg := sprintf(
"Pod missing required cost labels: %v. All pods must have team, cost-center, environment.",
[missing]
)
}
# Block pods without resource limits (will cause OOM and waste)
deny[msg] {
input.request.kind.kind == "Pod"
container := input.request.object.spec.containers[_]
not container.resources.limits
msg := sprintf(
"Container '%v' missing resource limits. Set cpu and memory limits to prevent cost overruns.",
[container.name]
)
}RI/SP Strategy: Commitment Purchasing 15.6
When to Buy Reserved Instances
- Baseline compute stable for >6 months → 1yr Standard RI (40% savings)
- DB instances (RDS/ElastiCache) → Reserved DB Instance
- Multi-AZ NAT Gateways → Savings Plans cover egress
- Use Convertible RIs when instance family may change
- Never commit 100% — keep 20-30% On-Demand for spikes
Compute Savings Plans (Preferred)
- Applies to EC2 and Fargate and Lambda
- Flexible across region, instance family, OS
- Up to 66% discount vs On-Demand
- 1-year No-Upfront: best for cash-constrained teams
- 3-year All-Upfront: maximum savings if budget allows
# Analyze your Savings Plan coverage and utilization $ aws ce get-savings-plans-coverage \ --time-period Start=2024-01-01,End=2024-02-01 \ --granularity MONTHLY \ --filter '{"Dimensions":{"Key":"SERVICE","Values":["Amazon EC2"]}}' \ --query 'SavingsPlansCoverages[*].Coverage' # Purchase recommendation: how much to commit $ aws ce get-savings-plans-purchase-recommendation \ --savings-plans-type COMPUTE_SP \ --term-in-years ONE_YEAR \ --payment-option NO_UPFRONT \ --lookback-period-in-days SIXTY_DAYS { "RecommendedSpend": "47.23", ← commit $47.23/hr = ~$34K/month "EstimatedSavings": "$12,450", ← monthly savings vs On-Demand "CurrentCoverage": "34.2%" ← only 34% currently covered }
Configure Cost Anomaly Detection
Unexecuted configuration and verification steps. No AWS account accessed or cloud resources created. Assumptions: AWS CLI v2.37 command shapes, commercial AWS partition, management-account Billing/Cost Management permissions, enabled Cost Explorer and existing usage history. Review existing monitors to avoid duplicates. Detection has no additional service charge; SNS and other services may charge. Establish an owner and approved budget first. An anomaly threshold is a notification threshold, not a spending cap. Cost Explorer data may lag up to 24 hours; newly used services need 10 days of history. Never create spend to train the detector.
This SERVICE monitor analyzes services separately. DAILY email avoids creating an SNS topic. Replace the example address with an approved recipient and copy the actual returned monitor ARN into the subscription file.
{
"MonitorName": "finops-services",
"MonitorType": "DIMENSIONAL",
"MonitorDimension": "SERVICE"
}{
"MonitorArnList": [
"arn:aws:ce::123456789012:anomalymonitor/REPLACE_WITH_RETURNED_ID"
],
"Subscribers": [
{
"Address": "finops@example.com",
"Type": "EMAIL"
}
],
"Frequency": "DAILY",
"SubscriptionName": "finops-daily-100usd",
"ThresholdExpression": {
"Dimensions": {
"Key": "ANOMALY_TOTAL_IMPACT_ABSOLUTE",
"MatchOptions": [
"GREATER_THAN_OR_EQUAL"
],
"Values": [
"100"
]
}
}
}# Separately authorized environment only; no AWS calls executed here.
aws ce get-anomaly-monitors --region us-east-1
aws ce create-anomaly-monitor --region us-east-1 --anomaly-monitor file://anomaly-monitor.json
# Replace monitor ARN and recipient before submission.
aws ce create-anomaly-subscription --region us-east-1 --anomaly-subscription file://anomaly-subscription.json
aws ce get-anomaly-subscriptions --region us-east-1
# Select a real recent interval containing billing history.
aws ce get-anomalies --region us-east-1 --date-interval StartDate=2026-10-01,EndDate=2026-10-14Verify: confirm dimension, subscription ARN, threshold and recipient confirmation status. Empty anomalies do not prove delivery or absence of waste. Reconcile any anomaly's service/account/region/usage type and impact against billing data and intended changes. IMMEDIATE notifications instead require an approved SNS topic, a topic policy granting costalerts.amazonaws.com publish access, confirmed destination subscription and SNS ARN with Type: SNS. Review delivery charges and KMS permissions for encryption.
Recover: check history, delay, recipient confirmation, threshold and topic permissions before changing configuration; do not induce spend. Remove only owned duplicate subscriptions after preserving their configuration. Contain real anomalies with the workload owner through approved changes; detection never stops resources.
Official references: AWS detection prerequisites, CLI v2.37 monitor, CLI v2.37 subscription, SNS policy setup and service pricing (rolling docs checked 2026-10-14).
CUR and Athena setup with scan controls
Unexecuted configuration and query examples. No bucket, role, report, crawler or Athena query created. Assumptions: legacy CUR API 2017-01-06 (not CUR 2.0), CLI v2.37, Athena engine 3, management-account billing permissions and an existing approved private us-east-1 bucket. New accounts should evaluate CUR 2.0 independently; do not mix schemas.
- Obtain Billing/CUR and owned-bucket policy permissions. In Billing → Cost & Usage Reports choose hourly granularity, resource IDs, existing bucket/prefix, Parquet, overwrite mode and Athena integration. Use the AWS-provided bucket-policy wizard and keep Block Public Access enabled.
- The reviewed policy must grant
billingreports.amazonaws.combucket-policy/ACL inspection and report object writes, scoped with your actualaws:SourceAccountand CURaws:SourceArn. Merge with existing statements rather than replacing unrelated access. The JSON below assumes this policy already exists. - For EKS namespace attribution enable split cost allocation in billing preferences and report schema. Choose documented resource-request or utilization prerequisites. Wait for fresh data; tags do not automatically backfill old namespace allocations.
- After delivery, review the delivered Athena CloudFormation template before separately authorized deployment. It provisions Glue database/table/crawler and permissions. Configure an engine-3 workgroup with private encrypted S3 query results and a per-query bytes-scanned cutoff. Run the owned crawler and inspect schema/partitions first. First report delivery can take up to 24 hours; check status rather than assuming an empty table means zero spend.
Bucket policy template below follows AWS's legacy CUR policy. Replace the example 12-digit account ID and bucket with the report owner's real values; do not apply this template here. Merge reviewed statements into the existing owned-bucket policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "billingreports.amazonaws.com"
},
"Action": [
"s3:GetBucketAcl",
"s3:GetBucketPolicy"
],
"Resource": "arn:aws:s3:::REPLACE_WITH_APPROVED_BUCKET",
"Condition": {
"StringEquals": {
"aws:SourceArn": "arn:aws:cur:us-east-1:123456789012:definition/*",
"aws:SourceAccount": "123456789012"
}
}
},
{
"Effect": "Allow",
"Principal": {
"Service": "billingreports.amazonaws.com"
},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::REPLACE_WITH_APPROVED_BUCKET/*",
"Condition": {
"StringEquals": {
"aws:SourceArn": "arn:aws:cur:us-east-1:123456789012:definition/*",
"aws:SourceAccount": "123456789012"
}
}
}
]
}{
"ReportName": "finops-hourly",
"TimeUnit": "HOURLY",
"Format": "Parquet",
"Compression": "Parquet",
"AdditionalSchemaElements": [
"RESOURCES",
"SPLIT_COST_ALLOCATION_DATA"
],
"S3Bucket": "REPLACE_WITH_EXISTING_APPROVED_BUCKET",
"S3Prefix": "cur",
"S3Region": "us-east-1",
"AdditionalArtifacts": [
"ATHENA"
],
"RefreshClosedReports": true,
"ReportVersioning": "OVERWRITE_REPORT"
}# Existing approved account/bucket required; not executed.
aws cur describe-report-definitions --region us-east-1
# Review name, bucket policy and budget before this resource-creation call.
aws cur put-report-definition --region us-east-1 --report-definition file://cur-report-definition.json
aws cur describe-report-definitions --region us-east-1
# Inspect delivered manifest and Glue crawler in the approved console.Charge prerequisites: report generation has no fee, but S3 storage/requests, Glue crawler/catalog and Athena scans may charge. On-demand Athena SQL commonly costs $5/TB scanned with regional variation and minimum billing; confirm the region's price before authorization. Use compressed Parquet, narrow columns/month partitions, a workgroup scan cutoff and a budget notification. A budget is not a hard spending cap. The API compression enum is Parquet, not Snappy.
Prefer the delivered template/crawler for the full schema. This optional narrow external table illustrates manual DDL, assuming an existing Glue database and exact legacy Parquet field names/types verified from the delivered files. Replace both S3 locations with the actual report root and October Parquet partition directory from the manifest; exclude metadata files. Do not create a second chargeback source by summing this table with the crawler's table. DDL is unexecuted and is not a substitute for schema inspection.
-- Athena engine 3; existing finops database, legacy Parquet schema required.
CREATE EXTERNAL TABLE finops.namespace_split_review (
resource_tags_aws_eks_namespace string,
split_line_item_split_cost double,
split_line_item_unused_cost double
)
PARTITIONED BY (year string, month string)
STORED AS PARQUET
LOCATION 's3://REPLACE_WITH_APPROVED_BUCKET/REPLACE_WITH_REPORT_ROOT/';
-- Use the actual delivered month directory, not an assumed directory layout.
ALTER TABLE finops.namespace_split_review
ADD IF NOT EXISTS PARTITION (year='2026', month='10')
LOCATION 's3://REPLACE_WITH_APPROVED_BUCKET/REPLACE_WITH_OCTOBER_PARQUET_DIRECTORY/';
SHOW PARTITIONS finops.namespace_split_review;Manual DDL reference: Athena engine-3 external table syntax and partition requirements.
-- Example Glue names; replace with the delivered database/table.
SHOW CREATE TABLE finops.finops_hourly;
SHOW COLUMNS IN finops.finops_hourly;
SHOW PARTITIONS finops.finops_hourly;
-- Confirm year/month and resource_tags_aws_eks_namespace,
-- split_line_item_split_cost and split_line_item_unused_cost first.-- Athena engine 3, delivered legacy CUR split-cost schema required.
-- Compute attribution, NOT a complete amortized invoice.
SELECT resource_tags_aws_eks_namespace AS namespace,
SUM(COALESCE(split_line_item_split_cost, 0)
+ COALESCE(split_line_item_unused_cost, 0)) AS allocated_compute_usd
FROM finops.finops_hourly
WHERE year = '2026' AND month = '10'
AND resource_tags_aws_eks_namespace IS NOT NULL
GROUP BY 1
ORDER BY 2 DESC;Reconcile: use a completed period and compare namespace allocation to corresponding node compute, not the entire bill. Never add split child allocations to parent EC2 billing rows. Use net split columns where discounts require them and document idle/shared-cost allocation. Storage, network, control-plane and unattributed costs need separate policies. For account amortization use Savings Plan effective cost on covered usage and RI effective cost on discounted usage plus unused commitments; exclude negation/duplicate parent rows. Do not label a split-cost or unblended sum as a full amortized invoice.
Verify and recover: inspect report definition, manifest, bucket policy, crawler status, partitions and scan bytes. Missing namespace columns need split-cost enablement/fresh delivery; never invent tags. Check S3 prefix before rerunning a stale crawler. Stop oversized queries, fix partition predicates/cutoffs and inspect the plan before rerunning. To retire an authorized setup, delete only the owned report definition, then review retention/dependencies before removing its template resources; retain finance records.
Official references: legacy CUR creation, bucket policy, CUR report API, delivered Athena integration, split-cost enablement, split-cost columns, Athena engine 3 and regional charges (rolling docs checked 2026-10-14).
Hands-On Enterprise Labs 15.7
FinOps Mastery Labs
- Deploy Kubecost on kind cluster, generate cost report for 3 sample namespaces
- Write Infracost policy that blocks any PR adding an instance > $300/month
- Configure Karpenter NodePool with Spot + arm64 Graviton support, verify consolidation
- Apply VPA in recommendation mode to a busy deployment, read its suggestions
- Create AWS Budget with SNS → Slack alert for 80% threshold breach
- Write OPA Gatekeeper constraint requiring cost-center label on all Pods
- Run AWS Cost Anomaly Detection, analyze and explain the anomaly report
- Calculate break-even point for 1-year Compute Savings Plan vs On-Demand for a given workload
Troubleshooting & Gotchas 15.8
Kubecost costs don't match AWS bill
Kubecost uses list price by default. Enable AWS Cost and Usage Reports (CUR) integration in Kubecost settings to pull actual billing data including discounts, EDP, and reserved instance rates. CUR integration requires an S3 bucket with Athena queries.
Karpenter not consolidating idle nodes
Check for daemon sets (can't evict), PodDisruptionBudgets with minAvailable=1 blocking eviction, or karpenter.sh/do-not-disrupt: "true" annotations on pods. Increase consolidateAfter window. Check disruption budget percentages.
Spot interruptions causing production issues
Set karpenter.sh/capacity-type: spot only on non-critical workloads. Use node selectors and taints to separate Spot-tolerant workloads. Deploy AWS Node Termination Handler (helm chart). Ensure PodDisruptionBudgets exist for all critical Deployments. Set terminationGracePeriodSeconds: 120 to handle 2-min Spot warning.
Infracost diff showing wrong baseline
The baseline must be generated from the target branch state, not the current PR. Always checkout the base ref first, run terraform init, then generate baseline JSON. Ensure both runs use the same --terraform-var-file flags.