We are designing a cross-environment configuration drift detector with auto-remediation. This involves multiple environments (e.g., dev, staging, production). The system should detect configuration drift between environments, assess risk, possibly auto-remediate, have a rollback policy, and define a developer workflow.
Key components:
-
Detection Logic: How to detect drift? Compare configurations across environments. This could be done by having a source of truth (e.g., a canonical configuration) and comparing each environment's actual configuration against it. Alternatively, compare pairwise between environments and flag differences. We need to define what "configuration" means: it could be infrastructure as code (IaC) templates, environment variables, application config files, database settings, etc. We assume we have a way to collect configuration from each environment (via agents, APIs, or scanning). Also, we need to consider the frequency of detection (scheduled, on-change, etc.) and the criteria for what constitutes drift (any difference? only certain keys?).
-
Risk Scoring: Not all drifts are equal. We need a scoring system to prioritize remediation. Factors could include: environment (production drift is riskier than dev), type of configuration (security-related, performance, etc.), magnitude of change, criticality of the affected service, etc. We can assign weights and compute a risk score. This score will inform whether auto-remediation is allowed or requires manual approval.
-
Auto-Remediation: The system may automatically correct drift under certain conditions (e.g., low risk). Remediation could involve applying the correct configuration from the source of truth, or rolling back to a previous known good state, or alerting a human. We need to define the conditions for auto-remediation: maybe risk score below a threshold, or only for non-breaking changes. Also, we need a way to apply the fix safely (e.g., using IaC apply, restarting services, etc.). There should be safeguards: avoid causing downtime, ensure we don't auto-remediate if the change is intentional (like a canary deployment that hasn't propagated fully). Possibly a verification step after remediation.
-
Rollback Policy: If auto-remediation causes issues (e.g., the applied configuration is bad), we need to rollback. Or if a manual remediation fails, we might need to rollback. Rollback should be to the previous stable configuration. We need to define what constitutes a failure (monitoring alerts, health checks). Also, we need to keep history of configurations and their deployments to enable rollback. The rollback policy could be: automatically rollback if health checks fail after remediation within a certain window, or manual approval for rollback after detection of issues.
-
Developer Workflow: How do developers interact with this system? They should be able to request configuration changes, see drift detection results, approve or reject auto-remediation, and possibly manually remediate. Also, they should be able to override the source of truth if a drift is intentional (e.g., hotfix). The workflow should integrate with existing CI/CD and change management processes. Possibly provide dashboards, notifications, and APIs.
We'll need to design the overall architecture and processes.
Let's outline:
System Overview
- We have multiple environments: dev, staging, prod, etc.
- Each environment has a set of configurations that can be represented as key-value pairs, files, or structured data. We'll assume we have a unified configuration model, perhaps using a schema.
- There is a canonical configuration store (source of truth). This could be a Git repository (IaC) or a dedicated configuration management database (CMDB). We'll assume the source of truth is version-controlled and changes to it go through a review process.
- We have a configuration collector that periodically or on-demand fetches the actual configuration from each environment.
- A drift detector compares the actual configuration against the source of truth (or against other environments) and produces a drift report.
- A risk scorer evaluates each drift and assigns a risk score.
- A remediation engine decides whether to auto-remediate (based on risk score and policy) or to raise an alert.
- A rollback manager handles rollbacks if needed.
- A dashboard and notification system for visibility.
Detailed Design
1. Detection Logic
- Configuration Collection: For each environment, we collect configuration data. This can be done via:
- Pull model: A central service queries each environment's configuration API or runs a script.
- Push model: Agents running in each environment push their config to a central store.
- We need to handle different types: e.g., Kubernetes ConfigMaps, environment variables, database connection strings, feature flags, etc. Might need adapters.
- Comparison: We compare the collected configuration with the expected configuration (from the source of truth). The expected config for each environment might be the same as the source of truth, or there could be environment-specific overrides. So we need a way to define the expected configuration for each environment. Possibly we have a base configuration and environment-specific layers. The source of truth could include all environments' configurations, or we derive expected config for an environment by applying its environment variables to the base. Alternatively, we treat the source of truth as the desired state for all environments (except maybe prod has some differences that are intentional). So we need to maintain a mapping: for each configuration key, we know what the expected value is in each environment. This mapping can be stored in a configuration repository with directory structure (e.g., config/dev/, config/prod/).
- Drift Identification: Any difference between actual and expected is a drift. However, we might ignore certain keys (like timestamps, generated values). We can have an ignore list or use a diff algorithm that can handle ordered lists, etc. Also, we might consider differences only if they are beyond a tolerance (e.g., numeric values within 5% might be acceptable? Probably not for config). Better to be exact for critical configs, but allow intentional overrides.
- Drift Reporting: For each drift, we record: environment, configuration key/path, expected value, actual value, timestamp, and maybe the source (which component). Also, we might want to know if the drift is due to a recent change (we can compare with previous states to see if it's new).
- Frequency: Detection can be scheduled (e.g., every 5 minutes) or triggered by events (e.g., a new deployment, a change in source of truth). Event-driven is more efficient. We can have webhooks from CI/CD pipelines to trigger detection after a deployment, and also periodic scans to catch out-of-band changes.
2. Risk Scoring
We assign a risk score to each drift. The score could be on a scale (0-100). Factors:
- Environment Weight: Production = high weight, Staging = medium, Dev = low.
- Configuration Criticality: Some configs are more critical (e.g., database connection strings, security keys, feature flags that affect revenue). We can have a tagging system in the source of truth: each config key can be labeled as
critical, high, medium, low. Or we can have a policy that all configs in certain paths are critical.
- Change Type: Adding a new config might be less risky than changing an existing one. Changing a value from safe to dangerous (e.g., turning off logging) might be more risky. We could analyze the delta: if the new value is outside a known safe range (e.g., connection pool size too low/high), that increases risk.
- Sensitivity: If the config contains secrets (PII, passwords) then even a small drift is high risk because it might indicate a leakage or misplacement.
- Propagation: If the same drift appears in multiple environments, maybe it's intentional (like a new feature rolled out gradually). Actually, if we compare against source of truth, and source of truth has been updated but environments haven't caught up, that's expected drift during deployment. We need to differentiate between "expected drift" (due to ongoing deployment) and "unexpected drift". So we should track deployment events: after a deployment to an environment, we expect that environment's config to drift temporarily until the deployment completes. We can mark those drifts as "in-progress" and not score them as high risk until a timeout.
- Historical Behavior: If a particular config frequently drifts and then self-corrects, maybe it's flaky and we can lower its risk score? Or if it's never changed intentionally, any drift is suspicious.
We'll compute a weighted sum:
Risk = w_env * env_factor + w_crit * criticality + w_change * change_type + w_sens * sensitivity + w_prop * propagation_status + ...
We can normalize to 0-100.
Then, we set thresholds:
- Low risk (0-30): auto-remediate immediately.
- Medium risk (31-70): require manual approval before remediation (maybe with a time limit, e.g., if not approved within 1 hour, auto-remediate? Or not auto).
- High risk (71-100): never auto-remediate; alert and require manual intervention.
These thresholds are configurable.
3. Auto-Remediation
- Policy Engine: Based on risk score and drift properties, decide action.
- Remediation Actions:
- If drift is due to source of truth being updated, apply the new expected configuration to the environment. This can be done via the same mechanism used for deployment (e.g., run Ansible playbook, apply Terraform, update Kubernetes ConfigMap). We must ensure the remediation is applied in a safe way: maybe canary? For config changes, often a restart is needed. So we might need to orchestrate a rolling update.
- If drift is due to the environment being ahead of source of truth (e.g., a hotfix was applied manually without updating source of truth), we might want to roll back the environment to match source of truth, or update source of truth to match environment. The latter might be preferred if the change is intentional and beneficial. But our system's goal is to enforce consistency with source of truth. However, if a developer manually changed something in production to fix an issue, we should capture that as a new desired state. So we need a process: when drift is detected, we can prompt: "Environment X has config Y different from source. Is this intentional?" If yes, then we update the source of truth (via PR) to match. That is a remediation from the perspective of aligning source of truth, but actually we are making source of truth reflect reality. That is not auto-remediation; it's a manual workflow. So auto-remediation should only be one-way: force environment to match source of truth.
- Pre-checks: Before applying remediation, check that the environment is healthy (e.g., passing health checks). If not, we might delay or skip auto-remediation to avoid making things worse.
- Post-remediation Verification: After applying the fix, verify that the configuration now matches expected and that the service is healthy. If not, trigger rollback.
- Safety: Auto-remediation should be disabled for certain environments (e.g., production) unless risk is very low. Even then, we might want a manual approval window? Or we can have an "auto-remediate only if risk < X and environment = staging/ dev". For production, require manual approval for all changes, but if risk is very low (e.g., a config that is known to be safe and change is just adding a comment), maybe auto. But by default, production should be manual.
4. Rollback Policy
- Trigger Conditions:
- Post-remediation health check fails (e.g., service down, error rate increased beyond threshold, or specific config-dependent health check).
- A drift is detected that risks the system even after remediation (maybe remediation partially applied).
- A manual rollback request from an operator.
- Rollback Mechanism:
- We keep a history of configurations (versions) for each environment. When we apply a new configuration, we store the previous one as a rollback candidate.
- Rollback simply reapplies the previous configuration.
- We need to ensure rollback is fast and reliable. Could be a one-click operation.
- Rollback Scope: Might be per service or per environment. Usually, rollback the specific configuration that changed.
- Policy:
- Automatic rollback: If remediation was auto-applied and health fails within, say, 5 minutes, automatically rollback.
- Manual rollback: If remediation was manually applied, operator can trigger rollback if issues arise.
- We should also have a "circuit breaker": if multiple rollbacks happen in a short period, disable auto-remediation for that config/service and alert.
5. Developer Workflow
- Configuration Change Process:
- Developer wants to change configuration. They modify the source of truth (e.g., edit a YAML file in the config repo) and submit a PR.
- PR goes through review (including risk assessment maybe). Once merged, the new expected configuration is deployed to environments via the normal deployment pipeline (or the drift detector will trigger remediation to bring environments up to date). Alternatively, the deployment pipeline itself updates environments, and drift detector is a safety net.
- Drift Detection Results:
- Dashboard shows current drifts, risk levels, and remediation status.
- Notifications: Slack/email alerts for high/medium risk drifts.
- Handling Drift:
- If drift is unexpected, developer (or SRE) can investigate. They can either:
- Approve auto-remediation: if risk is medium and they approve, system will apply fix.
- Reject: if the drift is intentional (e.g., emergency fix), they can mark it as accepted and update the source of truth to match the environment (so drift resolved).
- Ignore: maybe temporarily ignore certain drifts (e.g., known issue).
- Manual Remediation: For high-risk drifts, an operator may manually apply the fix (e.g., via existing tools). They then mark the drift as resolved.
- Audit Trail: All actions (detection, risk scoring, remediation, rollback, approvals) should be logged for compliance.
Architecture Sketch
We'll have the following services:
- Config Collector: Runs on each environment or centrally polls. Outputs actual config to a central data store (e.g., database or object storage).
- Source of Truth: Git repo or config management DB. We have a service that watches for changes and stores latest expected config for each environment.
- Drift Detection Service: Periodically or on event, fetches actual configs from store and expected configs from source, compares, and writes drift records to database. Also triggers risk scoring.
- Risk Scorer: Could be part of drift detection. It computes risk score per drift based on policies (configurable).
- Policy Engine: Decides on remediation action based on risk score and other rules.
- Remediation Engine: Executes remediation actions (e.g., using Terraform, Ansible, Kubernetes API, or custom scripts). It may also orchestrate canary deployments if needed.
- Rollback Service: Handles rollback requests, manages version history.
- Dashboard/API: For developers and operators to view drifts, approve actions, trigger manual remediation.
- Notification Service: Sends alerts.
- Health Check Service: Monitors environment health (maybe integrated with existing monitoring) to verify post-remediation.
Data Flow:
- Collect actual configs -> store.
- Get expected configs from source -> compare -> drifts.
- Score drifts.
- For each drift:
- If auto-remediate eligible, schedule remediation.
- Else, create a pending approval item and notify.
- Remediation: apply expected config.
- Verify health and config match. If fails, trigger rollback.
- Record outcome.
Edge Cases and Considerations
-
Drift due to ongoing deployment: When we deploy to an environment, we expect a temporary drift as new config is being rolled out. We should not flag these as issues if we know a deployment is in progress. We can track deployment events via CI/CD pipeline notifications. During deployment, we might suppress drift detection for the affected services or mark drifts as "expected".
-
Intentional drift: Sometimes we want environments to differ (e.g., prod has higher replica count). That should be captured in the source of truth (i.e., the expected config for prod includes that difference). So we need to model environment-specific values properly. Use templating: base config + environment variables. So differences are expected and not drifts. Drift occurs when actual deviates from the environment-specific expected config.
-
Partial drift: A configuration may have many keys; only some differ. Remediation might apply the entire config, which could override other changes that were intentionally made? If we apply the entire expected config, we might overwrite local modifications that are not part of the source of truth. That could be undesirable if those modifications are necessary (e.g., an emergency hotfix that hasn't been merged). So we need to be careful: remediation should only apply the specific keys that drifted? But config files are often atomic; you replace the whole file. If the file has been manually edited in the environment, replacing it with the version from source of truth will wipe those edits. That's okay if we want to enforce consistency. But if the edit is an emergency fix, we want to capture that in source of truth. So before auto-remediating, we could check: if the actual config differs from expected in a way that looks like an emergency fix (e.g., a value that is out of normal range but necessary), we might not want to auto-revert. But that's hard. Better to rely on manual approval for such cases. So auto-remediation only for low-risk drifts where we are confident the expected value is correct and safe. Typically, low-risk drifts are minor things like adding a logging level that doesn't affect functionality.
-
Order of remediation: If multiple drifts exist, we might remediate them in order of risk, or all at once. We could batch them.
-
Rollback safety: When rolling back, we also need to verify health. Could also auto-rollback if health fails.
-
Scale: Many configs, many environments. We need efficient diffing. Could use hash comparisons.
-
Security: The system itself must be secure; it has the ability to change production configs. Access control: only authorized users can approve manual remediation, change policies, etc.
Implementation Steps
We'll design a modular system.
Tech Stack (hypothetical)
- Language: Go or Python for services.
- Storage: PostgreSQL for drift records, config history; object storage for config snapshots.
- Messaging:RabbitMQ or Kafka for event-driven processing.
- Dashboard: Web UI with React.
- Integration: With existing CI/CD (Jenkins, GitLab CI, GitHub Actions), monitoring (Prometheus, Datadog), and config management tools (Ansible, Terraform, Helm).
Policy Configuration
We need a way to define risk scoring rules and auto-remediation thresholds. This could be YAML files stored in a config repo, loaded by the policy engine. Example:
risk_scoring:
environment_weights:
production: 50
staging: 30
development: 10
criticality_levels:
critical: 40
high: 30
medium: 20
low: 10
change_type_weights:
modification: 15
addition: 5
deletion: 10
sensitivity_multiplier:
secret: 2.0
pii: 1.5
propagation_penalty:
expected_during_deployment: -20 # reduce risk if deployment known
not_propagated: 0
auto_remediate_threshold: 30
manual_approval_threshold: 70
We also need to tag configuration keys with criticality and sensitivity. This could be done via annotations in the config repo or a separate mapping.
Workflow Example
Scenario 1: A developer changes a config value in the source of truth (e.g., increases log level). The change is merged. CI/CD deploys to dev environment. Drift detector runs on dev and finds the config matches now (no drift). Then on staging, drift detected because staging hasn't been deployed yet. Drift risk: environment=staging weight 30, criticality=low (10), change type=modification (15) -> total 55 -> medium. Since it's medium, it requires manual approval. The SRE sees alert, approves. Remediation engine applies the new config to staging (via the same deployment mechanism). After remediation, health check passes. Drift resolved.
Scenario 2: In production, a critical config (e.g., DB connection string) is changed manually (emergency) without updating source of truth. Drift detected: environment=prod weight 50, criticality=critical (40), change type=modification (15), sensitivity=secret (multiplier 2, so maybe 50+40+15)*2? Actually better to sum then multiply? We'll compute: base = 50+40+15 = 105; then apply sensitivity multiplier? That would exceed 100. Better to have multipliers applied to individual components or have a normalized score. Simpler: assign each factor a 0-10 score and weight them, then sum to 100. Anyway, high risk. System alerts. No auto-remediation. Operator investigates: the change was an emergency to switch to a failover DB. They decide to accept the drift and update source of truth to match production. They create a PR with the new config, merge it. Then drift detector will see that production matches source of truth (if we update source of truth with the new value). But careful: production's actual config is the new value; after PR merged, expected config becomes that new value, so drift resolved. So no remediation needed because they aligned source to reality. Alternatively, if the emergency change was incorrect, they would manually revert on production and then update source of truth accordingly. Either way, drift resolved after manual action.
Scenario 3: A config change is deployed to production via canary. During canary, some pods have old config, some have new. Drift detector will see that the actual config of the environment (maybe aggregated?) doesn't match expected? How do we define "environment config" for a distributed system? We might need to consider that configuration can be at multiple granularities: cluster-level, namespace-level, pod-level. Our drift detector might operate at the level of the infrastructure as a whole: we collect config from all nodes and compare to expected. During canary, we expect some nodes to have old config, some new. That's intentional, so we should not flag as drift. To handle this, we can have a notion of "deployment state": when a deployment is in progress, we suppress drift detection for the affected resources until deployment completes. Or we can treat the environment's expected config as the new version, and consider that during rollout, some resources haven't updated yet, so they will appear drifted. But that's expected and part of a controlled rollout. So the drift detector should be aware of deployments: it can query the deployment orchestrator (e.g., Kubernetes rollout status) to know if a rollout is ongoing and which resources are expected to be updated. If a resource hasn't updated yet, we exclude it from drift detection or mark it as "pending" with low risk. This is more advanced.
Simpler: We can have the deployment pipeline itself coordinate with the drift detector: when a deployment starts, it registers a "deployment window" during which drifts for that service are ignored. After deployment completes, drift detection resumes normally. That could be done via an API call to the drift detector service to put a hold on certain config paths.
Rollback Example
After auto-remediating a low-risk drift (e.g., changed a log level from INFO to DEBUG in staging), the remediation might cause an issue: DEBUG logging overloads the system. Health check detects increased CPU or errors. Rollback policy triggers automatic rollback: reapplies the previous config (INFO). Then health returns. Alert sent that rollback occurred. Drift might reappear? Actually if we rollback, the environment is now back to the previous state, which is still different from the new expected (since source of truth has DEBUG). So drift will be detected again. Since it's the same drift, the risk score is still low. The system might attempt auto-remediate again, causing a loop. To avoid this, after a rollback we should probably pause auto-remediation and alert for manual review, because something about the change is not safe. Alternatively, we could have a "circuit breaker": if a config change causes rollback, we mark that config as "failed" and stop auto-remediating until manual approval. That is prudent.
Developer Experience
- Dashboard shows all environments, config compliance status.
- They can drill down to see drifts, risk scores, and recommended actions.
- They can approve remediation from the dashboard.
- They can also override expected config for an environment (e.g., if they want to keep an emergency fix) and update source of truth accordingly.
Integration with CI/CD
- After CI/CD deploys config changes, it can call the drift detector to check compliance. If there are drifts (e.g., some pods didn't update), the pipeline could fail or wait until drift resolved.
- Alternatively, the drift detector runs independently and provides feedback.
Summary of Requirements
We need to produce a design document that covers:
- Detection logic: how drift is detected, what data is collected, how often, what constitutes drift.
- Risk scoring: how risk is calculated, what factors, thresholds.
- Rollback policy: when to rollback, how, how to manage versions.
- Developer workflow: how devs interact with the system, from change request to resolution.
- Additionally, maybe include architecture diagram (text description) and discuss edge cases.
Let's structure the answer accordingly.
We'll produce a comprehensive design.
Cross-Environment Configuration Drift Detector with Auto‑Remediation
1. Overview
The system continuously monitors configurations across all environments (dev, staging, prod, etc.), compares them against a source of truth (canonical configuration), detects drift, assesses risk, and either auto‑remediates or alerts for manual intervention. It includes a robust rollback mechanism and integrates into the developer/SRE workflow.
Key Principles
- Single source of truth (Git‑backed) for desired configuration.
- Agentless collection via APIs or read‑only integrations.
- Event‑driven detection on deployment events, plus periodic safety scans.
- Risk‑aware actions: low‑risk drifts auto‑remediated; higher‑risk require approval.
- Full auditability and easy rollback.
2. Detection Logic
2.1 Configuration Model
- Configuration items are structured key‑value pairs, files, or IaC templates.
- Each item has metadata:
path, environment, criticality (critical, high, medium, low), sensitivity (secret, pii, none), change_type (modification, addition, deletion).
- Expected configuration per environment is derived from the source of truth using templating (e.g., Helm/Kustomize) and environment‑specific overrides.
2.2 Collection
- Pull model: Central collector queries each environment’s configuration endpoints (e.g., Kubernetes APIs, AWS Parameter Store, database queries) on a schedule (5‑15 min) or on demand.
- Push model: Optional agents push config snapshots to a central store.
- Snapshots include a hash of the full config and a timestamp. Stored in object storage (e.g., S3) with metadata indexed in a database.
2.3 Comparison
- For each environment, compare the actual snapshot with the expected config (computed from source of truth).
- Compute a diff that accounts for:
- Value changes
- Missing/extra keys
- Type mismatches
- Ordered list changes (treated as reorder if values match set).
- Ignored fields: timestamps, generated IDs, or keys marked as
transient.
- Drift is recorded as:
{
"id": "drift-123",
"environment": "prod",
"path": "/app/db/connection_string",
"expected": "jdbc:mysql://primary",
"actual": "jdbc:mysql://failover",
"detected_at": "2025-04-01T12:00:00Z",
"change_type": "modification",
"criticality": "critical",
"sensitivity": "secret",
"deployment_id": null // linked if deployment in progress
}
2.4 Triggers
- Scheduled: Every 5 min (configurable).
- Event‑driven:
- After a deployment completes (via CI/CD webhook).
- After a change is merged to the source of truth (via Git webhook).
- Manual trigger via API.
2.5 Handling In‑Flight Deployments
- The deployment system (CI/CD) notifies the drift detector when a deployment starts/completes for a given service/environment.
- While a deployment is active, drifts that match the expected new version are marked as
expected and excluded from risk scoring/remediation. After a timeout (e.g., 30 min), if the drift persists it is treated as unexpected.
3. Risk Scoring
3.1 Factors & Weights
Each drift is scored 0–100. Components (normalized to 0–10 then weighted):
| Factor | Weight | Description |
|---|
| Environment | 0–25 | prod=25, staging=15, dev=5 |
| Criticality | 0–30 | critical=30, high=20, medium=10, low=5 |
| Change Type | 0–20 | modification=20, deletion=15, addition=5 |
| Sensitivity | 0–15 | secret=15, pii=10, none=0 |
| Propagation | 0–10 | deployment_in_progress=-10, no_deployment_known=0 |
| Historical Behavior | 0–10 | flaky_config (drift frequently self‑corrects) -5; never_changed +5 |
Example: Drift in production, critical config (secret), modification, no deployment:
Base = 25 (env) + 30 (critical) + 20 (mod) + 15 (secret) = 90
Add 0 for propagation, 0 for history = 90 → High risk
3.2 Thresholds
- Low (0‑30): Auto‑remediate immediately.
- Medium (31‑70): Require manual approval (default timeout 1 hour, then auto‑remediate unless overridden).
- High (71‑100): Never auto‑remediate; require manual intervention with elevated alerts.
Thresholds configurable per environment or config path.
4. Auto‑Remediation
4.1 Decision Engine
For each drift:
- If risk ≤ auto‑remediate threshold → schedule remediation.
- If risk in medium range → create approval ticket; if approved within timeout, remediate.
- If risk ≥ high → alert only.
4.2 Remediation Actions
- Apply expected config: Use the same mechanism as deployment (e.g., Terraform apply, Helm upgrade, Ansible playbook, Kubernetes patch). The expected config is rendered for the target environment.
- Prerequisites:
- Environment health check passes (e.g., pod ready, service responding).
- No higher‑risk drifts pending for same service.
- Throttling: max N concurrent remediations per environment.
- Post‑remediation validation:
- Re‑collect config to confirm match.
- Run health checks (HTTP 200, latency, error rate) for 2 min.
- If validation fails → trigger rollback (see section 5).
- Idempotency: Remediation scripts must be idempotent.
4.3 Safety Controls
- Production auto‑remediation disabled by default; can be enabled for low‑risk configs only (e.g., log levels).
- Circuit breaker: If a config causes >1 rollback in 24 h, auto‑remediation disabled for that config until manual review.
- Canary support: For services that support canary, remediation can be applied gradually (e.g., 10% of instances) with health monitoring before full rollout.
5. Rollback Policy
5.1 Versioning
- Every configuration snapshot stored with version number (incremental) and metadata (who deployed, from which Git commit).
- When a remediation is applied, the previous version is retained as a rollback candidate.
5.2 Rollback Triggers
- Automatic:
- Post‑remediation health check fails.
- Same drift reappears within 5 min after remediation (indicating incomplete fix).
- Manual: Operator clicks “Rollback” in dashboard or via API.
5.3 Rollback Execution
- Retrieve the previous config version for the affected environment/service.
- Apply it using the same tooling as remediation.
- Validate config match and health (same as forward remediation).
- If rollback fails, raise critical alert and pause further actions.
5.4 Post‑Rollback
- The drifted configuration (the one that caused failure) is flagged for investigation.
- Auto‑remediation for that config is disabled until a human marks it safe.
6. Developer Workflow
6.1 Making a Configuration Change
- Modify source of truth: Edit the relevant config files in the Git repository (e.g.,
config/prod/app.yaml).
- Open a PR: Include:
- Description of change and reason.
- Risk assessment (optional).
- Link to ticket (if applicable).
- Review & merge: After approval, CI/CD picks up the change and deploys to target environments (usually in order: dev → staging → prod).
- Deployment: The pipeline updates environments and notifies the drift detector of deployment start/end.
6.2 Monitoring Drift
- Dashboard (React/Grafana):
- Overview of all environments with compliance (% of configs matching).
- List of active drifts with risk scores, paths, values.
- Filter by environment, criticality, risk level.
- Notifications:
- Slack/Teams: Alerts for high‑risk drifts; medium‑risk pending approval; auto‑remediation events.
- Email digests (daily summary).
- CLI/API: Developers can query drifts, approve actions, trigger manual scans.
6.3 Responding to Drift
- Low‑risk drift: Auto‑remediated; developer receives a notification that remediation occurred.
- Medium‑risk drift:
- Developer (or SRE) receives approval request.
- They can:
- Approve: Remediation proceeds.
- Reject: Mark drift as “accepted” with comment (e.g., “intentional hotfix”). This updates the source of truth to match the environment (by automatically creating a PR or recording the acceptance). Drift resolves because expected config now equals actual.
- Ignore: Temporarily snooze (useful during known maintenance).
- High‑risk drift:
- Immediate alert.
- Developer/SRE investigates:
- If drift is intentional (e.g., emergency fix), they update the source of truth to reflect the new value (via PR). After merge, drift disappears.
- If drift is unintentional and harmful, they manually revert the configuration in the affected environment (using existing tools) and then update source of truth accordingly.
- Manual remediation: They can trigger a “force sync” from the dashboard to apply the expected config, but this is effectively a manual remediation and logged as such.
6.4 Audit & Compliance
- All actions (detections, scores, approvals, remediations, rollbacks) are logged with
actor, timestamp, and reason.
- Reports can be exported for audits (e.g., “all configuration changes in prod last month”).
7. Architecture
┌─────────────────┐ 1. collect ┌──────────────────┐
│ Environments ├─────────────────────────────────►│ Config Store │
│ (K8s, AWS, DB) │ (actual snapshots) │ (S3 + DB index) │
└─────────────────┘ └──────────────────┘
▲ ▲
│ 2. pull/push │ 3. fetch expected
│ │ from source
┌─────────────────┐ 4. compare & score │ of truth
│ Drift Detector │◄─────────────────────────────────────────┤
│ (Scheduler) │ │
└─────────────────┘ │
│ 5. publish drift events │
│ │
▼ │
┌─────────────────┐ 6. decide & act │
│ Policy Engine ├───────────────────────────────────────────┘
│ (risk + rules) │
└─────────────────┘
│ 7. remediation job
▼
┌─────────────────┐
│ Remediation │
│ Engine │
│ (Orchestrator) ─┼─► Apply config to target env
└─────────────────┘
│ 8. validate
▼
┌─────────────────┐
│ Health Check │
│ Service │
└─────────────────┘
│ 9. if fail → rollback
▼
┌─────────────────┐
│ Rollback │
│ Service │
└─────────────────┘
Data stores:
- Git repo (source of truth)
- Config snapshot store (S3)
- Drift & audit DB (PostgreSQL)
- Version history for rollbacks (stored with snapshots)
Messaging: RabbitMQ/Kafka for events (drift detected, approval needed, remediation scheduled).
UI: Dashboard (React) + API (REST/GraphQL).
8. Edge Cases & Considerations
| Scenario | Handling |
|---|
| Deployment in progress | Suppress drifts that match the new expected version; after timeout, treat as unexpected. |
| Intentional environment differences | Modelled in source of truth via overrides; not considered drift. |
| Emergency manual fix | Operator marks drift as accepted → auto‑create PR to update source of truth. |
| Flapping config | Historical behavior factor reduces risk; if frequent rollbacks, circuit‑breaker disables auto‑remediation. |
| Large-scale drift (e.g., whole cluster) | Batch remediation with rolling update; pause auto‑remediation if cluster-wide issue. |
| Secret rotation | Sensitive configs have higher weight; auto‑remediation may be disabled for them even if low risk, to avoid accidental exposure. |
| Multi‑tenant environments | Namespace‑level isolation; drift detection per tenant if needed. |
| Partial drift (only some keys) | Remediation applies the entire expected config; if file‑based, this overwrites any manual edits (by design). |
| Rollback storm | Circuit‑breaker stops further auto‑remediation after 2 rollbacks in 24 h for same config. |
| System failure | Drift detector and remediation components stateless; can be scaled horizontally. All state in DB. |
| Time‑sensitive drift | Some drifts (e.g., security policy violation) should be high‑risk regardless of environment. Can define rule: if path matches "/security/*" then risk += 30. |
9. Configuration & Extensibility
Policy as Code
Risk scoring and auto‑remediation rules are defined in a YAML file stored in the same config repo, e.g.:
risk_scoring:
environment_weights:
production: 25
staging: 15
development: 5
criticality_weights:
critical: 30
high: 20
medium: 10
low: 5
change_type_weights:
modification: 20
deletion: 15
addition: 5
sensitivity_multiplier:
secret: 1.5
pii: 1.2
propagation_adjustments:
deployment_in_progress: -10
historical_adjustments:
flaky: -5
never_changed: 5
auto_remediate_threshold: 30
manual_approval_threshold: 70
approval_timeout_minutes: 60
# Path‑specific overrides (e.g., never auto‑remediate certain paths)
blocked_paths:
- "/secrets/*"
- "/database/connection_string"
# Environment‑specific overrides
environment_overrides:
production:
auto_remediate: false # disable completely for prod
Tagging Configuration Items
Metadata can be attached via comments in config files or a separate mapping file:
# config/app.yaml
# @criticality high
# @sensitivity none
log_level: INFO
10. Implementation Roadmap (Incremental)
- Phase 1 – Core: Build collector, drift detector, basic dashboard. Manual remediation only.
- Phase 2 – Risk Scoring: Add risk engine, thresholds, notifications.
- Phase 3 – Auto‑Remediation: Implement remediation engine for low‑risk drifts in non‑prod.
- Phase 4 – Rollback: Versioning and rollback service.
- Phase 5 – Production Hardening: Add deployment integration, circuit‑breakers, advanced safety (canary, health checks).
- Phase 6 – Self‑Service: PR workflow integration, auto‑update source of truth for accepted drifts.
11. Metrics & Monitoring
- Drift count per environment, risk level.
- Remediation success rate, rollback rate.
- Mean time to detection and mean time to remediation.
- Number of auto‑ vs manual‑remediations.
- Alerts on circuit‑breaker activation.
These metrics feed into SLOs (e.g., “99% of low‑risk drifts auto‑remediated within 5 min”).
12. Security & Access Control
- RBAC: Roles:
viewer, approver, operator, admin.
- Audit logs immutable.
- Secrets in configs are never logged in plaintext; drift records mask secret values (store hashes).
- All API calls authenticated (OAuth2/JWT) and authorized.
13. Conclusion
This design provides a comprehensive, risk‑aware drift detection and remediation system that integrates seamlessly into existing DevOps workflows. It balances automation with safety, ensures quick recovery from unintentional changes, and maintains a clear audit trail—all while empowering developers to manage configuration as code.