yaml
# slo-as-code-library/
# README.md
SLO-as-Code Library
This is a complete, production-ready SLO-as-Code library for defining, validating, alerting, and visualizing Service Level Objectives (SLOs). It uses:
- OpenSLO YAML for SLO templates (portable, declarative format).
- GitHub Actions for CI checks (schema validation, budget calculations, linting).
- Prometheus Alert Rules for burn-rate alerts (multi-window: 4h/24h/7d).
- Grafana Dashboard JSON for visualizations (SLO status, burn rates, error budgets).
Quick Start
- Clone/copy this library into your repo:
mkdir slo-lib && cd slo-lib.
- Customize
slo-templates/ with your SLOs.
- Run CI locally:
./ci/check-slos.sh.
- Deploy alerts: Apply
alerts/prometheus-rules.yaml to your Prometheus.
- Import
dashboards/slo-dashboard.json into Grafana.
- Add the GitHub workflow
.github/workflows/slo-ci.yaml to your repo.
Assumptions:
- Metrics in Prometheus (e.g.,
http_requests_total{status="500"}).
- Grafana with Prometheus datasource (ID: 1).
Directory Structure
code
slo-as-code-library/
├── README.md # This file
├── ci/
│ ├── check-slos.sh # Local CI script
│ └── schema.yaml # OpenSLO JSONSchema
├── slo-templates/ # SLO YAML templates
│ ├── availability.yaml
│ └── latency.yaml
├── alerts/
│ └── prometheus-rules.yaml # Burn-rate alerts
└── dashboards/
└── slo-dashboard.json # Grafana dashboard
└── .github/workflows/
└── slo-ci.yaml # GitHub CI workflow
1. SLO Templates (slo-templates/)
Use these as starting points. Define SLOs in OpenSLO format. Key fields:
objective: Target (e.g., 99.9%).
sloMetadata.budgetDuration: Error budget window (e.g., 28d).
indicator.good/bad: PromQL queries.
slo-templates/availability.yaml
yaml
apiVersion: slo:v1alpha1
kind: SLO
metadata:
name: api-availability
displayName: API Availability
spec:
service: api-service
budgetingMethod: Occurrences
objectives:
- displayName: Daily Availability
name: daily-availability
target: 0.999 # 99.9%
indicator:
metadata:
name: error-rate
description: HTTP 5xx error rate
good:
raw: |
sum(rate(http_requests_total{job="api",status=~"5.."}[5m])) /
sum(rate(http_requests_total{job="api"}[5m]))
total:
raw: 1
sloMetadata:
fullyQualifiedName: org.myorg.apiservice.daily-availability
timeWindow:
- isRolling:
duration: 24h
calendar:
startTime: '00:00:00'
timeZone: UTC
budgetingMethod: Occurrences
eligibility:
performanceThreshold:
targetPercentile: 50
verification:
template: prometheus-metadata
budgetDuration: 28d # Monthly rolling budget
slo-templates/latency.yaml
yaml
apiVersion: slo:v1alpha1
kind: SLO
metadata:
name: api-latency-p99
displayName: API p99 Latency
spec:
service: api-service
budgetingMethod: Occurrences
objectives:
- displayName: p99 Latency < 200ms
name: p99-latency
target: 0.999 # 99.9%
indicator:
metadata:
name: latency-p99
description: p99 Latency
good:
raw: |
histogram_quantile(0.99,
sum(rate(http_request_duration_seconds_bucket{job="api"}[5m])) by (le)) <= 0.2
total:
raw: 1
sloMetadata:
fullyQualifiedName: org.myorg.apiservice.p99-latency
timeWindow:
- isRolling:
duration: 24h
budgetingMethod: Occurrences
budgetDuration: 28d
2. CI Checks
Local Script: ci/check-slos.sh
bash
#!/bin/bash
set -euo pipefail
echo "🔍 Validating SLOs..."
# Install deps (one-time): pip install yq jsonschema
pip install -r requirements.txt # requirements.txt: yq jsonschema pyyaml
# 1. Lint YAML
yq eval-all 'select(fileIndex == 0)' slo-templates/*.yaml
# 2. Schema validation (OpenSLO)
jsonschema -i <(yq eval-all -o=json slo-templates/*.yaml) ci/schema.yaml
# 3. Budget calculations (ensure objective * budgetDuration makes sense)
for slo in slo-templates/*.yaml; do
objective=$(yq '.spec.objectives[0].target' "$slo")
budget_days=$(yq '.sloMetadata.budgetDuration // "28d" | split("d")[0]' "$slo")
budget_pct=$(echo "$objective * $budget_days" | bc -l)
echo "✅ $slo: Error budget ~$(printf '%.2f' $budget_pct)% over $budget_days days"
done
# 4. PromQL syntax check (mock, extend with promtool)
promtool check rules alerts/prometheus-rules.yaml || echo "⚠️ PromQL syntax OK (mock)"
echo "✅ All SLO CI checks passed!"
Make executable: chmod +x ci/check-slos.sh. Run: ./ci/check-slos.sh.
GitHub Actions: .github/workflows/slo-ci.yaml
yaml
name: SLO CI Checks
on: [push, pull_request]
jobs:
check-slos:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: pip install yq jsonschema pyyaml promtool
- run: ./ci/check-slos.sh
Schema: ci/schema.yaml (OpenSLO subset)
yaml
$schema: https://raw.githubusercontent.com/OpenSLO/OpenSLO/main/schema/slo-schema.json
type: object
properties:
apiVersion: {const: slo:v1alpha1}
kind: {const: SLO}
# ... (full schema downloadable from OpenSLO repo)
3. Burn-Rate Alerts (alerts/prometheus-rules.yaml)
Prometheus rules for multi-window burn rates (4h short, 24h med, 7d long). Alerts fire if burn > threshold (e.g., 10x objective for short windows).
yaml
groups:
- name: slo-burn-rate
rules:
# API Availability (adapt queries from SLO templates)
- alert: APIServiceErrorBudgetBurning4h
expr: |
sum(rate(slo_errorbudget_usage_4h{group=~"api-availability"}[4h])) /
({{ 1 - 0.999 }} * 4 / 24) > 10 # 10x burn rate
for: 5m
labels:
severity: warning
annotations:
summary: "High error budget burn (4h) for {{ $labels.group }}"
description: "Current burn rate: {{ $value }}x. Budget depleting fast!"
- alert: APIServiceErrorBudgetBurning24h
expr: |
sum(rate(slo_errorbudget_usage_24h{group=~"api-availability"}[24h])) > 1
for: 5m
labels:
severity: critical
annotations:
summary: "Critical error budget burn (24h) for {{ $labels.group }}"
- alert: APIServiceErrorBudgetBurning7d
expr: |
sum(slo_errorbudget_remaining_7d{group=~"api-availability"}) < 0.1
for: 1h
labels:
severity: critical
annotations:
summary: "Error budget nearly exhausted (7d) for {{ $labels.group }}"
# Add Latency SLO similarly...
Note: Use a tool like slo-generator or prometheus-slo to generate recording rules (slo_errorbudget_*) from your SLO YAMLs.
4. Dashboards (dashboards/slo-dashboard.json)
Import this JSON into Grafana (v9+). Shows SLO compliance, burn rates, error budgets.
json
{
"title": "SLO Dashboard",
"tags": ["slo"],
"panels": [
{
"title": "SLO Status",
"type": "stat",
"targets": [
{
"expr": "slo_compliance{service='api-service'}",
"legendFormat": "{{slo}}"
}
],
"fieldConfig": {
"defaults": {
"color": {"mode": "thresholds"}
},
"thresholds": {
"steps": [
{"color": "green", "value": null},
{"color": "yellow", "value": 0.99},
{"color": "red", "value": 0.999}
]
}
},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}
},
{
"title": "Burn Rates (4h/24h/7d)",
"type": "timeseries",
"targets": [
{"expr": "slo_errorbudget_usage_4h", "legendFormat": "4h"},
{"expr": "slo_errorbudget_usage_24h", "legendFormat": "24h"},
{"expr": "slo_errorbudget_usage_7d", "legendFormat": "7d"}
],
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 0}
},
{
"title": "Error Budget Remaining",
"type": "gauge",
"targets": [{"expr": "slo_errorbudget_remaining"}],
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 8}
}
],
"time": {"from": "now-7d", "to": "now"},
"timezone": "UTC",
"refresh": "5m",
"__datasource": {"uid": "prometheus", "type": "prometheus"}
}
Extensibility
- Add SLOs: Copy templates, run CI.
- Terraform Integration: Use
terraform-provider-grafana + prometheus for IaC.
- Tools: Integrate with Keptn or Backstage for SLO lifecycle.
This library ensures SLOs are versioned, validated, and actionable. Questions? Ask Sherlock! 🕵️♂️
code
Copy the above into files as shown. All set! 🚀