Purpose & When-To-Use
Trigger this skill when:
- Manual infrastructure changes detected outside IaC workflow
- Compliance violation suspected from untracked modifications
- Scheduled drift scan required (daily, weekly, pre-deployment)
- IaC state reconciliation needed after provider API changes
- Post-incident analysis to identify unauthorized changes
- Continuous compliance monitoring for regulated environments
Outputs: Drift detection report with changed resources, remediation plan with impact analysis, compliance status, optional auto-remediation execution with audit trail.
Pre-Checks
Time normalization:
- Compute
NOW_ET = 2025-10-25T21:30:36-04:00 (NIST/time.gov semantics, America/New_York, ISO-8601)
Input validation:
Source freshness:
Abort conditions:
- Missing cloud credentials for state comparison
- IaC tool version incompatibility
- State file locked by active operation
Procedure
T1: Fast Path (≤2k tokens) - Quick Drift Scan
Scope: Single stack/workspace, on-demand drift check, common 80% case
Identify IaC tool and load state:
- Terraform:
terraform plan -refresh-only -detailed-exitcode to preview state refresh
- CloudFormation:
aws cloudformation detect-stack-drift --stack-name <name> then poll DescribeStackDriftDetectionStatus
- Pulumi:
pulumi refresh --preview-only to compare desired vs actual
- driftctl:
driftctl scan --from tfstate://<path> --to <provider> for multi-resource scan
Parse drift detection results:
- Extract changed resources (added, modified, deleted, drifted)
- Identify changed attributes and values (before → after)
- Calculate drift severity: high (security/network), medium (config), low (tags/metadata)
Generate quick remediation guidance:
- Accept drift: Update IaC to match live state if change is intentional
- Revert drift: Apply IaC to overwrite live state if change is unauthorized
- Ignore drift: Tag resource as exception if drift is acceptable
Output drift summary:
{
"drift_detected": true,
"tool": "terraform",
"timestamp": "NOW_ET",
"drifted_resources": 3,
"severity": "high",
"resources": [
{"id": "aws_security_group.web", "change": "ingress_rules_modified", "severity": "high"}
],
"recommended_action": "revert"
}
Token budget: ≤2k (state comparison, basic drift report)
T2: Extended Path (≤6k tokens) - Comprehensive Drift Analysis + Remediation
Scope: Multiple stacks, scheduled detection, compliance reporting, semi-automated remediation
T1 fast path (all steps above)
Multi-stack drift detection:
- Terraform Cloud: Enable continuous drift detection via workspace settings; configure schedule (daily/weekly)
- Pulumi Cloud: Setup Deployments with drift schedules; configure auto-remediation policy
- CloudFormation: Use AWS Config rule
cloudformation-stack-drift-detection-check for automated compliance
- driftctl: Run
driftctl scan --filter "Type=='aws_s3_bucket'" for resource-type scoping
Drift impact analysis:
- Security impact: Check if drift affects IAM, security groups, encryption, network ACLs
- Compliance impact: Map drifted resources to compliance controls (NIST, FedRAMP, PCI-DSS)
- Dependency impact: Identify downstream resources affected by drift
- Cost impact: Calculate cost delta from drift (instance type changes, storage modifications)
Generate remediation plan:
remediation_plan:
strategy: semi-automated
steps:
- action: revert
resource: aws_security_group.web
reason: Unauthorized ingress rule added (port 22 from 0.0.0.0/0)
severity: high
method: terraform apply
approval: required
- action: accept
resource: aws_instance.app
reason: Instance type upgraded via console (approved change ticket CHG-123)
severity: low
method: terraform import + update code
approval: auto
- action: ignore
resource: aws_s3_bucket.logs
reason: Tags modified by automation (exemption EXEMPT-456)
severity: low
method: add lifecycle ignore_changes
approval: auto
estimated_duration: 15min
rollback_plan: "terraform state backup + manual revert if apply fails"
Automated remediation execution (if policy allows):
- Pre-flight checks: Verify no active operations, backup state file
- Execute remediation: Apply IaC changes with
--auto-approve (if fully-automated) or prompt for approval
- Validation: Run post-remediation drift scan to confirm drift resolved
- Logging: Record remediation action, operator, timestamp, result in audit log
Drift trend analysis:
- Track drift frequency over time (daily, weekly, monthly)
- Identify drift-prone resources or teams
- Correlate drift with incidents or change tickets
- Generate compliance dashboard showing drift % by severity
Notification delivery:
- Slack: Post drift summary to #infrastructure-alerts with severity emoji
- Email: Send detailed drift report to platform team with remediation plan
- Webhook: POST drift JSON to SIEM or compliance platform
Token budget: ≤6k (multi-stack scan, impact analysis, remediation plan, notifications)
Authoritative sources used:
Decision Rules
When to revert drift vs accept drift:
- Revert if: Security resource modified, no change ticket, compliance violation, unauthorized operator
- Accept if: Change ticket approved, manual fix during incident, IaC code out of date
- Ignore if: Exemption granted, resource lifecycle managed externally, tags/metadata only
Remediation approval thresholds:
- Auto-remediate: Low severity, pre-approved resource types, non-production environments
- Require approval: High/medium severity, production resources, security/network changes
- Manual only: Critical infrastructure, multi-region resources, shared services
Escalation triggers:
- Drift affects >10 resources: Escalate to platform lead
- Drift unresolved >24h: Create incident ticket
- Repeated drift on same resource >3x: Investigate root cause
Abort conditions:
- State file corrupted during remediation: Halt, restore backup, alert on-call
- Cloud provider API errors during apply: Retry with exponential backoff, max 3 attempts
- Dependency conflict detected: Pause remediation, request manual review
Output Contract
Required fields:
interface DriftDetectionOutput {
timestamp: string; // ISO-8601, NOW_ET
tool: "terraform" | "cloudformation" | "pulumi" | "driftctl";
scope: string; // stack/workspace name or "all"
drift_detected: boolean;
drifted_resources: number;
resources: DriftedResource[];
severity_summary: {
high: number;
medium: number;
low: number;
};
remediation_plan?: RemediationPlan;
compliance_impact?: string[]; // Array of violated controls
trend?: {
drift_frequency: string; // "increasing" | "stable" | "decreasing"
most_drifted_resources: string[];
};
audit_log_id?: string; // Reference to remediation execution log
}
interface DriftedResource {
id: string; // Resource identifier
type: string; // Resource type (aws_security_group, etc.)
change_type: "added" | "modified" | "deleted";
severity: "high" | "medium" | "low";
changed_attributes: {
attribute: string;
before: any;
after: any;
}[];
recommended_action: "revert" | "accept" | "ignore";
}
interface RemediationPlan {
strategy: "manual" | "semi-automated" | "fully-automated";
steps: RemediationStep[];
estimated_duration: string;
rollback_plan: string;
}
interface RemediationStep {
action: "revert" | "accept" | "ignore";
resource: string;
reason: string;
severity: "high" | "medium" | "low";
method: string; // terraform apply, import, etc.
approval: "required" | "auto";
}
Example output: See /skills/devops-drift-detector/examples/drift-detection-example.txt
Examples
# Terraform drift detection with semi-automated remediation
input:
tool: terraform
workspace: prod-webapp
remediation_policy: semi-automated
output:
timestamp: "2025-10-25T21:30:36-04:00"
tool: terraform
scope: prod-webapp
drift_detected: true
drifted_resources: 2
resources:
- id: aws_security_group.web
type: aws_security_group
change_type: modified
severity: high
changed_attributes:
- attribute: ingress
before: [{cidr: "10.0.0.0/8", port: 443}]
after: [{cidr: "0.0.0.0/0", port: 22}]
recommended_action: revert
severity_summary: {high: 1, medium: 0, low: 1}
remediation_plan:
strategy: semi-automated
steps:
- action: revert
resource: aws_security_group.web
approval: required
Quality Gates
Token budgets enforced:
- T1 ≤ 2k tokens: Single-stack drift scan with basic remediation guidance
- T2 ≤ 6k tokens: Multi-stack analysis, impact assessment, remediation execution, trend reporting
- T3 not implemented (skill targets T2 complexity)
Safety checks:
Auditability:
- All drift detections logged with timestamp, operator, scope
- Remediation actions recorded with before/after state snapshots
- Compliance violations mapped to controls with evidence trail
Determinism:
- Same state file + same cloud state = same drift report
- Drift severity calculated consistently using predefined rules
- Remediation plan generation follows policy-as-code rules
Resources
Terraform Drift Detection:
Pulumi Drift Detection:
AWS CloudFormation Drift:
driftctl:
Drift Management Best Practices:
Resource files:
/skills/devops-drift-detector/resources/drift-detection-config.yaml - Sample drift detection configuration
/skills/devops-drift-detector/resources/remediation-workflow.yaml - Remediation workflow template
/skills/devops-drift-detector/resources/compliance-mapping.json - Drift to compliance control mapping
1---2name: infrastructure-drift-detection-and-remediation3description: Detect and remediate infrastructure drift between IaC definitions and live state with continuous monitoring and automated remediation.4license: Apache-2.05---67## Purpose & When-To-Use89**Trigger this skill when:**1011* Manual infrastructure changes detected outside IaC workflow12* Compliance violation suspected from untracked modifications13* Scheduled drift scan required (daily, weekly, pre-deployment)14* IaC state reconciliation needed after provider API changes15* Post-incident analysis to identify unauthorized changes16* Continuous compliance monitoring for regulated environments1718**Outputs:** Drift detection report with changed resources, remediation plan with impact analysis, compliance status, optional auto-remediation execution with audit trail.1920## Pre-Checks2122**Time normalization:**23* Compute `NOW_ET` = 2025-10-25T21:30:36-04:00 (NIST/time.gov semantics, America/New_York, ISO-8601)2425**Input validation:**26* [ ] IaC tool type specified and supported (Terraform, CloudFormation, Pulumi, driftctl)27* [ ] State file location accessible or cloud credentials valid28* [ ] Drift detection scope defined (full stack, specific resources, tag-based)29* [ ] Remediation policy clear (manual-only, semi-auto, full-auto)30* [ ] Notification channels configured if automated alerts required3132**Source freshness:**33* [ ] IaC tool documentation current (accessed NOW_ET)34* [ ] Cloud provider drift detection APIs available35* [ ] State file not corrupted and version compatible3637**Abort conditions:**38* Missing cloud credentials for state comparison39* IaC tool version incompatibility40* State file locked by active operation4142## Procedure4344### T1: Fast Path (≤2k tokens) - Quick Drift Scan4546**Scope:** Single stack/workspace, on-demand drift check, common 80% case47481. **Identify IaC tool and load state:**49 * Terraform: `terraform plan -refresh-only -detailed-exitcode` to preview state refresh50 * CloudFormation: `aws cloudformation detect-stack-drift --stack-name <name>` then poll `DescribeStackDriftDetectionStatus`51 * Pulumi: `pulumi refresh --preview-only` to compare desired vs actual52 * driftctl: `driftctl scan --from tfstate://<path> --to <provider>` for multi-resource scan53542. **Parse drift detection results:**55 * Extract changed resources (added, modified, deleted, drifted)56 * Identify changed attributes and values (before → after)57 * Calculate drift severity: high (security/network), medium (config), low (tags/metadata)58593. **Generate quick remediation guidance:**60 * **Accept drift:** Update IaC to match live state if change is intentional61 * **Revert drift:** Apply IaC to overwrite live state if change is unauthorized62 * **Ignore drift:** Tag resource as exception if drift is acceptable63644. **Output drift summary:**65 ```json66 {67 "drift_detected": true,68 "tool": "terraform",69 "timestamp": "NOW_ET",70 "drifted_resources": 3,71 "severity": "high",72 "resources": [73 {"id": "aws_security_group.web", "change": "ingress_rules_modified", "severity": "high"}74 ],75 "recommended_action": "revert"76 }77 ```7879**Token budget: ≤2k** (state comparison, basic drift report)8081### T2: Extended Path (≤6k tokens) - Comprehensive Drift Analysis + Remediation8283**Scope:** Multiple stacks, scheduled detection, compliance reporting, semi-automated remediation84851. **T1 fast path** (all steps above)86872. **Multi-stack drift detection:**88 * Terraform Cloud: Enable continuous drift detection via workspace settings; configure schedule (daily/weekly)89 * Source: [Terraform Cloud Drift Detection](https://developer.hashicorp.com/terraform/tutorials/cloud/drift-and-policy) (accessed 2025-10-25T21:30:36-04:00)90 * Pulumi Cloud: Setup Deployments with drift schedules; configure auto-remediation policy91 * Source: [Pulumi Drift Detection](https://www.pulumi.com/docs/pulumi-cloud/deployments/drift/) (accessed 2025-10-25T21:30:36-04:00)92 * CloudFormation: Use AWS Config rule `cloudformation-stack-drift-detection-check` for automated compliance93 * Source: [AWS CloudFormation Drift Detection](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html) (accessed 2025-10-25T21:30:36-04:00)94 * driftctl: Run `driftctl scan --filter "Type=='aws_s3_bucket'"` for resource-type scoping95 * Source: [driftctl GitHub](https://github.com/snyk/driftctl) (accessed 2025-10-25T21:30:36-04:00)96973. **Drift impact analysis:**98 * **Security impact:** Check if drift affects IAM, security groups, encryption, network ACLs99 * **Compliance impact:** Map drifted resources to compliance controls (NIST, FedRAMP, PCI-DSS)100 * **Dependency impact:** Identify downstream resources affected by drift101 * **Cost impact:** Calculate cost delta from drift (instance type changes, storage modifications)1021034. **Generate remediation plan:**104 ```yaml105 remediation_plan:106 strategy: semi-automated107 steps:108 - action: revert109 resource: aws_security_group.web110 reason: Unauthorized ingress rule added (port 22 from 0.0.0.0/0)111 severity: high112 method: terraform apply113 approval: required114 - action: accept115 resource: aws_instance.app116 reason: Instance type upgraded via console (approved change ticket CHG-123)117 severity: low118 method: terraform import + update code119 approval: auto120 - action: ignore121 resource: aws_s3_bucket.logs122 reason: Tags modified by automation (exemption EXEMPT-456)123 severity: low124 method: add lifecycle ignore_changes125 approval: auto126 estimated_duration: 15min127 rollback_plan: "terraform state backup + manual revert if apply fails"128 ```1291305. **Automated remediation execution (if policy allows):**131 * **Pre-flight checks:** Verify no active operations, backup state file132 * **Execute remediation:** Apply IaC changes with `--auto-approve` (if fully-automated) or prompt for approval133 * **Validation:** Run post-remediation drift scan to confirm drift resolved134 * **Logging:** Record remediation action, operator, timestamp, result in audit log1351366. **Drift trend analysis:**137 * Track drift frequency over time (daily, weekly, monthly)138 * Identify drift-prone resources or teams139 * Correlate drift with incidents or change tickets140 * Generate compliance dashboard showing drift % by severity1411427. **Notification delivery:**143 * Slack: Post drift summary to #infrastructure-alerts with severity emoji144 * Email: Send detailed drift report to platform team with remediation plan145 * Webhook: POST drift JSON to SIEM or compliance platform146147**Token budget: ≤6k** (multi-stack scan, impact analysis, remediation plan, notifications)148149**Authoritative sources used:**150* [Terraform Cloud Drift Detection Tutorial](https://developer.hashicorp.com/terraform/tutorials/cloud/drift-and-policy) - HashiCorp official docs (accessed 2025-10-25T21:30:36-04:00)151* [Pulumi Drift Detection Docs](https://www.pulumi.com/docs/pulumi-cloud/deployments/drift/) - Pulumi official docs (accessed 2025-10-25T21:30:36-04:00)152* [AWS CloudFormation Drift Detection](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html) - AWS official docs (accessed 2025-10-25T21:30:36-04:00)153* [driftctl GitHub Repository](https://github.com/snyk/driftctl) - Snyk/driftctl open source tool (accessed 2025-10-25T21:30:36-04:00)154* [Spacelift Drift Detection Guide](https://spacelift.io/blog/drift-detection) - Infrastructure drift best practices (accessed 2025-10-25T21:30:36-04:00)155156## Decision Rules157158**When to revert drift vs accept drift:**159* **Revert** if: Security resource modified, no change ticket, compliance violation, unauthorized operator160* **Accept** if: Change ticket approved, manual fix during incident, IaC code out of date161* **Ignore** if: Exemption granted, resource lifecycle managed externally, tags/metadata only162163**Remediation approval thresholds:**164* **Auto-remediate:** Low severity, pre-approved resource types, non-production environments165* **Require approval:** High/medium severity, production resources, security/network changes166* **Manual only:** Critical infrastructure, multi-region resources, shared services167168**Escalation triggers:**169* Drift affects >10 resources: Escalate to platform lead170* Drift unresolved >24h: Create incident ticket171* Repeated drift on same resource >3x: Investigate root cause172173**Abort conditions:**174* State file corrupted during remediation: Halt, restore backup, alert on-call175* Cloud provider API errors during apply: Retry with exponential backoff, max 3 attempts176* Dependency conflict detected: Pause remediation, request manual review177178## Output Contract179180**Required fields:**181182```typescript183interface DriftDetectionOutput {184 timestamp: string; // ISO-8601, NOW_ET185 tool: "terraform" | "cloudformation" | "pulumi" | "driftctl";186 scope: string; // stack/workspace name or "all"187 drift_detected: boolean;188 drifted_resources: number;189 resources: DriftedResource[];190 severity_summary: {191 high: number;192 medium: number;193 low: number;194 };195 remediation_plan?: RemediationPlan;196 compliance_impact?: string[]; // Array of violated controls197 trend?: {198 drift_frequency: string; // "increasing" | "stable" | "decreasing"199 most_drifted_resources: string[];200 };201 audit_log_id?: string; // Reference to remediation execution log202}203204interface DriftedResource {205 id: string; // Resource identifier206 type: string; // Resource type (aws_security_group, etc.)207 change_type: "added" | "modified" | "deleted";208 severity: "high" | "medium" | "low";209 changed_attributes: {210 attribute: string;211 before: any;212 after: any;213 }[];214 recommended_action: "revert" | "accept" | "ignore";215}216217interface RemediationPlan {218 strategy: "manual" | "semi-automated" | "fully-automated";219 steps: RemediationStep[];220 estimated_duration: string;221 rollback_plan: string;222}223224interface RemediationStep {225 action: "revert" | "accept" | "ignore";226 resource: string;227 reason: string;228 severity: "high" | "medium" | "low";229 method: string; // terraform apply, import, etc.230 approval: "required" | "auto";231}232```233234**Example output:** See `/skills/devops-drift-detector/examples/drift-detection-example.txt`235236## Examples237238```yaml239# Terraform drift detection with semi-automated remediation240input:241 tool: terraform242 workspace: prod-webapp243 remediation_policy: semi-automated244245output:246 timestamp: "2025-10-25T21:30:36-04:00"247 tool: terraform248 scope: prod-webapp249 drift_detected: true250 drifted_resources: 2251 resources:252 - id: aws_security_group.web253 type: aws_security_group254 change_type: modified255 severity: high256 changed_attributes:257 - attribute: ingress258 before: [{cidr: "10.0.0.0/8", port: 443}]259 after: [{cidr: "0.0.0.0/0", port: 22}]260 recommended_action: revert261 severity_summary: {high: 1, medium: 0, low: 1}262 remediation_plan:263 strategy: semi-automated264 steps:265 - action: revert266 resource: aws_security_group.web267 approval: required268```269270## Quality Gates271272**Token budgets enforced:**273* T1 ≤ 2k tokens: Single-stack drift scan with basic remediation guidance274* T2 ≤ 6k tokens: Multi-stack analysis, impact assessment, remediation execution, trend reporting275* T3 not implemented (skill targets T2 complexity)276277**Safety checks:**278* [ ] State file backups created before remediation279* [ ] Approval required for high-severity changes280* [ ] Rollback plan documented and validated281* [ ] Audit log captured with operator, timestamp, action282283**Auditability:**284* All drift detections logged with timestamp, operator, scope285* Remediation actions recorded with before/after state snapshots286* Compliance violations mapped to controls with evidence trail287288**Determinism:**289* Same state file + same cloud state = same drift report290* Drift severity calculated consistently using predefined rules291* Remediation plan generation follows policy-as-code rules292293## Resources294295**Terraform Drift Detection:**296* [Terraform Cloud Drift Detection Tutorial](https://developer.hashicorp.com/terraform/tutorials/cloud/drift-and-policy)297* [Spacelift Terraform Drift Guide](https://spacelift.io/blog/terraform-drift-detection)298299**Pulumi Drift Detection:**300* [Pulumi Drift Detection Docs](https://www.pulumi.com/docs/pulumi-cloud/deployments/drift/)301* [Pulumi Drift Announcement Blog](https://www.pulumi.com/blog/drift-detection/)302303**AWS CloudFormation Drift:**304* [CloudFormation Drift Detection User Guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html)305* [Automated CloudFormation Drift Remediation](https://aws.amazon.com/blogs/mt/implement-automatic-drift-remediation-for-aws-cloudformation-using-amazon-cloudwatch-and-aws-lambda/)306307**driftctl:**308* [driftctl GitHub Repository](https://github.com/snyk/driftctl)309* [Snyk Infrastructure Drift Blog](https://snyk.io/blog/infrastructure-drift-detection-mitigation/)310311**Drift Management Best Practices:**312* [Spacelift Drift Management Guide](https://spacelift.io/blog/drift-management)313* [Policy-as-Code for Drift Detection](https://devops.com/cloud-drift-detection-with-policy-as-code/)314315**Resource files:**316* `/skills/devops-drift-detector/resources/drift-detection-config.yaml` - Sample drift detection configuration317* `/skills/devops-drift-detector/resources/remediation-workflow.yaml` - Remediation workflow template318* `/skills/devops-drift-detector/resources/compliance-mapping.json` - Drift to compliance control mapping