We are designing a drift detection pipeline for Infrastructure as Code (IaC).
The goal: detect changes made to live infrastructure that are not reflected in the IaC (i.e., drift).
Steps:
- Sources: Where do we get the current state of infrastructure?
- For cloud: cloud provider APIs (e.g., AWS Config, Azure Resource Graph, GCP Cloud Asset Inventory)
- For on-prem: configuration management databases (CMDB) or direct API calls to systems.
- Suppression rules: How to ignore expected or benign drifts?
- We may have resources that are allowed to drift (e.g., tags that are updated by other systems) or changes that are temporary.
- Rules can be based on resource type, attribute, or even change history.
- Incident flow: What happens when drift is detected?
- Alerting, ticket creation, automated remediation (if safe), or manual review.
We'll design a modular pipeline:
Step 1: Data Collection
- Pull the current state from the infrastructure (live state) and the desired state from the IaC (e.g., Terraform state, CloudFormation template, etc.)
- Normalize both to a common format (e.g., a standardized resource representation).
Step 2: Comparison
- Compare the live state with the desired state (from IaC) for each resource.
- Output: a list of drifts (resource, attribute, live value, desired value).
Step 3: Suppression
- Apply suppression rules to filter out known/acceptable drifts.
- Rules can be defined in a configuration file or database.
Step 4: Incident Handling
- For remaining drifts, trigger an incident:
- Create an alert (e.g., send to Slack, PagerDuty, etc.)
- Create a ticket (e.g., Jira, ServiceNow)
- Optionally, trigger an automated remediation (e.g., run terraform apply to reconcile, but note: this might be dangerous if the drift is due to legitimate manual change that shouldn't be overwritten).
Let's break down each part:
-
Sources:
Live State Sources:
- Cloud: use cloud-specific APIs to get resource properties. We might use a tool like
terraform state pull for Terraform managed resources, but note: that only shows the last known state from the state file, not necessarily the live state.
Instead, we should query the cloud provider directly for the current state of resources. Alternatively, use a tool that does this, like infracost (which can fetch live state) or aws-sdk for AWS.
- For non-cloud: use CMDB or direct API (e.g., vSphere, Kubernetes API, etc.)
Desired State Sources:
- IaC tools: Terraform state files, CloudFormation templates, Ansible playbooks, etc.
- We need to parse these and represent the desired configuration.
We might have multiple sources for live state and desired state. We need to map them by resource identifier (e.g., AWS ARN, Azure resource ID, etc.)
-
Suppression Rules:
Example rules:
- Ignore drift on resource type
aws_s3_bucket for attribute tags (because tags are often updated by other systems).
- Ignore drift on resource with ID
i-123456 for attribute public_ip (if it's a temporary change).
- Ignore drift if the change was made by a specific automation (we might need to integrate with cloudtrail/audit logs? but that's more advanced).
Rule format:
{
"resource_type": "aws_s3_bucket",
"attribute": "tags",
"action": "suppress"
}
We can have more complex rules (e.g., regex on resource ID, multiple attributes, etc.)
-
Incident Flow:
We can have different severity levels based on:
- Resource criticality (e.g., production database vs. dev environment)
- Type of attribute changed (e.g., security groups vs. tags)
Steps:
- Classify the drift (severity, category)
- If severity is high and automated remediation is enabled and safe, then:
- Run a remediation playbook (e.g.,
terraform apply to update the resource to desired state, but note: this might break things if the drift is intentional and the IaC is out of date).
- Alternatively, update the IaC to match the live state? That's a different approach (reverse drift). But our goal is to enforce IaC, so we want to correct live state to match IaC.
However, note: sometimes the live state change is legitimate and the IaC is outdated. We might need a process to update IaC.
So, the incident flow should also include a step to review and update IaC if the change is approved.
Proposed flow:
- Detect drift.
- Suppress known acceptable drifts.
- For remaining:
a. Create an incident ticket with details (resource, attribute, live vs desired).
b. Notify the team.
c. Wait for human approval?
d. If approved and automated remediation is configured and safe, then run remediation (which will update live state to match IaC).
e. If the change is actually desired, then update the IaC (and then re-run the pipeline to confirm no drift?).
But note: updating IaC might be a separate process. We might not want to automatically update IaC because that could be a breaking change.
So, let's separate:
Option 1: Automated remediation (revert live state to IaC) - only if we are sure the IaC is the source of truth and the drift is unauthorized.
Option 2: Update IaC to match live state (if the change is approved and we want to adopt it).
We might have both options as separate playbooks. The incident ticket should specify which action to take.
Given the complexity, we might start with just alerting and then manually decide.
-
Pipeline Design:
We can build this as a set of microservices or a single application with modules.
Components:
- Collector: Fetches live state and desired state, normalizes.
- Comparator: Compares and produces drift list.
- Suppressor: Applies suppression rules.
- Dispatcher: For non-suppressed drifts, dispatches incidents (alerts, tickets) and optionally triggers remediation.
We can run this periodically (e.g., every hour) or on-demand (e.g., when a change is detected via webhook from cloud provider).
-
Implementation considerations:
-
State normalization: We need to convert both live and desired states into a common format. We can define a schema (e.g., JSON) with fields: resource_type, resource_id, attributes (key-value).
-
Mapping: How do we match a live resource to a desired one? We need a unique identifier. In Terraform, we have the resource address and the ID (from the state). But note: the same resource might be represented differently in different IaC tools.
-
Handling deleted resources: If a resource exists in IaC but not in live state, that's also drift (missing resource). Similarly, if a resource exists in live state but not in IaC, that's also drift (unmanaged resource). We might want to handle both.
-
Performance: For large infrastructures, we need to be efficient in collecting and comparing.
-
Example workflow:
Step 1: Collect live state from AWS (using AWS Config) for all resources in a given account and region.
Step 2: Collect desired state from Terraform state file (which might be stored in S3 or locally).
Step 3: For each resource in the desired state, find the corresponding live resource by ID (or by tags/name if ID is not available?).
Step 4: Compare attributes.
Step 5: Apply suppression rules.
Step 6: For remaining drifts, create a Jira ticket and send a Slack alert.
-
Advanced:
- We might want to track drift over time and see if it's persistent or temporary.
- We might want to ignore drifts that are corrected within a certain time window (e.g., a temporary scaling event).
-
Tools:
Existing tools that do something similar:
- AWS Config: can detect configuration changes and compliance, but not necessarily against IaC.
- Terraform:
terraform plan will show drifts if you run it against the live state? Actually, Terraform refreshes the state and then compares with the configuration. But that only works for resources managed by Terraform and requires the state file to be up to date. Also, it doesn't compare against the desired state if the configuration has changed? Actually, terraform plan compares the current state (which is updated from live) with the configuration. But if we have updated the configuration (IaC) and the live state is different, then it will show changes. However, if we have multiple sources of truth (multiple IaC tools) then we need a more general solution.
We might build on top of Terraform for Terraform-managed resources, but we need a generic solution for any IaC.
-
Generic Approach:
We can define a desired state in a generic format (like Open Policy Agent's input format, or a custom JSON). Then, we fetch live state in that same format.
Example desired state (from Terraform) for an AWS instance:
{
"resource_type": "aws_instance",
"id": "i-1234567890abcdef0",
"attributes": {
"ami": "ami-0c55b159cbfafe1f0",
"instance_type": "t2.micro",
"tags": {
"Name": "my-instance"
}
}
}
Live state (from AWS) for the same instance:
{
"resource_type": "aws_instance",
"id": "i-1234567890abcdef0",
"attributes": {
"ami": "ami-0c55b159cbfafe1f0",
"instance_type": "t2.micro",
"tags": {
"Name": "my-instance",
"Environment": "Production"
}
}
}
Drift: the live state has an extra tag "Environment".
-
Implementation Steps:
a. Define the common schema for resource representation.
b. Build adapters for each IaC tool to convert their desired state to the common schema.
- Terraform: use
terraform state pull and parse the state file (or use the Terraform API if available).
- CloudFormation: parse the template and the current stack resources (but note: CloudFormation doesn't store the desired state in the same way; we have the template and the current stack resources which are the live state? Actually, the stack resources are managed by CloudFormation, so the template is the desired state and the stack resources are the live state. So we can compare the template with the stack resources.)
c. Build adapters for each cloud/on-prem to fetch live state in the common schema.
d. Build the comparator:
for each desired resource, find the live resource by ID.
if found, compare attributes (deep diff).
if not found, then it's a missing resource (or if live resource not found in desired, then unmanaged).
e. Suppression rules:
We can define rules that match on resource_type, resource_id (or pattern), attribute (or attribute path), and then suppress if the difference matches a condition (e.g., value in a list, regex, etc.)
f. Incident:
For each non-suppressed drift, create an incident object with:
- resource_type, resource_id, attribute, live_value, desired_value, severity (maybe based on attribute).
Then, based on configuration, send alerts and create tickets.
-
Example Rule Configuration:
suppression_rules:
-
id: "ignore-s3-tags"
description: "Ignore changes to S3 bucket tags"
resource_type: "aws_s3_bucket"
attribute: "tags"
effect: "suppress"
-
id: "ignore-ec2-public-ip"
description: "Ignore public IP changes for EC2 instances with specific tag"
resource_type: "aws_instance"
attribute: "public_ip"
condition:
tags:
key: "environment"
value: "dev"
effect: "suppress"
-
Scalability:
We might have thousands of resources. We need to:
- Collect live state: use cloud provider's bulk APIs (e.g., AWS Config can query all resources).
- Desired state: if from Terraform, we might have multiple state files. We can merge them.
We can also parallelize the comparison.
-
Security:
The pipeline will need credentials to access cloud accounts and IaC state stores. We must secure these.
-
Deployment:
We can run this as a scheduled job (e.g., AWS Batch, Kubernetes CronJob) or as a serverless function (AWS Lambda, but might time out for large infrastructures).
-
Extensibility:
We should design so that adding a new IaC tool or cloud provider is easy (just write an adapter).
-
Monitoring:
We should monitor the pipeline itself (collector success, comparison time, number of drifts, etc.)
-
Example Tech Stack:
- Language: Go or Python (for cloud SDKs and flexibility)
- Storage: For suppression rules and configuration, use a database or config files (in S3, etc.)
- Alerting: integrate with Slack, PagerDuty, etc.
- Ticketing: Jira, ServiceNow APIs.
Given the complexity, we might start with a specific use case (e.g., AWS + Terraform) and then generalize.
Let's outline the code structure:
project/
collect/
aws_collector.py # fetches live state from AWS and converts to common schema
terraform_collector.py # reads Terraform state and converts to common schema
compare/
comparator.py # compares two lists of resources (desired and live) and produces drift list
suppress/
suppressor.py # applies suppression rules to drift list
incident/
dispatcher.py # sends alerts, creates tickets, triggers remediation
common/
schema.py # defines the resource schema
models.py # data classes for Resource, Drift, etc.
config/
rules.yaml # suppression rules
settings.py # configuration for the pipeline (cloud accounts, Terraform state location, etc.)
main.py # orchestrates the steps
-
Example main flow:
desired_resources = terraform_collector.collect(terraform_state_location)
live_resources = aws_collector.collect(aws_account, region)
drifts = comparator.compare(desired_resources, live_resources)
filtered_drifts = suppressor.suppress(drifts, suppression_rules)
if filtered_drifts:
dispatcher.dispatch(filtered_drifts)
-
Remediation:
We might have a separate remediation module that, given a drift, can:
- For missing resource: create it (if we have the desired state) or alert.
- For unmanaged resource: delete it? (dangerous) or alert.
- For attribute drift: update the live resource to match desired.
But note: we might not have permission to update live resources, or the update might be complex (e.g., replacing an EC2 instance). So remediation might be tool-specific.
We can use the IaC tool to apply the change (e.g., run terraform apply for the specific resource). But that requires that the desired state is in the IaC and that the IaC tool can handle the change.
Alternatively, we can use cloud provider APIs to update the resource directly (but then we are not updating the IaC, so the next run will detect drift again).
So, the proper way is to update the IaC if the change is desired, or update the live state via IaC if the change is not desired.
Given the complexity, we might start without automated remediation and just alert.
-
Conclusion:
This is a high-level design. The implementation details will depend on the specific tools and requirements.
Let's write a sample code for the comparator and suppressor to illustrate:
We assume a resource is represented as:
class Resource:
resource_type: str
resource_id: str
attributes: dict # key-value pairs of attributes
Comparator:
def compare(desired: List[Resource], live: List[Resource]) -> List[Drift]:
# Build a map of live resources by (resource_type, resource_id)
live_map = {(r.resource_type, r.resource_id): r for r in live}
drifts = []
for d in desired:
key = (d.resource_type, d.resource_id)
if key not in live_map:
drifts.append(Drift(d.resource_type, d.resource_id, "resource_missing", None, "resource not found in live"))
else:
l = live_map[key]
for attr, desired_value in d.attributes.items():
if attr not in l.attributes:
drifts.append(Drift(d.resource_type, d.resource_id, attr, None, desired_value))
else:
live_value = l.attributes[attr]
if live_value != desired_value:
drifts.append(Drift(d.resource_type, d.resource_id, attr, live_value, desired_value))
# Also check if live has extra attributes not in desired?
# That might be acceptable if we don't care about extra attributes. But if we want to enforce that live only has the desired attributes, then we would also check for extra attributes.
# Typically, we only compare the attributes that are in the desired state. Extra attributes in live are not considered drift?
# But if we have a desired state that is the complete specification, then extra attributes are drift.
# We'll leave that as a design decision.
# Also, check for unmanaged resources (live resources not in desired)
desired_keys = {(r.resource_type, r.resource_id) for r in desired}
for l in live:
key = (l.resource_type, l.resource_id)
if key not in desired_keys:
drifts.append(Drift(l.resource_type, l.resource_id, "resource_unmanaged", "resource exists in live but not in desired", None))
return drifts
Suppressor:
def suppress(drifts: List[Drift], rules: List[SuppressionRule]) -> List[Drift]:
filtered = []
for drift in drifts:
suppress = False
for rule in rules:
if (rule.resource_type == drift.resource_type and
(rule.attribute is None or rule.attribute == drift.attribute) and
(rule.resource_id is None or re.match(rule.resource_id, drift.resource_id))):
# We can also have condition on drift values? e.g., if attribute is "tags" and we want to ignore a specific tag key?
# For simplicity, let's assume the rule is just on resource_type and attribute and optionally resource_id pattern.
suppress = True
break
if not suppress:
filtered.append(drift)
return filtered
This is a simple suppressor. We might want more complex conditions (like checking the value of the attribute, or multiple attributes). We can extend the rule to have a condition function.
-
Extensions:
-
We might want to ignore drifts that are of a certain severity (e.g., only alert on security-related attributes). So we need to map attributes to severity.
-
We might want to have a whitelist of resource IDs that are allowed to drift (e.g., resources created by other teams).
-
Final Note:
This design is a starting point. In practice, we need to consider:
-
How to handle resources that are not uniquely identified by (resource_type, resource_id)? Some cloud resources might have multiple identifiers. We might need to use a different key.
-
How to handle nested attributes? (e.g., aws_instance.root_block_volume[0].encrypted). We might need to flatten the attributes or use a path.
-
How to handle large state files? We might need to stream or paginate.
But for a proof of concept, the above should work.
Let's write a more detailed example for AWS and Terraform.
AWS live state collector:
We can use AWS Config to get all resources. AWS Config provides a list of configuration items for each resource. We can query for all resources and then convert each ConfigurationItem to our Resource schema.
Alternatively, we can use the AWS Resource Groups Tagging API to get all resources and then describe each one? That might be too many API calls.
AWS Config is better because it already has the configuration of each resource.
Steps for AWS Config:
- Enable AWS Config in the account (if not already).
- Use the `select_resource_config` API to run a query that gets all resources? Or use `list_discovered_resources` and then `get_resource_config_history` for each? That's a lot.
Alternatively, we can use the AWS Config Advanced Query language:
SELECT * WHERE resourceType = 'AWS::EC2::Instance'
But we want all resource types. We can do:
SELECT *
However, that might be too many. We can do:
SELECT resourceType, resourceId, configuration
But note: the configuration is a JSON string. We can parse that.
We'll get:
resourceType: e.g., "AWS::EC2::Instance"
resourceId: e.g., "i-1234567890abcdef0"
configuration: the full configuration of the resource.
We can map:
resource_type: we might want to convert to a shorter form (e.g., "aws_instance" for Terraform). But for now, we can keep the CloudFormation type.
resource_id: use the resourceId.
attributes: the configuration JSON (but we might want to flatten or extract only certain attributes? We can keep the whole configuration as attributes? But then comparison might be too broad. We want to compare only the attributes that are in the IaC.
Alternatively, we can build a mapping from CloudFormation resource types to Terraform resource types and the relevant attributes. But that's a huge mapping.
Another approach: we can use the desired state (from Terraform) to know which attributes we care about. So when comparing, we only compare the attributes that are in the desired state.
So, for live state, we can store the entire configuration (as a dict) and then when comparing, we extract the same attributes as in the desired state.
So, the live resource's attributes will be the entire configuration? But then we are comparing a subset. That's okay.
We can do:
desired_resource.attributes = { "ami": "...", "instance_type": "..." }
live_resource.attributes = { ... entire configuration ... }
Then, when comparing, for each key in desired_resource.attributes, we look in live_resource.attributes.
But note: the live configuration might have nested structures. We need to handle that.
Example: desired attribute might be "root_block_volume.0.encrypted", but in the live configuration, root_block_volume is a list.
We can use a path notation (like jmespath) to extract the value from the live configuration.
So, we need to be able to evaluate a path in the live configuration.
Alternatively, we can flatten the live configuration (convert nested dicts and lists to a flat dictionary with keys like "root_block_volume.0.encrypted"). But that might be complex.
Another idea: use the same representation for both desired and live. For desired, we already have a flat dictionary (Terraform state is flat). For live, we can flatten the configuration.
But note: Terraform state also has nested structures? Actually, the Terraform state file has a nested structure, but when we parse it, we get a flat attribute map? Let's check:
In Terraform state, for an aws_instance, the attributes are:
"attributes": {
"id": "i-123456",
"ami": "...",
"instance_type": "...",
"root_block_volume": [
{
"encrypted": true,
...
}
]
}
So it's nested. But when we do `terraform state pull`, we get a JSON that has a nested structure.
We need a way to compare nested structures. We can do a deep diff, but then we have to decide what to report.
Alternatively, we can convert both desired and live to a flat representation using a canonical path (like dot notation or jmespath). Then we compare each key.
Let's define:
For a resource, we have a dictionary of attributes. The keys are dot-notation paths for nested structures.
Example:
Desired:
{
"ami": "ami-123",
"instance_type": "t2.micro",
"root_block_volume.0.encrypted": true
}
Live (from AWS Config) might have:
{
"ImageId": "ami-123",
"InstanceType": "t2.micro",
"BlockDeviceMappings": [
{
"Ebs": {
"Encrypted": true
}
}
]
}
We need to map the desired attribute paths to the live configuration. That mapping is tool-specific.
For Terraform, the attribute names are the same as in the AWS API? Not exactly. Terraform uses its own attribute names (like `root_block_volume` vs AWS `BlockDeviceMappings`).
So we need a mapping from Terraform attribute names to AWS API field names.
This is getting very complex.
Given the complexity, we might limit the scope to:
Option 1: Only compare the attributes that are present in the desired state and that have the same name in the live state (after normalization). But that won't work for different naming.
Option 2: Use the cloud provider's API to get the resource in the same shape as the IaC tool expects? That's not straightforward.
Alternatively, we can use the IaC tool's own refresh and plan to detect drift. For Terraform, we can run `terraform plan` and parse the output. That will give us exactly what Terraform thinks is different between the state (which is updated from live) and the configuration (desired). But note:
- Terraform state is updated by `terraform refresh` (which is done automatically in plan). So the state file becomes the live state? Not exactly, because the state file might not have all attributes that the configuration has? Actually, the state file has the attributes that Terraform knows about. And the configuration has the desired attributes. So `terraform plan` will show drifts for attributes that are in the configuration.
But what if we have multiple IaC tools? We want a unified view.
Given the time, let's assume we are only supporting Terraform and AWS, and we use the Terraform state as the desired state and AWS Config as the live state. Then we need a mapping from Terraform attribute names to AWS Config attribute names.
However, note: Terraform state attributes are in the form that Terraform uses, which might be different from the AWS API. For example, in Terraform for `aws_instance`, the attribute for the AMI is `ami`, but in AWS Config, it's `ImageId`.
We can create a mapping for each resource type. But that's a lot of work.
Alternatively, we can use the Terraform provider's schema to map from Terraform attribute names to AWS API field names? That's too heavy.
Given the complexity, maybe we should use Terraform's own drift detection for Terraform-managed resources. But then we are tied to Terraform.
Since the requirement is for IaC in general, we need a generic solution.
Let's step back:
We have a desired state in some form (from IaC) and a live state in another form (from cloud provider). We want to compare them.
We need a mapping between the two. We can define that the desired state uses a canonical set of attribute names (maybe the cloud provider's API names) and then the IaC tool's desired state must be transformed to that canonical form.
Similarly, the live state from the cloud provider is already in the canonical form (if we use the cloud provider's API). Then we can compare.
So, we can require that the IaC tool's desired state is expressed in the cloud provider's API terms. For example, for AWS, we use the AWS CloudFormation property names (or the AWS API parameter names). Then, for Terraform, we would have to transform the Terraform state (which uses Terraform attribute names) to the AWS API names.
But that transformation is exactly what the Terraform provider does. We might be able to use the provider's schema to transform.
Alternatively, we can use the cloud provider's API to get the live state and then compare with the desired state that is written in the same terms as the cloud provider's API. That means we have to write the IaC in terms of the cloud provider's API? That's not user-friendly.
Given the difficulty, perhaps we should focus on a specific IaC tool and cloud provider and use the tool's own drift detection, and then just add suppression and incident flow on top.
For example, for Terraform and AWS:
Step 1: Run `terraform plan -detailed-exitcode` (which returns an exit code of 2 if there are changes). But we want the details.
Step 2: Parse the Terraform plan output (or use the Terraform JSON output) to get the list of changes.
Then, we can apply suppression rules on those changes (by resource type, attribute, etc.)
Then, incident.
This way, we leverage Terraform's own understanding of what is a drift.
But note: Terraform only knows about resources it manages. If there are unmanaged resources, Terraform won't know. So we still need a way to detect unmanaged resources.
We can use AWS Config to find all resources and then subtract the ones managed by Terraform (from the state file). That gives unmanaged resources.
So, for Terraform-managed resources, we use Terraform's drift detection (which compares the state (refreshed from live) with the configuration). For unmanaged resources, we just alert that they exist.
This seems more feasible.
Revised design for Terraform + AWS:
Part 1: Managed resources (by Terraform)
- We have a Terraform state file (or multiple). We run `terraform plan` (with refresh) for each state (or workspace) and parse the JSON output.
- The JSON output has a section `resource_changes` which lists the changes (actions: update, delete, create). But note: `terraform plan` only shows changes that would be made to match the configuration. So if a resource is changed manually, it will show as an update.
- We can extract:
resource_type, resource_name (from Terraform), resource_id (from state), change.attribute? Actually, the change might be for the entire resource or specific attributes.
- The Terraform plan output does not always list every attribute that changed. It might say "Update resource" without listing attributes. We can look at the `change.actions` and then the `change.before` and `change.after` to see the diff.
- We can generate a list of drifts for each attribute that is different.
Part 2: Unmanaged resources
- We use AWS Config to list all resources of types that we care about (or all). Then we compare the list of resource IDs with the ones in the Terraform state. Any resource in AWS Config that is not in the Terraform state is unmanaged.
- We might also want to check for resources in the Terraform state that are not in AWS? That would be missing resources (already covered by Terraform plan? Terraform plan would try to create them, so that's a drift too? Actually, if a resource is in the state but not in AWS, Terraform plan would show it as create. So we don't need to check separately for missing resources if we use Terraform plan.
So, we can do:
Step 1: For each Terraform workspace/state, run `terraform plan -out=plan.out` and then `terraform show -json plan.out` to get the JSON. Then parse the resource changes.
Step 2: For unmanaged resources, we run an AWS Config query (or use AWS Resource Groups Tagging API) to get all resources and then subtract the resources in the Terraform state (by resource ID and type?).
Step 3: Combine the two lists (managed drifts and unmanaged resources) and then apply suppression.
This approach:
- Uses Terraform for managed resources (so we don't have to map attribute names).
- Uses AWS Config for unmanaged resources (so we get all resources).
But note: AWS Config might not have every resource (if not enabled for that resource type). We can use AWS Resource Groups Tagging API as a fallback? But that only gives resources with tags.
Alternatively, we can use the AWS CLI `aws resourcegroupstaggingapi get-resources` to get all resources that have tags, and then for each, describe it to get the full configuration? That's heavy.
Given the complexity, we might start with just Terraform-managed resources and then add unmanaged resource detection later.
Conclusion:
For a generic solution, we need to handle multiple IaC tools and cloud providers, which is very complex due to the mapping problem.
Given the time, I propose:
Phase 1: Build a drift detection for Terraform on AWS that uses Terraform's own plan output for managed resources and AWS Config for unmanaged resources (for resource types that Terraform doesn't manage). And then apply suppression and incident.
Phase 2: Extend to other IaC tools and cloud providers by building adapters that convert their desired state to a common schema and live state to the same schema, but we might need to write mappings for each resource type.
Given the scope, we might start with Phase 1.
Let's design for Phase 1:
Steps:
1. For each Terraform state (we assume we know the state location, e.g., S3), run:
terraform init (if needed) and terraform plan -refresh-only? Actually, we want to see what changes would be made to match the configuration. So we run `terraform plan` and then parse the output.
2. Parse the Terraform plan JSON:
{
"resource_changes": [
{
"address": "aws_instance.example",
"type": "aws_instance",
"name": "example",
"provider_name": "registry.terraform.io/hashicorp/aws",
"change": {
"actions": ["update"],
"before": { ... },
"after": { ... },
"after_unknown": { ... }
}
},
...
]
}
For each resource change with action "update", we can compute a diff between `before` and `after`. The `before` is the live state (after refresh) and `after` is the desired state (from configuration). So the drift is that the live state (before) is different from the desired (after).
We can generate a list of attribute drifts by comparing the two dictionaries (deep diff). But note: the `before` and `after` might have nested structures. We can flatten both and then compare.
3. For unmanaged resources:
We run an AWS Config query:
SELECT resourceId, resourceType, configuration WHERE resourceType NOT IN ('AWS::Terraform::State', ...)
But we don't have a list of resource types that Terraform manages. Instead, we can get all resources and then for each, check if there's a corresponding resource in the Terraform state.
How to match? Terraform state has resources with type (like "aws_instance") and name, and the state has an `id` (which is the AWS resource ID). So we can build a set of (type, id) from the Terraform state.
But note: the Terraform state's `id` might be the ARN or the resource ID? For AWS, it's usually the resource ID (e.g., instance ID). But for some resources, it might be the ARN.
We can build the set from the Terraform state:
for each resource in state:
key = (resource.type, resource.id)
Then, for each resource from AWS Config:
key = (resource.resourceType, resource.resourceId)
If the key is not in the Terraform state set, then it's unmanaged.
4. Combine:
- For managed drifts: we have a list of (resource_type, resource_id, attribute, before_value, after_value)
- For unmanaged: (resource_type, resource_id, "unmanaged", None, None)
5. Suppression: apply rules.
6. Incident.
This design uses Terraform for managed resources and AWS Config for unmanaged. But note: AWS Config might not have all resources (if not recorded). We can also use the AWS API to list resources of a given type, but that would require knowing the types. We can get the list of resource types from the Terraform state? Not all.
Alternatively, we can use AWS Resource Groups Tagging API to get all resources that have tags, and then for each, describe it to get the full configuration and resource type. But that's a lot of API calls and might be expensive.
Given the complexity, we might start with only managed resources (Terraform) and then add unmanaged resource detection as an optional feature.
Code structure for Phase 1:
terraform_drift.py:
- run_terraform_plan(workspace) -> returns list of Drift (managed drifts)
aws_unmanaged.py:
- get_aws_resources(account, region) -> returns list of (resource_type, resource_id)
- get_terraform_state_resources(terraform_state) -> returns set of (resource_type, resource_id)
- compute_unmanaged(aws_resources, tf_resources) -> list of Drift (unmanaged)
suppressor.py: same as before.
dispatcher.py: same.
main.py:
tf_drifts = []
for workspace in terraform_workspaces:
tf_drifts.extend(terraform_drift.run(workspace))
unmanaged_drifts = aws_unmanaged.compute(account, region, terraform_state_location)
all_drifts = tf_drifts + unmanaged_drifts
filtered = suppressor.suppress(all_drifts, rules)
dispatcher.dispatch(filtered)
This is a more focused solution that we can build and then generalize later.
23. Conclusion for the answer:
We'll design a pipeline that:
Sources:
- For resources managed by IaC (Terraform): use Terraform's own plan output (which compares the refreshed state with the configuration).
- For unmanaged resources: use AWS Config (or similar) to list all resources and compare with the IaC state.
Suppression rules: defined by resource type, attribute, etc. and applied to the drift list.
Incident flow: alert and ticket for non-suppressed drifts, with optional automated remediation (via Terraform apply) after approval.
We'll write the code for the Terraform part and the AWS unmanaged part, and then combine.
Note: This design is specific to Terraform and AWS. For other IaC tools and clouds, we would need to write similar adapters.
Given the instructions to "architect a drift detection pipeline", we present this as a practical approach.
24. Implementation details for Terraform plan parsing:
We can use the `terraform plan -out=plan.out` and then `terraform show -json plan.out` to get the JSON.
The JSON has a field `resource_changes`. For each change:
- If actions include "update", then we have `before` and `after`. We can compute a diff of the two dictionaries (at the first level? but we want nested too). We can use a recursive diff function.
- We want to report each attribute that is different. So we can flatten the `before` and `after` dictionaries and then compare the keys.
Example flattening:
before: {"root_block_volume": [{"encrypted": true}]}
after: {"root_block_volume": [{"encrypted": false}]}
flattened:
before: {"root_block_volume.0.encrypted": true}
after: {"root_block_volume.0.encrypted": false}
Then we compare. But note: the index might change? We assume the list order is the same.
We can write a function to flatten a nested structure (dicts and lists) into dot-notation keys.
Steps:
def flatten(d, parent_key='', sep='.'):
items = []
if isinstance(d, dict):
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
items.extend(flatten(v, new_key, sep=sep).items())
elif isinstance(d, list):
for i, v in enumerate(d):
new_key = parent_key + sep + str(i) if parent_key else str(i)
items.extend(flatten(v, new_key, sep=sep).items())
else:
items.append((parent_key, d))
return dict(items)
Then, for each resource change with update, we flatten the `before` and `after` and then for each key in the union of both, if the values differ, we create a Drift.
But note: some attributes might be computed (like `id`) and we might not want to compare them? Actually, the `id` in Terraform state is the live ID, so it should be the same. But if the resource is recreated, the ID changes. That's a drift? Actually, if the ID changes, then the resource is replaced. But in Terraform, that's a destroy and create. So the action would be "delete" and "create", not "update". So for update, the ID should be the same.
We can ignore the `id` attribute? Or we can include it. It's up to the suppression rules.
25. Example code for flattening and diff:
from deepdiff import DeepDiff
# But we want to flatten first? Or we can use DeepDiff on the nested structures and then convert the diff to our drift list.
Actually, we can use DeepDiff to get the differences in a structured way, but then we have to convert to our flat attribute paths.
Alternatively, we can flatten both and then compare.
Let's flatten and then:
before_flat = flatten(before)
after_flat = flatten(after)
all_keys = set(before_flat.keys()) | set(after_flat.keys())
for key in all_keys:
before_value = before_flat.get(key, MISSING)
after_value = after_flat.get(key, MISSING)
if before_value != after_value:
drifts.append(Drift(resource_type, resource_id, key, before_value, after_value))
But note: if an attribute is removed (before has it, after doesn't) or added, that will be captured.
However, the `change` object in Terraform plan might already tell us the attributes that changed? Not exactly. The `change` object has `before` and `after` but not a list of changed attributes.
So we have to compute the diff ourselves.
26. Unmanaged resources:
We get from AWS Config:
response = config_client.select_resource_config(
Expression="SELECT resourceId, resourceType, configuration WHERE resourceType NOT LIKE 'AWS::Terraform::State'"
)
But note: AWS Config might not support SELECT * for all accounts? We have to use the query.
Then, for each result:
resource_type = result['resourceType']
resource_id = result['resourceId']
# configuration is a JSON string, we don't need it for the drift, just the existence.
Then, we check if (resource_type, resource_id) is in the Terraform state set.
But note: the resource_type in AWS Config is in the form "AWS::EC2::Instance", while in Terraform state it's "aws_instance". We need to map? Or we can store the Terraform state with the AWS resource type?
In Terraform state, the resource type is the provider type (e.g., "aws_instance"). We can create a mapping from Terraform resource type to AWS CloudFormation type. But that's not 1-to-1? Actually, for AWS, the Terraform resource type corresponds to an AWS CloudFormation resource type? Not exactly. For example, `aws_instance` -> `AWS::EC2::Instance`.
We can build a mapping for common resources. Or we can just compare by the resource ID? Because the same resource ID (like an instance ID) is unique across AWS, regardless of type? But wait, an instance ID is only for EC2 instances. So we can match by resource ID alone? Not if we have different resource types with the same ID? That's unlikely because AWS resource IDs are unique within a type? Actually, an instance ID is only for EC2, a bucket name is global, etc. So we can match by resource ID alone? But note: a bucket name is also the resource ID for S3? In Terraform, the `id` of an S3 bucket is the bucket name. In AWS Config, the resourceId for an S3 bucket is the bucket name. So we can match by resourceId without the type?
However, there might be two resources of different types with the same ID? For example, an IAM user named "foo" and an S3 bucket named "foo"? That's possible because the namespaces are different. But the resourceId in AWS Config for an IAM user is the user name, and for an S3 bucket it's the bucket name. So they are in different namespaces? Actually, the resourceId is just a string and AWS Config doesn't namespace it by type. So if we have an IAM user "mybucket" and an S3 bucket "mybucket", they would both have resourceId "mybucket". But they are different types. So we need the type to distinguish.
Therefore, we must use (resource_type, resource_id) as the key.
But the resource_type in AWS Config is in the form "AWS::EC2::Instance", and in Terraform state it's "aws_instance". We need to convert one to the other.
We can create a mapping:
terraform_to_aws_type = {
"aws_instance": "AWS::EC2::Instance",
"aws_s3_bucket": "AWS::S3::Bucket",
...
}
Then, for each resource in Terraform state, we convert the type to AWS Config type and then use that to compare.
Alternatively, we can convert the AWS Config type to Terraform type? But we don't have a reverse mapping for all.
Since we are comparing Terraform state to AWS Config, we should convert one to match the other. Let's convert the Terraform state type to AWS Config type, because we have a fixed set of Terraform resource types we use.
Steps for unmanaged:
tf_resources_set = set()
for tf_resource in terraform_state:
aws_type = terraform_to_aws_type.get(tf_resource.type)
if aws_type:
tf_resources_set.add((aws_type, tf_resource.id))
Then, for each aws_resource from AWS Config:
if (aws_resource.resourceType, aws_resource.resourceId) not in tf_resources_set:
then it's unmanaged.
But note: the Terraform state might have resources that are not in AWS Config (e.g., because AWS Config doesn't record that type). Then we would miss them? But we are only concerned about live resources that are not in IaC. If AWS Config doesn't have it, then we don't know about it. So we can only check for unmanaged resources that AWS Config knows about.
That's acceptable.
27. Putting it together:
We have:
Managed drifts: from Terraform plan (for resources in Terraform state).
Unmanaged drifts: from AWS Config (for resources not in Terraform state, after mapping types).
Then we combine and suppress.
28. Example code for Terraform plan parsing:
import subprocess
import json
def run_terraform_plan(workspace_dir):
# Run terraform plan and capture JSON output
cmd = ["terraform", "plan", "-out=plan.out"]
subprocess.run(cmd, cwd=workspace_dir, check=True)
cmd = ["terraform", "show", "-json", "plan.out"]
result = subprocess.run(cmd, cwd=workspace_dir, capture_output=True, text=True, check=True)
plan = json.loads(result.stdout)
return plan
def extract_drifts_from_plan(plan, terraform_state):
drifts = []
for change in plan.get("resource_changes", []):
if "update" in change["change"]["actions"]:
# Get the resource type and id from the change?
# The change has "address", "type", "name", and "change.before" and "change.after"
resource_type = change["type"] # e.g., "aws_instance"
resource_name = change["name"]
# The resource id is in the state. We can get it from the terraform_state?
# Actually, the change has a field "change.before.id" and "change.after.id", but they should be the same?
# Let's use the before.id (which is the live id) as the resource_id.
resource_id = change["change"]["before"].get("id")
if not resource_id:
# If there's no id, then we can't track it? Skip or use address?
continue
before = change["change"]["before"]
after = change["change"]["after"]
# Flatten both
before_flat = flatten(before)
after_flat = flatten(after)
# Compare
all_keys = set(before_flat.keys()) | set(after_flat.keys())
for key in all_keys:
before_value = before_flat.get(key, MISSING)
after_value = after_flat.get(key, MISSING)
if before_value != after_value:
drifts.append(Drift(
resource_type=resource_type,
resource_id=resource_id,
attribute=key,
live_value=before_value,
desired_value=after_value
))
return drifts
But note: the Terraform plan might also have "create" and "delete". We might want to treat create as missing in live? and delete as unmanaged? Actually, if Terraform wants to create a resource, that means it's in the configuration but not in the state (so not in live). That's a missing resource. And if it wants to delete, that means it's in the state but not in the configuration? Or in the configuration with `count=0` or `for_each`? Actually, delete means the resource is in the state but not in the configuration (or removed by count). That's a drift? It's a removal from IaC. We might want to alert that a resource is about to be deleted? But that's a plan to delete, not a drift. Drift is when the live state doesn't match the desired state. If the desired state says to delete, then the live state having the resource is a drift. So we should consider:
- If action is "delete": the resource is in the state (so it exists in live) but not in the configuration (so desired state doesn't have it). That's a drift (unmanaged? but it's managed by Terraform, but Terraform wants to remove it). We can treat it as a drift of type "resource_unmanaged" from the perspective of the current configuration? But it is managed by Terraform, just the configuration changed.
Actually, the desired state (configuration) does not include that resource anymore. So it's a drift: the live state has a resource that the configuration does not. We can report that as an unmanaged resource? But it is managed by Terraform (in the state) but not in the configuration. We might want to treat it as a drift because the configuration does not declare it.
However, note: the user might have removed it from the configuration intentionally. So it's not a drift, it's a planned deletion. But until it's deleted, it exists and is not in the configuration, so it's a drift.
We can include it in the drift list as:
resource_type, resource_id, "resource_unmanaged", "resource exists in live but not in desired configuration", None
But note: the Terraform plan will delete it, so the incident might be: "This resource is going to be deleted by the next Terraform apply". That's a different kind of alert.
Given the complexity, we might only focus on update drifts and unmanaged resources (from AWS Config) that are not in the Terraform state at all.
So, for the Terraform plan part, we only consider update actions? And then for unmanaged, we consider resources that are not in the Terraform state (from the state file) at all.
But what about resources that are in the state but the configuration changed (so they are going to be deleted or replaced)? That's a change in the desired state, not a drift from the current desired state? Actually, the desired state has changed (the configuration was updated). So the current desired state (configuration) does not include that resource, so it's a drift (unmanaged) until it's deleted.
We might want to include that in the unmanaged list? But note: the resource is in the Terraform state, so it's managed. But the configuration no longer includes it. So from the perspective of the current configuration, it's unmanaged.
We can do:
For the unmanaged detection, we compare the current configuration (from Terraform state? or from the configuration files?) with the live state.
But wait: we have two desired states:
- The Terraform configuration (what we want now)
- The Terraform state (what was desired in the past and what is deployed? but the state might be out of date if we haven't refreshed)
Actually, the Terraform state is the last known desired state? Not exactly. The state is what Terraform knows is deployed. The configuration is what we want now.
So, for unmanaged resources, we want resources that are in the live state but not in the current configuration. That includes:
- Resources that were never in the configuration (truly unmanaged)
- Resources that were in the configuration but removed (so they are in the state but not in the configuration) -> but note: the state still has them until we run apply? Actually, the state is updated only after apply? No, the state is updated during refresh (which is done in plan). So if we removed a resource from the configuration, then in the plan, the state will still have it (because it's still deployed) and the configuration doesn't. So in the plan, it will show as delete. But in the live state (from AWS Config) it exists. So when we do the unmanaged check (comparing AWS Config resources to the current configuration), we would not find it in the configuration, so it would be unmanaged. But it is in the Terraform state? Yes, but the state is not the configuration. We are comparing to the configuration.
So, for unmanaged, we should compare the live resources to the current configuration (not the state). But how do we get the current configuration from Terraform? We can parse the Terraform configuration files (HCL) to get the list of resources? That's complex because of modules, count, for_each, etc.
Alternatively, we can get the list of resources that Terraform plans to manage from the plan? The plan has the resources that are in the configuration (even if they are going to be deleted). In the plan JSON, the `resource_changes` includes resources that are in the configuration (with action delete). So we can build a set of (type, id) from the configuration? But note: for resources that are going to be created, they are not in the state, so we don't have an id. How do we match? We can't by id because the id doesn't exist yet.
This is getting very messy.
Given the time, let's simplify:
We will only detect drifts for resources that are:
- In the Terraform state (so they are managed) and
- In the current configuration (so they are still desired) and
- The plan shows an update action.
And for unmanaged, we only consider resources that are:
- In AWS Config and
- Not in the Terraform state at all (by type and id, with type mapping).
We ignore resources that are in the state but not in the configuration (to be deleted) and resources that are in the configuration but not in the state (to be created) because those are not drifts, they are planned changes.
But note: a resource that is in the configuration and not in the state (so to be created) is not a drift because it doesn't exist in live? Actually, it doesn't exist in live, so no drift. Similarly, a resource that is in the state and not in the configuration (to be deleted) exists in live and is not in the configuration, so that is a drift (unmanaged). But we are not including it because we are only checking resources that are not in the state at all? Wait, we are checking for unmanaged by comparing AWS Config to the Terraform state set. If a resource is in the state, then it's managed, even if it's going to be deleted. So we won't count it as unmanaged.
So we are missing the case of a resource that is in the state but removed from the configuration. That is a drift (it exists in live but not in desired). But we are not capturing it because it's in the state set.
We can adjust: for unmanaged, we compare AWS Config resources to the set of resources that are in the current configuration (not the state). But we don't have an easy way to get the set of resources in the current configuration.
Alternatively, we can get the set of resources from the plan? The plan has a list of resources that are in the configuration (including those to be deleted). So we can build a set of (type, id) for resources that are in the configuration? But for resources to be created, we don't have an id. So we can't match by id.
We can do:
For each resource in the plan (resource_changes):
if the action is not "delete", then we have an id (from before or after). We can add (type, id) to the set of desired resources.
For resources with action "delete", they are in the state but not in the configuration, so they are not desired. So we don't add them.
Then, for unmanaged, we compare AWS Config resources to this set of desired resources (from the plan, excluding deletes). Then, any resource in AWS Config that is not in this set is unmanaged.
But note: resources that are going to be created are not in the state and not in AWS Config? They don't exist, so they won't be in AWS Config. So we don't care.
So:
desired_resources_set = set()
for change in plan["resource_changes"]:
if "delete" not in change["change"]["actions"]:
# It's either create or update, so it's in the configuration and will exist after apply? But for create, we don't have an id in the plan? Actually, for create, the before is null and after has the attributes, but the id might be computed? In the plan, for a create, the after might have a computed id (which is not known). So we can't get the id for creates.
This is a problem.
Alternatively, we can get the list of resources that are in the configuration by running `terraform state pull` and then looking at the resources? But the state might have resources that are no longer in the configuration (to be deleted). So we need the current configuration.
Given the complexity, we might have to parse the Terraform configuration to get the list of resources (with their types and names) but without the ids? Then, for unmanaged, we compare by type and name? But the same resource type and name might exist in multiple environments? We need a unique identifier.
Actually, for unmanaged, we want to know if a live resource is not managed by Terraform at all. So we can check by the Terraform state: if a resource is in the state, then it's managed. Even if it's going to be deleted, it's still managed until the next apply. So we can consider that as managed.
So, we can define:
Managed: resources that are in the Terraform state (regardless of whether they are in the current configuration). Because Terraform knows about them and will delete them if they are not in the configuration.
Then, unmanaged: resources that are not in the Terraform state.
This is simpler: we don't need to parse the configuration for unmanaged. We just need the state.
And for drifts, we only consider resources that are in the state and in the configuration (so they are still desired) and have an update action.
But what about resources that are in the state and in the configuration but the plan shows delete? That means the configuration changed (e.g., count reduced) and the resource is going to be removed. But until it's removed, it's still in the state and in the configuration? Actually, if the configuration changed to remove the resource (by reducing count or removing from for_each), then the resource is no longer in the configuration? But the state still has it. So it's in the state but not in the configuration? Then it's not in the configuration, so we don't consider it for drift? But it exists in live and is not in the configuration, so it's a drift (unmanaged). But we are not capturing it because we only look at resources that are in the configuration (via the plan?).
Let's clarify:
Desired state: the current configuration (what we want now).
Live state: what is actually deployed.
Drift: when live state does not match desired state.
For a resource that is in the state but not in the configuration, the desired state does not include it, so it's a drift (unmanaged). But note: it is managed by Terraform (in the state) but the desired state (configuration) has changed. So it's a drift because the configuration doesn't want it.
We want to catch that as an unmanaged resource? But it is managed by Terraform, just the configuration changed.
We can treat it as:
- If the resource is in the state and not in the configuration, then it's a drift of type "resource_unmanaged" (because the configuration doesn't want it).
How do we know if a resource is in the configuration? We need to parse the configuration files to get the list of resources that are currently declared.
Given the complexity, we might decide:
We only report drifts for resources that are in both the state and the configuration (so they are still desired) and have attribute changes.
And we report unmanaged resources as those that are in AWS Config but not in the Terraform state.
This means we miss the case of resources that are in the state but removed from the configuration. But that's okay because the user will see that in the Terraform plan (delete action) and might not consider it a drift because they intended to remove it.
But wait, if they removed it from the configuration, then the desired state does not include it, so the fact that it exists in live is a drift. But we are not reporting it because we are not comparing the configuration to the live state for resources that are not in the configuration.
We can adjust the unmanaged detection:
Unmanaged: resources in live state that are not in the desired state (current configuration).
To get the desired state (current configuration) we need to know which resources are declared. We can get that from the Terraform state? No, the state might have resources that are no longer declared.
So we need to parse the configuration files.
This is getting too complex for a simple design.
Given the time, I propose we stick to:
Phase 1:
- Managed drifts: resources that are in the Terraform state and in the current configuration (so they are still desired) and the plan shows an update (non-idempotent change). We get this from the Terraform plan.
- Unmanaged: resources that are in AWS Config but not in the Terraform state (by type and id, with type mapping).
This will cover:
- Drifts in managed resources (attribute changes).
- Unmanaged resources (never managed by Terraform).
It will not cover:
- Resources that were managed by Terraform but removed from the configuration (they will be in the state and in AWS Config, but we don't report them as unmanaged because they are in the state). But we do report them in the Terraform plan as delete? And we don't report the drift because the configuration no longer wants them.
The user might be okay with that because they intended to remove them.
However, if they removed the resource from the configuration by mistake, they might not realize it's still deployed. But the Terraform plan will show a delete, so they will see it.
So, we rely on the Terraform plan to show deletions, and our drift detection only shows updates and unmanaged.
This is a practical compromise.
29. Summary of the design:
We have a pipeline that:
1. For each Terraform workspace:
a. Run `terraform plan` and parse the JSON output.
b. For each resource change with action "update", compute the attribute diff (by flattening the before and after) and create Drift objects.
2. For unmanaged resources:
a. Query AWS Config for all resources (or for specific types?).
b. Build a set of (resource_type, resource_id) from the Terraform state (with type mapping to AWS Config types).
c. For each resource in AWS Config, if not in the set, create an unmanaged Drift.
3. Apply suppression rules to the combined list of drifts.
4. Dispatch incidents for non-suppressed drifts.
We assume that the Terraform state is up-to-date (we run `terraform plan` which refreshes the state). But note: `terraform plan` refreshes the state in memory, but does not save it. So we are using the refreshed state for the comparison, but the state file on disk might be old. That's okay because we are using the refreshed state for the drift detection.
However, for unmanaged, we use the state file on disk? We can use the refreshed state from the plan? The plan does not output the entire state. We can run `terraform state pull` to get the state. But that might be outdated if we haven't refreshed? Actually, `terraform plan` refreshes the state in memory but does not update the state file. So `terraform state pull` will give the old state. We need the refreshed state.
We can run `terraform refresh` first? That updates the state file. But that might be dangerous if we have multiple people running this. Alternatively, we can use the state from the plan? The plan output includes the `resource_changes` and for each change, the `before` is the refreshed state. But we don't have a full list of resources from the plan. Only the ones that changed.
So for unmanaged, we need the full list of resources in the state (after refresh). We can get that by running `terraform state pull` after `terraform plan`? But `terraform plan` doesn't update the state file. We can run `terraform apply -refresh-only`? That would update the state file. But that might be heavy and we don't want to apply.
Alternatively, we can run `terraform refresh` to update the state file, then use `terraform state pull` to get the state. But `terraform refresh` will update the state file, which might be shared? We might not want to update the state file automatically.
Given the complexity, we might have to accept that the state file might be outdated for unmanaged detection. Or we can do:
Step 1: Run `terraform plan` (which does an implicit refresh in memory).
Step 2: From the plan output, we can get the list of resources that are in the configuration (from the resource_changes). But we also need the resources that are in the state but not in the configuration? For unmanaged, we only care about resources that are not in the state. So we need the full state.
We can run `terraform state pull` and then manually refresh the state by running `terraform refresh` and then `terraform state pull` again? But that updates the state file.
Alternatively, we can use the `terraform plan` output to get the refreshed state for the resources that changed, but not for the ones that didn't change? That's incomplete.
Given the challenges, we might have to update the state file as part of the drift detection. We can do:
terraform refresh -no-color
This will update the state file. Then we can use `terraform state pull` to get the updated state.
But note: if multiple runs of this pipeline are happening, we might have race conditions. We can use a lock? Or we can use a separate state file for drift detection?
We might decide that the drift detection pipeline should not modify the state file. Then we have to accept that the unmanaged detection might be based on an outdated state.
Given the trade-offs, we might skip unmanaged detection for now and only do managed drifts.
Or, we can do unmanaged detection only for resources that are not in the state file (as is) and accept that if the state file is outdated, we might miss some unmanaged resources.
Given the time, I'll leave the unmanaged detection as using the state file (without refresh) and note that it might be inaccurate if the state file is outdated.
30. Final design for the answer:
We'll present a design that:
- For managed resources (Terraform): use `terraform plan` to get drifts (updates only).
- For unmanaged resources: use AWS Config and compare with the Terraform state file (without refresh) to find resources not in the state.
And we'll note the limitations.
We'll also design the suppression and incident flow.
We'll write the code structure accordingly.
31. Code structure:
drift_detection/
__init__.py
terraform/
__init__.py
drift.py # contains functions to run plan and extract drifts
aws/
__init__.py
unmanaged.py # contains functions to query AWS Config and compare with state
suppressor.py
dispatcher.py
models.py # defines Drift, SuppressionRule, etc.
config.py # loads configuration (rules, terraform workspaces, aws account, etc.)
main.py
32. Example main:
import yaml
from drift_detection.terraform.drift import get_managed_drifts
from drift_detection.aws.unmanaged import get_unmanaged_drifts
from drift_detection.suppressor import suppress
from drift_detection.dispatcher import dispatch
from drift_detection.models import Drift
def load_config(config_file):
with open(config_file) as f:
return yaml.safe_load(f)
def main():
config = load_config("config.yaml")
all_drifts = []
# Managed drifts from Terraform
for workspace in config["terraform"]["workspaces"]:
drifts = get_managed_drifts(workspace)
all_drifts.extend(drifts)
# Unmanaged drifts from AWS
unmanaged_drifts = get_unmanaged_drifts(
aws_account=config["aws"]["account"],
region=config["aws"]["region"],
terraform_state_location=config["terraform"]["state_location"]
)
all_drifts.extend(unmanaged_drifts)
# Apply suppression
suppression_rules = config.get("suppression_rules", [])
filtered_drifts = suppress(all_drifts, suppression_rules)
# Dispatch
if filtered_drifts:
dispatch(filtered_drifts, config["incident"])
if __name__ == "__main__":
main()
33. Note: This is a simplified version. In reality, we might have multiple Terraform states (by workspace, or by directory) and multiple AWS accounts/regions.
-
Conclusion:
This design is a starting point. It focuses on Terraform and AWS, and has limitations in terms of state freshness for unmanaged resources and coverage of all resource types.
However, it provides a clear architecture that can be extended for other IaC tools and cloud providers by implementing similar modules.
The suppression and incident flow are generic and can be configured.
We can improve by:
- Using a more robust way to get the current desired state (configuration) for unmanaged detection.
- Handling more complex attribute comparisons (nested, computed attributes).
- Adding more suppression rule conditions (e.g., based on attribute values).
- Adding severity scoring and different incident channels based on severity.
But for the purpose of this question, this should suffice.
-
Final note:
The user asked for "sources, suppression rules, and incident flow". We've covered:
Sources: Terraform state and plan for managed, AWS Config for unmanaged.
Suppression rules: defined in YAML, applied to the drift list.
Incident flow: dispatch function that can send alerts and create tickets.
We've also discussed the possibility of automated remediation, but we left it out for simplicity.
This is a complete architecture for a drift detection pipeline.
I'll architect a comprehensive Infrastructure as Code (IaC) Drift Detection Pipeline that monitors for configuration drift between declared IaC and actual cloud/on-prem resources.
Architecture Overview
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ IaC Sources │───▶│ Drift Detector │───▶│ Suppression │
└─────────────────┘ └─────────────────┘ │ Engine │
│ │ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Live State │ │ Comparison │ │ Filtered │
│ Collectors │ │ Engine │ │ Drifts │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────────────┐
│ Incident Response │
│ Workflow │
└─────────────────────────┘
1. Sources & Data Collection
IaC Sources (Desired State)
Sources:
- Terraform:
- State files (S3, remote backend)
- HCL configuration parsing
- Terraform Cloud/Enterprise API
- CloudFormation:
- Stack templates (S3, API)
- Change sets
- Pulumi:
- Checkpoint files
- Stack definitions
- Ansible:
- Playbooks & inventory
- Fact gathering
- Kubernetes:
- GitOps repos (ArgoCD/Flux)
- Manifests (Helm charts, Kustomize)
- Azure ARM/Bicep:
- Template deployments
- Resource group state
Live State Collectors (Actual State)
class LiveStateCollector:
def collect(self, cloud_provider, region, credentials):
collectors = {
'aws': [
AWSConfigRecorder(), # Historical config
AWSResourceGroupsTaggingAPI(), # Current resources
EC2DescribeInstances(), # Service-specific
S3ListBuckets(),
CloudTrailEvents() # Change history
],
'azure': [
AzureResourceGraph(),
AzureResourceManagerAPI(),
AzureActivityLog()
],
'gcp': [
GCPCloudAssetInventory(),
GCPResourceManager(),
GCPAuditLogs()
],
'kubernetes': [
KubernetesAPI(),
CustomResourceDefinitions()
]
}
2. Normalization & Comparison Engine
Resource Normalization Schema
{
"resource_id": "unique/identifier",
"resource_type": "aws_instance/azurerm_vm/gcp_compute",
"cloud_provider": "aws/azure/gcp",
"region": "us-east-1",
"properties": {
"immutable": ["id", "arn", "creation_time"],
"mutable": ["tags", "size", "state", "labels"],
"computed": ["public_ip", "endpoint"]
},
"metadata": {
"last_modified": "timestamp",
"changed_by": "user/service",
"source": "manual/terraform/cloudformation"
}
}
Comparison Algorithm
class DriftDetector:
def detect_drift(self, desired_state, live_state):
drifts = []
# 1. Resource existence checks
missing_resources = self._find_missing_resources(desired_state, live_state)
extra_resources = self._find_extra_resources(desired_state, live_state)
# 2. Property comparison
for resource in self._matching_resources(desired_state, live_state):
differences = self._deep_compare(
resource.desired_properties,
resource.live_properties
)
for diff in differences:
severity = self._calculate_severity(
resource.type,
diff.property_path,
diff.change_type
)
drifts.append(Drift(
resource_id=resource.id,
resource_type=resource.type,
property_path=diff.path,
desired_value=diff.desired,
actual_value=diff.actual,
change_type=diff.type, # modified, added, removed
severity=severity,
timestamp=datetime.utcnow()
))
return drifts + missing_resources + extra_resources
def _calculate_severity(self, resource_type, property_path, change_type):
"""Severity scoring based on impact"""
severity_matrix = {
'security_group': {'ingress': 'CRITICAL', 'egress': 'HIGH'},
'iam_role': {'policy': 'CRITICAL', 'assume_role': 'CRITICAL'},
'database': {'publicly_accessible': 'CRITICAL'},
'storage': {'encryption': 'CRITICAL', 'versioning': 'HIGH'},
'network': {'subnet': 'HIGH', 'route_table': 'HIGH'},
'compute': {'instance_type': 'MEDIUM', 'image': 'MEDIUM'}
}
return severity_matrix.get(resource_type, {}).get(property_path, 'LOW')
3. Suppression Rules Engine
Rule Types & Examples
suppression_rules:
# 1. Temporal Suppression (maintenance windows)
- id: "maintenance-window"
description: "Allow changes during scheduled maintenance"
condition:
time_window: "Sat 02:00-06:00 UTC"
resource_types: ["aws_instance", "azurerm_vm"]
effect: "suppress"
expire: "2024-12-31"
# 2. Attribute-based Suppression
- id: "ignore-last-modified"
description: "Ignore last_modified timestamp changes"
condition:
attribute: "metadata.last_modified"
effect: "suppress"
# 3. Resource Pattern Suppression
- id: "ephemeral-resources"
description: "Ignore autoscaling group instances"
condition:
resource_type: "aws_instance"
name_pattern: "asg-.*-i-.*"
effect: "suppress"
# 4. Change Type Suppression
- id: "tag-only-changes"
description: "Ignore tag-only modifications"
condition:
changed_properties: ["tags.*"]
change_type: "modified"
effect: "suppress"
# 5. Source-based Suppression
- id: "approved-automation"
description: "Allow changes from CI/CD pipeline"
condition:
changed_by: ["github-actions", "jenkins", "terraform-cloud"]
resource_types: ["aws_s3_bucket", "azure_storage"]
effect: "suppress"
# 6. Owner-based Suppression
- id: "team-xyz-exceptions"
description: "Team XYZ can modify load balancers"
condition:
owner: "team-xyz"
resource_types: ["aws_lb", "aws_alb"]
effect: "alert_low" # Still alert but lower severity
# 7. Value-based Suppression
- id: "dev-environment"
description: "Relax rules for dev environments"
condition:
environment: "dev|test|staging"
severity: ["MEDIUM", "LOW"]
effect: "suppress"
# 8. Dynamic Suppression (via API)
- id: "temporary-exception"
description: "Temporary suppression via API"
condition:
dynamic_rule: "api/suppression-rules/{rule_id}"
effect: "suppress"
ttl: "24h"
Suppression Engine Implementation
class SuppressionEngine:
def __init__(self, rules, context):
self.rules = self._load_rules(rules)
self.context = context # env, owner, time, etc.
def should_suppress(self, drift):
for rule in self.rules:
if self._rule_matches(rule, drift):
if rule.effect == "suppress":
return True, rule.id
elif rule.effect == "alert_low":
drift.severity = "LOW"
return False, None
return False, None
def _rule_matches(self, rule, drift):
# Check all conditions (time, attributes, patterns, etc.)
checks = {
'resource_type': drift.resource_type in rule.resource_types,
'attribute': self._match_attribute(rule.condition, drift.property_path),
'change_type': drift.change_type in rule.change_types,
'environment': self._match_env(rule.condition),
'owner': drift.owner in rule.owners,
'time': self._in_time_window(rule.time_window),
'pattern': re.match(rule.name_pattern, drift.resource_id)
}
return all(checks.values())
4. Incident Flow & Response Workflow
Incident Classification
class IncidentClassifier:
def classify(self, drift):
if drift.severity == "CRITICAL":
return {
"priority": "P1",
"response_time": "15 minutes",
"channel": "pagerduty",
"automated_remediation": True
}
elif drift.severity == "HIGH":
return {
"priority": "P2",
"response_time": "1 hour",
"channel": "slack-alerts",
"automated_remediation": False
}
elif drift.severity == "MEDIUM":
return {
"priority": "P3",
"response_time": "4 hours",
"channel": "email+ticket",
"automated_remediation": False
}
else:
return {
"priority": "P4",
"response_time": "24 hours",
"channel": "weekly-report",
"automated_remediation": False
}
Workflow Stages
graph LR
A[Drift Detected] --> B{Severity Assessment}
B -->|CRITICAL| C[PagerDuty/Slack]
B -->|HIGH| D[Slack Channel]
B -->|MEDIUM| E[Jira Ticket]
B -->|LOW| F[Log & Report]
C --> G{Automated Remediation?}
D --> G
E --> G
G -->|Yes| H[Run Playbook]
H --> I[IaC Apply]
I --> J[Verify]
J --> K[Close Incident]
G -->|No| L[Assignment]
L --> M[Owner Investigation]
M --> N[Manual Resolution]
N --> O[Update IaC/Reconcile]
O --> K
Automated Remediation Playbooks
remediation_playbooks:
- drift_type: "attribute_change"
resource_types: ["aws_s3_bucket", "azure_storage"]
conditions:
property: "encryption"
desired_value: true
action:
type: "terraform_apply"
plan_file: "/tmp/fix-encryption.tfplan"
timeout: 300
rollback:
type: "terraform_apply"
plan_file: "/tmp/rollback.tfplan"
- drift_type: "resource_exists"
resource_types: ["aws_instance"]
conditions:
not_in_terraform_state: true
action:
type: "terraform_import"
address: "aws_instance.{instance_id}"
rollback:
type: "terraform_destroy"
address: "aws_instance.{instance_id}"
Notification Templates
{# Slack Alert #}
**{{ severity }} Drift Detected**
*Resource*: `{{ resource_type }}` ({{ resource_id }})
*Property*: `{{ property_path }}`
*Desired*: `{{ desired_value | truncate(50) }}`
*Actual*: `{{ actual_value | truncate(50) }}`
*Environment*: {{ environment }}
*Account*: {{ account }}
*Link*: {{ console_url }}
*Suppressed*: {{ suppressed | default(false) }}
{% if runbook_url %}
*Runbook*: <{{ runbook_url }}>
{% endif %}
{# Jira Ticket #}
Project: INFRA
Issue Type: Bug
Summary: [{{ severity }}] IaC Drift - {{ resource_type }} {{ resource_id }}
Description:
{{ description }}
Priority: {{ priority }}
Labels: drift,{{ resource_type }},{{ environment }}
5. Pipeline Implementation
Scheduling & Triggers
# config.yaml
triggers:
- type: "schedule"
cron: "0 */2 * * *" # Every 2 hours
- type: "event"
sources:
- "aws-cloudtrail"
- "azure-activity-log"
- "gcp-audit-logs"
event_types:
- "Create/Update/Delete Instance"
- "Modify Security Group"
- type: "manual"
webhook: "/webhooks/drift-detection"
# Or using Apache Airflow DAG
dag = DAG('iac_drift_detection', schedule_interval='0 */2 * * *')
detect = PythonOperator(
task_id='detect_drift',
python_callable=run_drift_detection,
op_kwargs={'account': 'prod', 'regions': ['us-east-1', 'eu-west-1']}
)
alert = SlackWebhookOperator(
task_id='send_alerts',
slack_webhook_conn_id='slack_alerts',
message="{{ task_instance.xcom_pull(task_ids='detect_drift') }}"
)
detect >> alert
Storage & State Management
class DriftStateStore:
def __init__(self):
self.backend = {
'dynamodb': DriftTable('drift_history'),
's3': DriftBucket('drift-reports/{{date}}/'),
'bigquery': BigQueryDataset('iac_drift'),
'elasticsearch': ESIndex('drift-detection')
}
def store_drift(self, drift, incident_id=None):
record = {
'drift_id': uuid4(),
'timestamp': datetime.utcnow().isoformat(),
'resource': drift.resource_id,
'type': drift.resource_type,
'property': drift.property_path,
'desired': drift.desired_value,
'actual': drift.actual_value,
'severity': drift.severity,
'suppressed': drift.suppressed,
'incident_id': incident_id,
'ttl': datetime.utcnow() + timedelta(days=365) # Retention
}
self.backend['dynamodb'].put_item(record)
Metrics & Dashboard
# Prometheus Metrics
iac_drift_total{severity="CRITICAL", environment="prod"} 5
iac_drift_suppressed_total{rule="ephemeral-resources"} 12
iac_drift_time_to_resolve_seconds{resource_type="aws_s3_bucket"} 3600
iac_drift_recurring{resource_id="i-123456"} 3
# Grafana Dashboard Panels:
# 1. Drift Count by Severity (last 7 days)
# 2. Top Drifting Resources
# 3. Mean Time to Detect (MTTD)
# 4. Suppression Effectiveness
# 5. Drift by Resource Type
# 6. Trend Analysis (drift volume over time)
6. Advanced Features
A. Change Intelligence
class ChangeIntelligence:
def analyze(self, drift_history, resource_context):
"""Predictive analysis and root cause"""
return {
'likely_cause': self._correlate_with_logs(drift),
'risk_score': self._calculate_risk(drift, history),
'similar_incidents': self._find_similar(drift),
'recommended_action': self._suggest_remediation(drift)
}
def _correlate_with_logs(self, drift):
"""Correlate with CloudTrail/Azure Activity Logs"""
logs = cloudtrail.lookup(
resource_id=drift.resource_id,
time_range='1h',
event_names=['Modify*', 'Create*']
)
return self._identify_user_or_service(logs)
B. Drift Trend Analysis
class TrendAnalyzer:
def detect_anomalies(self, drifts):
"""Statistical anomaly detection"""
df = pd.DataFrame(drifts)
# Moving average of drifts per resource
# Spike detection (3σ rule)
# Seasonality detection (daily/weekly patterns)
return self._bayesian_change_point_detection(df)
C. IaC Health Score
def calculate_health_score(account):
"""Overall IaC compliance score"""
total_resources = get_managed_resource_count(account)
drifting_resources = get_drift_count(account)
suppressed_resources = get_suppressed_count(account)
compliance_rate = (total_resources - drifting_resources) / total_resources
# Weighted score
score = (
compliance_rate * 0.6 +
(1 - suppressed_resources / total_resources) * 0.2 +
incident_resolution_rate * 0.2
) * 100
return {
'score': round(score, 1),
'grade': 'A' if score > 90 else 'B' if score > 80 else 'C',
'trend': 'up' if score > last_month_score else 'down'
}
7. Security & Compliance
Access Control
# RBAC for drift detection system
roles:
- name: drift-reader
permissions:
- "drift:list"
- "drift:get"
- "reports:generate"
- name: drift-operator
permissions:
- "drift:*"
- "suppression:manage"
- "remediation:trigger"
- "notifications:configure"
- name: drift-admin
permissions:
- "*"
Audit Trail
class AuditLogger:
def log_action(self, user, action, resource, changes):
audit_entry = {
'timestamp': datetime.utcnow(),
'user': user,
'action': action, # 'suppress', 'remediate', 'escalate'
'resource': resource,
'changes_suppressed': changes,
'ip_address': request.remote_addr,
'user_agent': request.headers.get('User-Agent')
}
# Write to immutable storage (S3 with WORM, CloudTrail, etc.)
self.immutable_store.append(audit_entry)
8. Deployment Options
Cloud-Native Architecture
AWS:
- EventBridge → Lambda (detector) → DynamoDB (state) → SNS (alerts)
- Step Functions for complex workflows
- S3 for report storage
- CloudWatch dashboards
Azure:
- Event Grid → Function App → Cosmos DB → Service Bus
- Logic Apps for workflows
- Monitor workbooks
GCP:
- Cloud Scheduler → Cloud Functions → Firestore → Pub/Sub
- Cloud Workflows
- Looker dashboards
Kubernetes:
- Argo Workflows/CronJobs
- PostgreSQL for state
- Grafana/Prometheus
Multi-Cloud Considerations
multi_cloud:
normalization_layer: "Open Policy Agent (OPA) + custom adapters"
unified_identity: "AWS IAM Identity Center / Azure AD / GCP IAM"
cross_account_roles: "AssumeRole across organizations"
unified_logging: "Azure Monitor / CloudWatch Logs / GCP Logging"
deduplication: "hash(resource_id + property_path + timestamp)"
9. Example Configuration
# drift-detection.yaml
accounts:
- id: "prod-aws"
provider: "aws"
regions: ["us-east-1", "us-west-2"]
credentials:
role_arn: "arn:aws:iam::123456789012:role/DriftDetectionRole"
sources:
terraform:
- workspace: "production"
state_file: "s3://my-terraform-state/production/terraform.tfstate"
cloudformation:
- stack: "vpc-stack"
region: "us-east-1"
- id: "prod-azure"
provider: "azure"
subscription_id: "xxxx-xxxx-xxxx-xxxx"
sources:
arm:
- resource_group: "network-rg"
deployment_name: "vpc-deployment"
suppression_rules:
- id: "autoscaling-group"
description: "Ignore autoscaling group instance changes"
condition:
resource_type: "aws_autoscaling_group"
property_path: "instances.*.id"
effect: "suppress"
notifications:
slack:
webhook: "https://hooks.slack.com/..."
channels:
critical: "#infra-alerts-critical"
high: "#infra-alerts"
medium: "#infra-alerts-medium"
pagerduty:
integration_key: "xxxx"
routing_key: "infrastructure"
remediation:
enabled: true
auto_approve:
- resource_type: "aws_s3_bucket"
property: "versioning.enabled"
action: "update"
approval_required:
- resource_type: "aws_security_group"
- resource_type: "aws_iam_role"
storage:
backend: "dynamodb"
table_name: "IaC-Drift-History"
retention_days: 365
monitoring:
metrics: "cloudwatch/prometheus"
dashboard: "grafana/dashboard-id"
alerts:
- metric: "drift_count"
threshold: 10
period: "5m"
10. Best Practices
- Start Small: Begin with critical resources (security groups, IAM, databases)
- Gradual Rollout:
- Phase 1: Detection only (no suppression)
- Phase 2: Add suppression rules
- Phase 3: Enable automated remediation for low-risk changes
- Baseline First: Run in detection-only mode for 2-4 weeks to understand drift patterns
- Change Management: Integrate with existing change approval workflows
- Cost Control:
- Use incremental detection (only scan changed resources)
- Cache live state for 5-15 minutes
- Sample large environments
- Testing:
- Unit tests for comparison logic
- Integration tests with mock cloud APIs
- Chaos testing (inject drift, verify detection)
- Documentation:
- Maintain runbooks for each drift type
- Document suppression rules with justification
- Keep architecture diagrams updated
Key Design Principles
- Idempotent: Safe to run repeatedly without side effects
- Observable: Comprehensive logging, metrics, and tracing
- Secure: Least privilege access, audit trails, encrypted storage
- Extensible: Plugin architecture for new IaC tools/clouds
- Performant: Parallel collection, incremental detection, caching
- Accurate: Minimize false positives through smart normalization
- Actionable: Clear remediation steps with rollback capability
- Cost-Aware: Efficient API usage, sampling for large environments
This architecture provides a production-ready drift detection pipeline that can scale from small environments to large multi-cloud enterprises while maintaining security, compliance, and operational excellence.