The user wants me to build a system for "config-as-data" that includes:
Schema Linting: Validation against a schema (e.g., JSON Schema) to ensure structure and types are correct.
Review Gates: A mechanism to approve changes (often implemented via Pull Requests).
Audit: Logging who changed what and when.
This sounds like a request for a technical architecture or a code example (likely Python or Go, or perhaps a Terraform/CUE/JSON scheme). Since the prompt is brief ("Build a..."), I should provide a comprehensive conceptual design and a concrete implementation example.
Choice of Technology:
Language: Python is widely understood and great for scripting tooling. Go is also good, but Python might be more accessible for a "config-as-data" logic demo.
Format: YAML is the standard for config-as-data.
Validation:pykwalify or jsonschema are common. Let's use jsonschema (via a yaml wrapper) as it's an industry standard.
Storage/Versioning: Git is the de facto standard for version control, review gates, and history.
Automation: GitHub Actions (or GitLab CI) are perfect for implementing the "gates" and "linting" automatically.
Implementation Example: Create a mock repository structure.
config.yaml: The data.
schema.json: The rules.
validate.py: The linter script.
audit.py: The script to record changes (simulated).
.github/workflows/main.yml: The automation for gating and linting.
Audit Mechanism: Explain how to track changes (Git log vs. external DB).
Drafting the Content:
Phase 1: The Schema. Define a simple schema (e.g., for a server configuration: CPU, RAM, Environment).
Phase 2: The Config. Create a valid and an invalid example.
Phase 3: The Linter. Write a Python script using jsonschema and PyYAML.
Phase 4: The Gate (CI/CD). Define a workflow that runs the linter on Pull Requests. It must fail if validation fails.
Phase 5: The Audit. Show how to extract commit metadata (Author, Time, SHA) and log it to a file or database upon merge.
Refining the "Review Gates" aspect:
In a real system, "Review Gates" usually means "Code Owners" or "Branch Protection Rules". I should mention these specifically in the architecture section.
Refining the "Audit" aspect:
Real auditing usually requires an immutable ledger or a specific database table. I'll simulate an "append-only log" file for the demo to keep it self-contained.
Self-Correction/Review:
The prompt asks to "Build" it. Just describing it isn't enough. I need to provide code.
I will structure the response as a complete "mini-project" guide.
Project Structure:
text
config-repo/
├── .github/workflows/
│ └── validate.yml # The Gate
├── schemas/
│ └── service.json # The Schema
├── configs/
│ └── production.yaml # The Data
├── scripts/
│ ├── validate.py # The Linter
│ └── audit.py # The Auditor
└── audit.log # The History
Let's proceed with generating this structure and explanation.
This design implements a Config-as-Data pipeline using a GitOps approach. In this model, configuration files (YAML/JSON) are treated as immutable data objects that must pass strict validation (linting), human verification (review gates), and compliance tracking (audit) before being applied.
Here is a complete implementation architecture using Python for the tooling, JSON Schema for linting, and GitHub Actions for the orchestration.
1. The Project Structure
text
config-repo/
├── .github/
│ └── workflows/
│ └── pipeline.yml # Orchestration (Review Gates & Linting)
├── schemas/
│ └── service.schema.json # The "Law" (Schema Definition)
├── policies/
│ └── checks.py # The Logic (Python Linter/Auditor)
├── configs/
│ └── production/
│ └── api-service.yaml # The Data (Config)
├── audit.log # The Compliance Record
└── requirements.txt # Dependencies (pyyaml, jsonschema)
policies/checks.py (The Linting Engine)
This script validates the config against the schema and enforces custom business logic (Policy-as-Code).
python
import sys
import json
import yaml
from jsonschema import validate, ValidationError
from pathlib import Path
from datetime import datetime
def load_config(filepath):
with open(filepath, 'r') as f:
return yaml.safe_load(f)
def lint_config(config_path, schema_path):
# 1. Load Data
config = load_config(config_path)
with open(schema_path, 'r') as f:
schema = json.load(f)
# 2. Structural Validation (Schema Linting)
try:
validate(instance=config, schema=schema)
print(f"✅ Schema Linting Passed for {config_path}")
except ValidationError as e:
print(f"❌ Schema Linting Failed: {e.message}")
sys.exit(1)
# 3. Business Logic Linting (Custom Rules)
# Example: Production services cannot use t2.micro
if config.get('environment') == 'production':
instance = config.get('scaling', {}).get('instance_type')
if instance == 't2.micro':
print(f"❌ Policy Violation: Production services cannot use t2.micro.")
sys.exit(1)
print(f"✅ Policy Checks Passed for {config_path}")
return config
def write_audit_log(config, user, action="APPROVED"):
# Append-only audit log
timestamp = datetime.utcnow().isoformat()
log_entry = {
"timestamp": timestamp,
"user": user,
"action": action,
"service_id": config.get('service_id'),
"config_hash": hash(str(config)) # Simple hash for integrity
}
with open("audit.log", "a") as f:
f.write(json.dumps(log_entry) + "\n")
print(f"📝 Audit Log Updated: {timestamp}")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python checks.py <config_file>")
sys.exit(1)
# Mocking user for local test; in CI, this comes from ENV vars
current_user = "admin@example.com"
config = lint_config(sys.argv[1], "schemas/service.schema.json")
write_audit_log(config, current_user)
4. Review Gates (The Workflow)
We use GitHub Actions to enforce the "Gate." This pipeline runs on a Pull Request. It prevents merging if linting fails.
.github/workflows/pipeline.yml
yaml
name: Config Validation Pipeline
on:
pull_request:
branches: [ main ]
push:
branches: [ main ]
jobs:
lint-and-audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # Fetch history for audit
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install Dependencies
run: |
pip install pyyaml jsonschema
# THE LINTING GATE
- name: Validate Config Schema & Policies
env:
ACTOR: ${{ github.actor }}
run: |
# Find all yaml files in configs/ and run validation
for file in configs/**/*.yaml; do
echo "Validating $file..."
python policies/checks.py "$file"
done
# THE AUDIT STAGE (Only runs on merge/push to main)
- name: Finalize Audit Trail
if: github.event_name == 'push'
run: |
echo "Configuration merged to main. Audit log finalized."
# In a real scenario, you would upload audit.log to S3 or a DB here.
5. The Audit (Compliance)
The audit is the immutable record of who approved what change. The script above writes to audit.log.
Change Request: A developer edits api-service.yaml to change replicas.
Submit: They open a Pull Request.
Gate 1 (Automated Lint): The GitHub Action triggers. checks.py runs.
If the YAML syntax is wrong: FAIL.
If they set min_replicas: 0 (violates schema): FAIL.
If they try to use t2.micro in prod (violates policy): FAIL.
Gate 2 (Human Review): A peer reviews the code changes (Diff).
Merge: Once the automated check passes and the human approves, the PR is merged.
Audit: Upon merge, the system records the final state and the actor to the audit log.
Advanced Implementations
For enterprise grade systems:
Schemas: Use CUE (Configure, Unite, Execute) or Rego (OPA) instead of JSON Schema for more complex logical constraints (e.g., "If region is EU, encryption must be mandatory").
Audit: Instead of a local file, stream audit logs to Splunk, Datadog, or an immutable ledger service.
Drift Detection: Add a scheduled pipeline that runs every hour to compare the Git config state against the actual production state (e.g., AWS state) and alerts if they differ.