A Go SDK for building DevOps automation applications using ConfigHub as the configuration backend. This SDK provides reusable modules for cost analysis, waste detection, resource optimization, and deployment strategies. It extends the official SDK for ConfigHub which is here.
CLI Linting (Most Popular):
- Quick Start: CLI Command Linter
- CLI Command Validation (Full Docs)
- Testing & Verification
- Enforcement Mechanisms
SDK Modules:
Get quick feedback on ConfigHub CLI commands in your project:
cub CLI.
# One-line validation
curl -fsSL https://raw.githubusercontent.com/monadic/devops-sdk/main/cub-command-analyzer.sh | bash -s -- .
# Or clone and run locally
git clone https://github.com/monadic/devops-sdk.git
cd devops-sdk
./cub-command-analyzer.sh /path/to/your/projectWhat it validates:
- ✅ Command syntax (entity + verb structure)
- ✅ Required flags and combinations
- ✅ WHERE clause grammar (EBNF compliance)
- ✅ Common error patterns from ConfigHub maintainer feedback
- ✅ Semantic correctness with pre/post conditions
Test coverage:
- 39/39 unit tests passing (for known patterns)
- Integration tests against real
cubCLI (as of 2025-10-12) - Validated against 154 commands across production projects
- Based on official feedback from Brian Grant (ConfigHub maintainer)
- Note: Tests validate known commands; may not cover newest CLI features
Quick links:
- 📖 Standalone Quick Start Guide
- 📚 Full CLI Validation Documentation
- 🔍 Testing & Verification
⚠️ Known Limitations
app.go- Base DevOps app framework with health checks and informersconfighub.go- ConfigHub client with Sets, Filters, and BulkOps supportclaude.go- Claude AI integration for intelligent analysiskubernetes.go- Kubernetes utilities and informer setupcost.go- Cost analysis module for resource pricingwaste.go- Waste detection module for over-provisioningoptimizer.go- Optimization engine for resource rightsizingdeployment.go- Core deployment strategiesdeployment_dev.go- Development mode deployment (direct to K8s)deployment_enterprise.go- Enterprise mode deployment (via Git)health.go- Health check endpoints for monitoringhealth_check.go- Comprehensive health checking systemtables.go- ASCII table rendering for terminal outputretry.go- Retry logic with exponential backoffpackage.go- Package management for ConfigHub resources
The DevOps SDK enables building persistent, event-driven DevOps applications. Key characteristics:
- Persistent Apps: Run continuously with Kubernetes informers, not just when triggered
- Event-Driven: React immediately to changes, not on schedules
- Stateful: ConfigHub tracks all config state and history
- AI-Powered: Integrated Claude AI for intelligent decisions
- Bulk Operations: Sets and Filters for cross-environment operations
The SDK includes a minimal Technology Compatibility Kit for verifying ConfigHub + Kubernetes integration:
./test-confighub-k8sWhat it tests:
- ✅ ConfigHub API connectivity
- ✅ Kubernetes cluster access (creates Kind cluster)
- ✅ Worker installation and connection
- ✅ Unit apply workflow (ConfigHub → K8s)
- ✅ Live state verification (K8s → ConfigHub)
Quick verification:
# Run directly
curl -fsSL https://raw.githubusercontent.com/monadic/devops-sdk/main/test-confighub-k8s | bashThis TCK is used by TraderX and MicroTraderX as a pre-flight check before deployments. See TCK.md for full documentation.
The SDK includes comprehensive validation tools for ConfigHub cub CLI usage:
Static analysis tool that validates every cub command in your scripts:
# Analyze entire project
./cub-command-analyzer.sh /path/to/your/project/
# Analyze specific directory
./cub-command-analyzer.sh bin/
# Remote analysis
curl -fsSL https://raw.githubusercontent.com/monadic/devops-sdk/main/cub-command-analyzer.sh | bash -s -- .What it validates:
- ✅ Command syntax (entity + verb structure)
- ✅ Required flags and combinations
- ✅ WHERE clause grammar (EBNF compliance)
- ✅ Common error patterns from Brian Grant's feedback
- ✅ Semantic correctness with pre/post conditions
Example output:
==========================================
FILE: bin/deploy
LINE 42: cub unit update backend --patch '{"spec":{"replicas":3}}'
==========================================
SYNTAX VALIDATION:
[FAIL] Invalid syntax
Error: --patch requires one of: --from-stdin, --filename, --restore, --upgrade,
--merge-source, --label, --delete-gate, --destroy-gate, or --changeset
GRAMMAR VALIDATION:
[N/A] No WHERE clause present
COMMON ERRORS:
[WARN] Common errors found:
- --patch requires additional flags
- Inline JSON with --patch is invalid. For DATA: use stdin (-).
For METADATA: use --from-stdin. For fine-grained: use 'cub function do'
- Missing required --space flag
[INFO] Suggested corrections:
For unit DATA update (spec.replicas, etc.):
echo '{...}' | cub unit update --space <space> <unit> -
For unit METADATA update (labels, annotations):
echo '{...}' | cub unit update --patch --space <space> <unit> --from-stdin
For fine-grained updates:
cub function do --space <space> --where "Slug = '<unit>'" set-replicas 3
SEMANTIC EXPLANATION:
Updates unit 'backend' with patch operation
Pre-condition: Unit 'backend' exists
Post-condition: Unit updated based on patch operation
Core validation library used by the analyzer:
Location: test/lib/cub-test-framework.sh
Functions:
validate_cub_syntax()- Command structure validationvalidate_where_clause()- WHERE clause EBNF compliancedetect_common_errors()- Pattern matching for 7 common mistakesgenerate_semantic_explanation()- English description with pre/post conditions
Supported entities: space, unit, filter, function, worker, auth, run, link, changeset, set, revision, target, context, dataset
Comprehensive tests proving validator correctness:
Unit tests (test/unit/test-cub-validator.sh):
- 39 tests covering all validation functions
- Known valid commands from global-app
- Known invalid commands from Brian's feedback
- WHERE clause grammar (EBNF)
- Common error patterns
- Edge cases
Integration tests (test/integration/test-cub-validator-integration.sh):
- Compares validator with actual
cubCLI behavior - Validates against real ConfigHub API
- Cross-references with
cub --helpoutput
Run tests:
# Unit tests (no dependencies)
./test/unit/test-cub-validator.sh
# Integration tests (requires cub CLI)
cub auth login
./test/integration/test-cub-validator-integration.shResults:
Tests run: 39
Tests passed: 39
Tests failed: 0
Success rate: 100%
Example metadata templates for ConfigHub testing:
Location: test-data/
Files:
metadata.json- Unit metadata template (labels/annotations)space-metadata.json- Space metadata templateREADME.md- Usage documentation and best practices
Usage:
# Copy templates to your project
cp test-data/*.json your-project/test-data/
# Use in tests
cat test-data/metadata.json | cub unit create --from-stdin myunit --space myspaceHow is this linter tested?
The linter is tested through multiple methods (though cannot guarantee perfect accuracy):
The validator's results are compared against actual cub CLI behavior:
# Run integration tests (requires cub auth)
./test/integration/test-cub-validator-integration.shWhat these tests prove:
- If validator says VALID → cub CLI succeeds ✅
- If validator says INVALID → cub CLI fails ✅
- Validator matches actual ConfigHub API behavior
All validation rules derive from Brian Grant's feedback (ConfigHub maintainer):
Key insights from Brian:
- Inline JSON error: "You're passing that data patch (which isn't a thing you can pass to update) as the unit slug"
- WHERE clause limitations: Data fields are opaque, OR operator not supported
- Required flags:
--patchrequires companion flags (--from-stdin, --filename, --upgrade, etc.)
See test/strategies/cub-tests.md for complete feedback documentation.
Real-world validation across production codebases:
| Project | Total Commands | Valid | Invalid | Status |
|---|---|---|---|---|
| TraderX | 88 | 88 | 0 | ✅ 100% |
| MicroTraderX | 66 | 66 | 0 | ✅ 100% |
| DevOps Examples | Multiple apps | All valid | 0 | ✅ 100% |
Total validated: 154+ commands across 3 production projects
39 unit tests covering:
- ✅ Valid commands from global-app (canonical patterns)
- ✅ Invalid commands from Brian's feedback
- ✅ WHERE clause EBNF grammar
- ✅ All common error patterns
- ✅ Edge cases and boundary conditions
Test results: 39/39 passing (100% success rate)
Validation rules cross-checked against:
- ConfigHub source code (
/confighub/public/cmd/cub/*.go) - Official ConfigHub CLI help text (
cub --help,cub <entity> --help) - WHERE clause grammar specification (EBNF)
Confidence level: Moderate - Provides helpful linting for common patterns
Important limitations:
- Validator is a static analyzer with hardcoded rules
- May lag behind CLI updates (last synced: 2025-10-12, cub commit a9e49ba)
- Cannot validate all command combinations
- Always test with actual
cubCLI before deploying
This tool provides quick feedback for obvious errors, but is not a substitute for testing with the actual CLI.
See LIMITATIONS.md for complete list of what this linter cannot do.
All projects using this SDK must:
- ✅ Run
cub-command-analyzerbefore commits - ✅ Fix all invalid commands (exit code 0 required)
- ✅ Document validation status in README/TESTING.md
- ✅ Include CLI validation in CI/CD pipelines
Current validation status (as of 2025-10-12):
- TraderX: 88/88 commands valid ✅
- MicroTraderX: 66/66 commands valid ✅
- DevOps Examples: 100% validated ✅
Note: Command counts are point-in-time metrics. Run the analyzer on your project to get current results.
See test/README.md for complete testing documentation.
To ensure CLI validation in your workflow:
Install the pre-commit hook to validate commands before committing:
# Install hook
cp hooks/pre-commit .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
# Test hook
git add some-script.sh
git commit -m "test" # Hook runs automatically
# Bypass hook (not recommended)
git commit --no-verifyThe hook validates all staged shell scripts and prevents commits with invalid commands.
Add GitHub Actions workflow to your repository:
File: .github/workflows/validate-cli.yml
name: Validate ConfigHub CLI Commands
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
validate-cli:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Download validator
run: |
curl -fsSL https://raw.githubusercontent.com/monadic/devops-sdk/main/cub-command-analyzer.sh \
-o cub-command-analyzer.sh
chmod +x cub-command-analyzer.sh
- name: Validate commands
run: ./cub-command-analyzer.sh .See examples/github-actions/validate-cli.yml for full example.
Use the enforcement script for manual validation:
# Validate current directory
./bin/validate-cli
# Validate specific project
./bin/validate-cli /path/to/project
# CI mode (stricter checks, no colors)
./bin/validate-cli --ci
# Show help
./bin/validate-cli --helpExit codes:
0- All commands valid1- Invalid commands found2- Validation errors (missing tools, etc.)
All content below this line 100% created by Claude.
Analyzes resource costs across ConfigHub spaces and Kubernetes deployments.
Features:
- Multi-cloud pricing models (AWS, GCP, Azure)
- Kubernetes resource cost estimation
- ConfigHub unit cost analysis
- Hierarchical space analysis
- Cost breakdown by resource type
- Support for all Kubernetes resource units (Ki, Mi, Gi, Ti, Pi)
Key Functions:
NewCostAnalyzer()- Create cost analyzer with ConfigHub integrationAnalyzeSpace()- Analyze costs for a single spaceAnalyzeHierarchy()- Analyze full environment hierarchyGenerateReport()- Create detailed cost reportStoreAnalysisInConfigHub()- Save analysis resultsGetOptimizationRecommendations()- Get cost-saving suggestionsParseQuantity()- Parse Kubernetes resource quantities
Identifies resource waste by comparing allocated vs actual usage.
Features:
- CPU waste detection with safety checks
- Memory waste analysis
- Storage waste identification
- Idle replica detection
- Waste categorization and prioritization
- Negative waste ratio protection
Key Functions:
NewWasteAnalyzer()- Create waste analyzer with thresholdsSetThresholds()- Configure waste detection sensitivityAnalyzeWaste()- Perform comprehensive waste analysisGenerateWasteReport()- Create detailed waste reportIdentifyWaste()- High-level waste identification helper
Generates optimized configurations based on waste analysis.
Features:
- Multi-container resource optimization
- Proportional resource distribution
- Safety margin calculations (20% buffer)
- Risk assessment (LOW/MEDIUM/HIGH)
- Requests/limits ratios (CPU 150%, Memory 120%)
- Deep manifest copying with type safety
Key Functions:
NewOptimizer()- Create optimization engineGenerateOptimizedConfiguration()- Generate optimized manifestsApplyOptimizations()- Apply optimizations to ConfigHubValidateOptimizedConfiguration()- Validate optimized configsGenerateOptimizationReport()- Create optimization reportStoreOptimizationInConfigHub()- Save optimizations
Direct ConfigHub → Kubernetes deployment for fast development cycles.
Features:
- Direct manifest application
- No Git intermediary
- Watch and sync capabilities
- Instant rollback
- Validation tools
Key Functions:
NewDevModeDeployer()- Create dev mode deployerDeployUnit()- Deploy single unit to KubernetesDeploySpace()- Deploy entire spaceDeployWithFilter()- Deploy filtered unitsWatchAndSync()- Continuous sync from ConfigHubRollback()- Rollback to previous revisionValidateDeployment()- Validate deployment status
Core deployment strategies and environment management.
Features:
- Environment hierarchy creation (base → qa → staging → prod)
- Automatic space setup with unique prefixes
- Filter creation for bulk operations
- Base configuration loading
- Environment promotion patterns
Key Functions:
NewDeploymentHelper()- Create deployment helperSetupBaseSpace()- Initialize base space with unique prefixCreateStandardFilters()- Create app/infra/all filtersLoadBaseConfigurations()- Load configs from filesCreateEnvironmentHierarchy()- Build full env hierarchyCreateVariant()- Create config variantApplyToEnvironment()- Deploy to specific environmentPromoteEnvironment()- Promote between environmentsQuickDeploy()- One-command deployment
ConfigHub → Git → Flux/Argo → Kubernetes for production compliance.
Features:
- Git repository integration
- Flux and Argo CD support
- Full audit trail
- GitOps configuration generation
- Automated sync triggering
Key Functions:
NewEnterpriseModeDeployer()- Create enterprise deployerDeployUnit()- Export unit to Git and trigger syncDeploySpace()- Export space to Git repositoryCreateGitOpsConfig()- Generate Flux/Argo configsValidateGitOpsDeployment()- Validate GitOps deployment
- Simple API for sending prompts to Claude
- JSON analysis with structured responses
- Automatic response parsing and error handling
- Comprehensive timestamped logging with request/response tracking
- Full CRUD operations for units and spaces
- Type-safe API interactions with real ConfigHub APIs
- Token-based authentication
- High-level convenience helpers for common patterns
- Real space name resolution (no more mock UUIDs)
- Multi-client initialization (standard, dynamic, metrics)
- Config detection (kubeconfig, in-cluster)
- Resource helper for nested field operations
- Namespace detection
- Base structure for continuous DevOps applications
- Built-in health checks and metrics
- Signal handling and graceful shutdown
- Environment variable helpers
- Retry logic with exponential backoff
- Event-driven mode with
RunWithInformers()for Kubernetes events
- Health and readiness endpoints
- Metrics endpoint
- Status tracking
- Complete system health validation
- Kubernetes cluster health monitoring
- ConfigHub connection verification
- Resource availability checks
- Compliance validation for ConfigHub-only commands
- Detailed error reporting and diagnostics
- Wrap ConfigHub's native Helm support
- Install and upgrade Helm charts as ConfigHub units
- List and manage Helm releases
- Detect drift in Helm chart versions
- Validate Helm values with ConfigHub functions
- Generate upgrade commands for corrections
- Export ConfigHub resources to distributable packages
- Load packages from local directories or remote URLs
- Clone entire environments with one command
- Backup and restore spaces with timestamps
- Publish packages to Git repositories
- Support for versioned packages
- Unicode box-drawing tables for terminal output
- Standardized table formats for ConfigHub resources
- Color support with ANSI escape codes
- Automatic column width calculation
Available tables:
RenderSpacesTable()- List ConfigHub spacesRenderUnitsTable()- Display units with optional upstream infoRenderSetsTable()- Show configured SetsRenderFiltersTable()- Display Filters with WHERE clausesRenderActivityTable()- Show activity timelineRenderStateComparisonTable()- Compare desired vs actual stateRenderEnvironmentHierarchyTable()- Show env relationshipsRenderCostAnalysisTable()- Display cost estimatesRenderSuccessFailureTable()- Show operation resultsRenderKubectlTable()- Generic table with custom headers
- Exponential backoff with configurable parameters
- Context-aware cancellation support
- Retryable error pattern matching
- Comprehensive logging
Key Functions:
NewRetryableClient()- Create client with retry supportRunWithRetry()- Execute function with automatic retriesRetryConfig- Configure max attempts, initial delay, max delay, multiplier
package main
import (
"log"
sdk "github.com/monadic/devops-examples/devops-sdk"
)
func main() {
config := sdk.DevOpsAppConfig{
Name: "my-devops-app",
Version: "1.0.0",
Description: "My DevOps automation app",
RunInterval: 5 * time.Minute,
HealthPort: 8080,
}
app, err := sdk.NewDevOpsApp(config)
if err != nil {
log.Fatal(err)
}
// Run your main logic
if err := app.Run(func() error {
// Your reconciliation logic here
return processResources(app)
}); err != nil {
log.Fatal(err)
}
}
func processResources(app *sdk.DevOpsApp) error {
// Use the pre-initialized clients
ctx := context.Background()
pods, err := app.K8s.Clientset.CoreV1().Pods("default").List(ctx, metav1.ListOptions{})
// Get ConfigHub units using real API with space ID
spaceID := uuid.MustParse("your-space-id")
units, err := app.Cub.ListUnits(sdk.ListUnitsParams{
SpaceID: spaceID,
Where: "Labels.monitor = 'true'",
})
// Analyze with Claude (now with comprehensive logging)
response, err := app.Claude.Complete("Analyze this configuration and identify issues...")
return nil
}claude := sdk.NewClaudeClient(apiKey)
// Enable debug logging to see full prompts/responses
claude.EnableDebugLogging()
// Or set environment variable: CLAUDE_DEBUG_LOG=true
// Simple completion with automatic logging
response, err := claude.Complete("Analyze this Kubernetes configuration for issues")
// Analyze JSON data (logs request/response automatically)
analysis, err := claude.AnalyzeJSON(
"Identify drift in these deployments and suggest fixes",
driftData,
)
// Get structured response with logging
var result DriftAnalysis
err := claude.AnalyzeWithStructuredResponse(
"Analyze configuration drift and return JSON with fixes",
comparisonData,
&result,
)
// Get request statistics
count, stats := claude.GetRequestStats()
fmt.Printf("Made %d Claude API calls\n", count)cub := sdk.NewConfigHubClient(baseURL, token)
// List units using real API with filters
units, err := cub.ListUnits(sdk.ListUnitsParams{
SpaceID: spaceID,
Where: "Labels.tier = 'critical'",
})
// Create a unit with upstream relationship
unit, err := cub.CreateUnit(spaceID, sdk.CreateUnitRequest{
Slug: "my-deployment",
DisplayName: "My Application Deployment",
Data: yamlContent,
UpstreamUnitID: &baseUnitID, // For inheritance
Labels: map[string]string{"tier": "critical"},
})
// Create a space with proper request
space, err := cub.CreateSpace(sdk.CreateSpaceRequest{
Slug: "new-space",
DisplayName: "New Environment Space",
Labels: map[string]string{"environment": "dev"},
})
// Use Sets for bulk operations
set, err := cub.CreateSet(spaceID, sdk.CreateSetRequest{
Slug: "critical-services",
DisplayName: "Critical Services Set",
})
// Apply changes using push-upgrade pattern
err = cub.BulkPatchUnits(sdk.BulkPatchParams{
SpaceID: targetSpaceID,
Where: "SetID = '" + set.SetID.String() + "'",
Patch: patchData,
Upgrade: true, // Push-upgrade to downstream
})// Get space by name (no more manual UUID lookups)
space, err := cub.GetSpaceBySlug("my-project-dev")
// Create space with unique prefix (like cub space new-prefix)
space, fullName, err := cub.CreateSpaceWithUniquePrefix("drift-detector",
"Drift Detector App", map[string]string{"app": "drift-detector"})
// Result: space named "prefix-1234567890-drift-detector"
// Clone units with upstream relationships
units, err := cub.BulkCloneUnitsWithUpstream(
sourceSpaceID, targetSpaceID,
[]string{"deployment", "service", "rbac"},
map[string]string{"environment": "staging"},
)
// Apply units in dependency order
err = cub.ApplyUnitsInOrder(spaceID, []string{
"namespace", "rbac", "service", "deployment",
})// Create Helm helper
helm := sdk.NewHelmHelper(cub, spaceID)
// Install a Helm chart
err := helm.InstallChart("my-nginx", "bitnami/nginx", sdk.HelmOptions{
Namespace: "web",
Version: "15.5.2",
Values: []string{
"service.type=LoadBalancer",
"replicaCount=3",
},
})
// List Helm releases
releases, err := helm.ListHelmReleases()
for _, release := range releases {
fmt.Printf("Release: %s, Chart: %s v%s\n",
release.Name, release.Chart, release.Version)
}
// Check for newer versions
release, _ := helm.GetHelmRelease("my-nginx")
hasUpdate, newVersion, _ := helm.CompareChartVersions(release)
if hasUpdate {
fmt.Printf("Update available: %s -> %s\n", release.Version, newVersion)
// Upgrade the chart
err = helm.UpgradeChart("my-nginx", "bitnami/nginx", sdk.HelmOptions{
Version: newVersion,
UpdateCRDs: true,
})
}
// Generate correction command for drift
cmd := helm.GenerateUpgradeCommand(release, newVersion)
fmt.Printf("To fix drift, run: %s\n", cmd)// Note: Requires CONFIGHUB_EXPERIMENTAL=1 environment variable
pkg := sdk.NewPackageHelper(cub)
// Export app configuration to package
err := pkg.CreatePackage("./my-app-package", sdk.PackageOptions{
SpaceID: spaceID,
Where: "Labels.app='drift-detector'",
})
// Load package from local directory
err = pkg.LoadPackage("./my-app-package", "staging")
// Load from GitHub
err = pkg.LoadPackageFromGitHub("monadic", "packages", "drift-detector", "prod")
// Clone entire environment
err = pkg.CloneEnvironment(prodSpaceID, "staging-clone")
// Backup space with timestamp
backupPath, err := pkg.BackupSpace(spaceID, "./backups")
fmt.Printf("Backup created at: %s\n", backupPath)
// Restore from backup
err = pkg.RestoreSpace(backupPath, "restored")
// Create versioned package
err = pkg.CreateVersionedPackage("./release", "v1.2.0", sdk.PackageOptions{
SpaceID: spaceID,
})
// Publish package to Git
err = pkg.PublishPackage("./my-app-package",
"https://github.com/myorg/packages.git",
"Release v1.2.0")// Get configured clients
k8s, err := sdk.NewK8sClients()
// Use different client types
pods, err := k8s.Clientset.CoreV1().Pods("").List(...)
metrics, err := k8s.MetricsClient.MetricsV1beta1().PodMetricses("").List(...)
// Resource helpers
helper := sdk.NewResourceHelper()
value := helper.GetResourceValue(resource, "spec.replicas")
helper.SetResourceValue(resource, "spec.replicas", 5)The SDK automatically reads these environment variables:
CLAUDE_API_KEY: Claude API keyCLAUDE_DEBUG_LOG: Set to "true" to enable full prompt/response loggingCUB_TOKEN: ConfigHub authentication tokenCUB_API_URL: ConfigHub API base URLKUBECONFIG: Path to kubeconfig fileNAMESPACE: Default namespace for operations
# Standard logging: request/response previews only
export CLAUDE_DEBUG_LOG=false
# Debug logging: full prompts and responses
export CLAUDE_DEBUG_LOG=trueExample log output:
[Claude] req-1 ◀ REQUEST: Analyze this Kubernetes configuration for drift...
[Claude] req-1 → Sending API request
[Claude] req-1 ▶ RESPONSE (2.1s): I found 3 configuration drift issues...
// Environment variables with defaults
namespace := sdk.GetEnvOrDefault("NAMESPACE", "default")
required := sdk.GetEnvOrPanic("CLAUDE_API_KEY")
enabled := sdk.GetEnvBool("AUTO_APPLY", false)
interval := sdk.GetEnvDuration("CHECK_INTERVAL", 5*time.Minute)
port := sdk.GetEnvInt("PORT", 8080)// Simple retry with default config
err := sdk.RunWithRetry(ctx, 3, func() error {
return apiCall()
})
// Advanced retry with custom config
config := sdk.RetryConfig{
MaxAttempts: 5,
InitialDelay: 1 * time.Second,
MaxDelay: 30 * time.Second,
Multiplier: 2.0,
RetryableErrors: []string{"connection refused", "timeout"},
}
client := sdk.NewRetryableClient(config)
err := client.Do(ctx, func() error {
return unreliableOperation()
})// Render ConfigHub spaces
spaces, _ := cub.ListSpaces()
fmt.Println(sdk.RenderSpacesTable(spaces))
// Render units with upstream relationships
units, _ := cub.ListUnits(sdk.ListUnitsParams{SpaceID: spaceID})
fmt.Println(sdk.RenderUnitsTable(units, true))
// Render state comparison (drift detection)
resources := []sdk.ResourceState{
{
Name: "Deployment/backend-api",
DesiredState: "replicas: 3",
ActualState: "replicas: 5",
Drift: true,
},
}
fmt.Println(sdk.RenderStateComparisonTable(resources))
// Render cost analysis
estimates := []sdk.UnitCostEstimate{
{
UnitSlug: "backend-api",
MonthlyCost: 150.00,
ResourceType: "Deployment",
},
}
fmt.Println(sdk.RenderCostAnalysisTable(estimates))// Create health checker
healthChecker := sdk.NewComprehensiveHealthCheck(
k8s.Clientset,
cub,
"default",
)
// Run health check
ctx := context.Background()
result, err := healthChecker.RunHealthCheck(ctx)
// Check results
if result.Status == sdk.HealthStatusHealthy {
fmt.Println("All systems operational")
} else {
fmt.Printf("Issues detected: %v\n", result.Issues)
}
// Validate ConfigHub compliance
corrections := []string{
"cub unit update backend --patch ...",
"cub unit apply backend --space prod",
}
isCompliant := healthChecker.CheckConfigHubCompliance(corrections)The SDK is used by three production-ready DevOps apps in the devops-examples repository:
Event-driven configuration drift detection with auto-correction.
Key features:
- Kubernetes informers for real-time drift detection
- ConfigHub Sets and Filters for targeting critical services
- Claude AI for root cause analysis
- Push-upgrade pattern for multi-environment fixes
- Web dashboard on :8080
Deployment:
cd devops-examples/drift-detector
bin/install-base # Create ConfigHub structure
bin/setup-worker # Install ConfigHub worker
bin/apply-base # Deploy to Kubernetes
bin/test-workflow # Validate everything worksSee QUICKSTART.md for full guide.
AI-powered cost optimization with OpenCost integration.
Key features:
- Real-time cost analysis from OpenCost or AWS pricing
- Claude AI cost recommendations
- Bulk optimization across environments
- Interactive web dashboard on :8081
- Metrics server integration
Deployment:
cd devops-examples/cost-optimizer
bin/install-base # Create ConfigHub structure
bin/setup-worker # Install ConfigHub worker
bin/apply-base # Deploy to Kubernetes
bin/test-workflow # Validate everything worksSee QUICKSTART.md for full guide.
Pre-deployment cost analysis with trigger-based hooks.
Key features:
- Monitors all ConfigHub spaces for cost changes
- Pre-apply warnings for high-cost deployments
- Post-apply verification and learning
- Cross-environment cost tracking
- Web dashboard on :8083
Deployment:
cd devops-examples/cost-impact-monitor
bin/install-base # Create ConfigHub structure
bin/setup-worker # Install ConfigHub worker
bin/apply-base # Deploy to Kubernetes
bin/test-workflow # Validate everything worksSee QUICKSTART.md for full guide.
All examples follow the same deployment pattern:
- Create ConfigHub structure -
bin/install-basecreates spaces, filters, and units - Set up worker -
bin/setup-workerinstalls ConfigHub worker for applies - Deploy to Kubernetes -
bin/apply-basesets targets and applies units - Validate -
bin/test-workflowchecks everything is working
This demonstrates the ConfigHub → Worker → Kubernetes deployment workflow that replaces traditional kubectl apply with ConfigHub-managed deployments.
- Pre-initialized clients for ConfigHub, Kubernetes, and Claude AI
- Consistent error handling and logging patterns
- Health checks, metrics, and graceful shutdown support
- Strongly typed API clients
- Mockable components for testing
- Extensible architecture for additional clients and utilities