| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
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):
SDK Modules:
Get quick feedback on ConfigHub CLI commands in your project:
⚠️ Note: This is a linter that provides helpful hints, not comprehensive validation. Always test with the actual 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:
Test coverage:
Quick links:
The DevOps SDK enables building persistent, event-driven DevOps applications. Key characteristics:
New to ConfigHub? Start with MicroTraderX Prerequisites for step-by-step installation of Docker, Kind, and ConfigHub CLI.
Quick checklist:
The SDK includes a minimal Technology Compatibility Kit for verifying ConfigHub + Kubernetes integration:
./test-confighub-k8sWhat it tests:
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:
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:
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):
Integration tests (test/integration/test-cub-validator-integration.sh):
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:
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:
All validation rules derive from Brian Grant's feedback (ConfigHub maintainer):
Key insights from Brian:
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:
Test results: 39/39 passing (100% success rate)
Validation rules cross-checked against:
Confidence level: Moderate - Provides helpful linting for common patterns
Important limitations:
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:
Documentation Code is Production Code: Commands in .md files are copy-pasted by users. Invalid examples cause hours of debugging frustration.
Current validation status (as of 2025-10-12):
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:
All content below this line 100% created by Claude.
Analyzes resource costs across ConfigHub spaces and Kubernetes deployments.
Features:
Key Functions:
Identifies resource waste by comparing allocated vs actual usage.
Features:
Key Functions:
Generates optimized configurations based on waste analysis.
Features:
Key Functions:
Direct ConfigHub → Kubernetes deployment for fast development cycles.
Features:
Key Functions:
Core deployment strategies and environment management.
Features:
Key Functions:
ConfigHub → Git → Flux/Argo → Kubernetes for production compliance.
Features:
Key Functions:
Available tables:
Key Functions:
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:
# 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:
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:
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:
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:
This demonstrates the ConfigHub → Worker → Kubernetes deployment workflow that replaces traditional kubectl apply with ConfigHub-managed deployments.
| Back | FazBrowse Home | New Git URL |