The user wants a "reproducible infra provisioner" with specific features:
- Idempotency: Running the provisioner multiple times should result in the same state without side effects.
- Drift Checks: The tool should detect if the actual infrastructure differs from the desired configuration.
- Policies: There should be a way to enforce rules (e.g., tagging, security groups) before applying changes.
The prompt asks to create this. Since building a full-fledged Terraform/OpenTofu competitor from scratch in a single response isn't feasible or practical (and reinventing the wheel is usually bad advice), the best approach is to:
- Select a framework. Python with a library like
pulumi or a custom abstraction over docker/cloud-api is good for demonstration. However, showing how to implement these concepts conceptually using a simple, self-contained Python script is often more educational than just writing a Terraform config.
- Let's choose a Python-based approach that simulates infrastructure (local files or Docker containers) to make it "reproducible" and runnable on any machine without needing AWS keys.
- Actually, a better approach for a "reproducible infra provisioner" is to provide a pattern or a reference architecture using industry-standard tools (like Terraform/OpenTofu) wrapped in a framework that enforces the requested constraints (Idempotency, Drift, Policies).
Alternative: Write a minimal implementation from scratch in Python using a local state file (JSON) and simple "resources" (e.g., creating local files or dummy HTTP requests) to demonstrate the logic of how tools like Terraform work internally. This satisfies the "Create a..." prompt better than just showing config files for existing tools.
Let's go with the Python Implementation approach. It demonstrates the core mechanics:
- State: JSON file to store known infrastructure.
- Desired State: Python dictionaries defining what we want.
- Idempotency: Logic to compare Current vs. Desired.
- Drift: Compare Real World vs. State File.
- Policies: A validation step before applying.
Plan:
- Concept: Define a
Resource base class.
- Idempotency: Implement a
plan phase. If resource exists and matches, do nothing. If it doesn't exist, create. If it exists but differs, update.
- Drift: Implement a
check_drift method that queries the "real world" (simulated) and compares it to the "state file".
- Policies: Implement a
Policy class that validates the desired configuration (e.g., "must have a 'owner' tag").
- Execution Engine: A script that ties it all together.
Let's refine the "Real World" simulation. To make it runnable for the user, I'll use the local filesystem.
- Resource:
File.
- Operations: Create, Update, Delete.
Structure:
infra.py: The core engine.
main.py: The configuration (like main.tf).
state.json: The state file.
Components Details:
- Idempotency: If
state says file exists, and file does exist, and content matches, no-op.
- Drift: If
state says file exists, but file is missing (external deletion) -> Drift detected. Or if content changed manually -> Drift detected.
- Policies: A registry of checks. e.g.,
check_file_size or check_name_convention.
Let's write the code.
Self-Correction during thought process:
A pure Python script might be too abstract. The user might want something that actually provisions real infra, or at least acts like a real tool. However, creating a provider for AWS in a chat response is too heavy. I will stick to the "Local File System as Infrastructure" analogy. It is reproducible (runs locally) and illustrates the concepts perfectly.
I will structure the response as:
- Philosophy: How the loop works (Desired -> Plan -> Validate -> Apply -> State).
- The Code: A complete, single-file (or modular) Python script that acts as the provisioner.
- Explanation: How the code achieves Idempotency, Drift, and Policies.
Drafting the Code Logic:
- Base Resource:
__init__(self, name, config), create(), update(), delete(), read() (checks real state).
- State Manager: Loads/Saves JSON.
- Policy Engine: A function that takes a resource config and raises errors.
- Orchestrator:
- Load Desired Config.
- Load State.
- Run Drift Detection (Compare Real World vs State). If drift, alert or fix.
- Plan (Compare Desired vs Real World).
- Run Policies on Desired Config.
- Apply Plan.
- Save State.
This seems solid. I will use Python standard libraries (os, json, hashlib) to ensure it runs everywhere.
Refining the Policy aspect:
Policies usually check before deployment.
Example Policy: "All files must have a .txt extension" or "Must not exceed 1KB".
I'll implement a simple decorator or validation function.
Refining Drift:
Drift is when state.json says "File A has content 'Hello'" but the actual file has content 'Hacked'".
I need to differentiate between "Correction" (bringing it back to Desired State) and "Drift Detection" (Reporting that it changed). I will implement a specific detect_drift command.
Let's build it.
Summary of the Tool:
Name: Pyraform (Py-Infrastructure-Former).
Goal: Manage local files idempotently.
Step 1: The Core Logic
State: Dict mapping ID -> Attributes.
Resource: File type.
Policies: NamingConventionPolicy, SizeLimitPolicy.
Step 2: The Workflow
plan: Shows what needs to happen.
apply: Executes changes.
drift: Checks for external modifications.
I will provide a single comprehensive Python script that can be copied and run. This is the most "reproducible" way to answer.
Detailed implementation:
- Use
argparse for CLI.
FileResource class.
check_drift: Reads actual file, compares hash/content to state.
reconcile: Compares desired to actual.
validate_policy: Checks rules.
Let's verify the requirements:
- Reproducible: Yes, script form.
- Idempotency: Yes, checks hashes before writing.
- Drift Checks: Yes, reads actual file system vs state.
- Policies: Yes, validation step.
I'll write the response now.
To create a robust, reproducible infrastructure provisioner from scratch, we need to move beyond simple scripts and implement a State-Driven Architecture.
Unlike imperative scripts (which run commands in sequence), a state-driven provisioner works like Terraform or Pulumi. It follows a cycle: Desired State (Config) vs. Actual State (Real World) -> Plan -> Apply.
Below is a complete, runnable Python-based provisioner. It manages local files (as a stand-in for cloud resources) to demonstrate the core concepts of Idempotency, Drift Detection, and Policy Enforcement.
The Architecture
- Idempotency: The provisioner calculates a "diff" between the configuration and the actual state. It only acts if changes are needed.
- Drift Detection: Before applying, it verifies if the real world has changed manually (externally) since the last run.
- Policies: A validation hook that rejects changes that violate rules (e.g., "dangerous ports" or in this case, "forbidden file extensions").
The Code: provisioner.py
Save this to a file named provisioner.py.
import os
import json
import hashlib
import shutil
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import List, Dict, Any, Optional
# ==========================================
# CORE INTERFACES & STATE MANAGEMENT
# ==========================================
class PolicyViolationError(Exception):
"""Raised when a resource violates a policy."""
pass
class DriftDetectedError(Exception):
"""Raised when manual changes are detected outside the provisioner."""
pass
@dataclass
class ActionResult:
resource_id: str
status: str # 'created', 'updated', 'deleted', 'skipped', 'drift'
message: str
class Resource(ABC):
def __init__(self, name: str, state_file: str = "state.json"):
self.name = name
self.state_file = state_file
self.type = self.__class__.__name__
self.id = f"{self.type}.{name}"
@abstractmethod
def get_actual_state(self) -> Optional[Dict[str, Any]]:
"""Reads the real world state (e.g., API call, file read)."""
pass
@abstractmethod
def get_desired_state(self) -> Dict[str, Any]:
"""Returns the configuration defined in code."""
pass
@abstractmethod
def create(self, desired: Dict[str, Any]) -> None:
pass
@abstractmethod
def update(self, desired: Dict[str, Any]) -> None:
pass
@abstractmethod
def delete(self) -> None:
pass
def load_stored_state(self) -> Dict:
"""Loads the state from the local JSON file."""
if not os.path.exists(self.state_file):
return {}
with open(self.state_file, 'r') as f:
return json.load(f)
def save_stored_state(self, state: Dict) -> None:
"""Saves the state to the local JSON file."""
with open(self.state_file, 'w') as f:
json.dump(state, f, indent=4)
# ==========================================
# CONCRETE RESOURCE IMPLEMENTATION (Local File)
# ==========================================
class LocalFile(Resource):
def __init__(self, name: str, path: str, content: str, ensure: str = "present"):
super().__init__(name)
self.path = path
self.content = content
self.ensure = ensure # 'present' or 'absent'
def get_checksum(self, data: str) -> str:
return hashlib.md5(data.encode()).hexdigest()
# --- Real World Interaction ---
def get_actual_state(self) -> Optional[Dict[str, Any]]:
if not os.path.exists(self.path):
return None
with open(self.path, 'r') as f:
content = f.read()
return {
"path": self.path,
"content": content,
"checksum": self.get_checksum(content)
}
def get_desired_state(self) -> Dict[str, Any]:
return {
"path": self.path,
"content": self.content,
"checksum": self.get_checksum(self.content),
"ensure": self.ensure
}
def create(self, desired: Dict[str, Any]) -> None:
os.makedirs(os.path.dirname(desired['path']), exist_ok=True)
with open(desired['path'], 'w') as f:
f.write(desired['content'])
def update(self, desired: Dict[str, Any]) -> None:
# Idempotent update: Overwrite to match desired state
self.create(desired)
def delete(self) -> None:
if os.path.exists(self.path):
os.remove(self.path)
# ==========================================
# POLICY ENGINE
# ==========================================
class PolicyEngine:
@staticmethod
def validate(resource: Resource, desired: Dict[str, Any]):
"""
Validates the desired configuration against business rules.
Throws PolicyViolationError if rules are broken.
"""
if isinstance(resource, LocalFile):
# Policy 1: No sensitive data paths allowed in root
if desired['path'].startswith("/etc"):
raise PolicyViolationError(f"Policy Violation: Cannot manage files in /etc for {resource.id}")
# Policy 2: File content must not contain 'FORBIDDEN_WORD'
if "FORBIDDEN_WORD" in desired['content']:
raise PolicyViolationError(f"Policy Violation: Content contains restricted keyword in {resource.id}")
# ==========================================
# PROVISIONER ENGINE (The Brain)
# ==========================================
class Provisioner:
def __init__(self, resources: List[Resource], state_file: str = "state.json"):
self.resources = resources
self.state_file = state_file
self.stored_state = self._load_full_state()
def _load_full_state(self) -> Dict:
if not os.path.exists(self.state_file):
return {}
with open(self.state_file, 'r') as f:
return json.load(f)
def _save_full_state(self, state: Dict):
with open(self.state_file, 'w') as f:
json.dump(state, f, indent=4)
def check_drift(self, resource: Resource):
"""
Detects if Real World != Stored State.
This means someone changed infrastructure manually.
"""
stored = self.stored_state.get(resource.id, {})
actual = resource.get_actual_state()
if actual and stored:
# If actual state exists, but differs from what we recorded last time
if actual['checksum'] != stored.get('checksum'):
return True
return False
def plan(self):
"""Pre-calculates what needs to happen."""
print("\n--- 📝 GENERATING PLAN ---")
actions = []
for res in self.resources:
desired = res.get_desired_state()
# 1. Check Policies First
try:
PolicyEngine.validate(res, desired)
except PolicyViolationError as e:
print(f"❌ HALT: {e}")
return []
actual = res.get_actual_state()
resource_state_entry = self.stored_state.get(res.id, {})
if desired['ensure'] == 'absent':
if actual:
actions.append((res, 'delete', desired))
else:
actions.append((res, 'skip', desired))
continue
# 2. Drift Detection
if self.check_drift(res):
print(f"⚠️ DRIFT DETECTED for {res.id}: Manual changes found. Overwriting to match config.")
# Depending on strategy, you might halt here. We will enforce desired state.
actions.append((res, 'update', desired))
continue
# 3. Idempotency Logic
if not actual:
actions.append((res, 'create', desired))
elif actual['checksum'] != desired['checksum']:
actions.append((res, 'update', desired))
else:
actions.append((res, 'skip', desired))
return actions
def apply(self):
actions = self.plan()
if not actions:
print("🚫 No actions to perform (Policies failed or nothing to change).")
return
print("\n--- 🚀 APPLYING CHANGES ---")
new_state = self.stored_state.copy()
for res, action, desired in actions:
try:
if action == 'create':
print(f"✅ Creating {res.id}...")
res.create(desired)
new_state[res.id] = desired
elif action == 'update':
print(f"🔄 Updating {res.id}...")
res.update(desired)
new_state[res.id] = desired
elif action == 'delete':
print(f"🗑️ Deleting {res.id}...")
res.delete()
if res.id in new_state: del new_state[res.id]
elif action == 'skip':
print(f"⏩ Skipping {res.id} (Already compliant)")
except Exception as e:
print(f"💥 Error applying {res.id}: {e}")
# Rollback logic would go here in production
self._save_full_state(new_state)
print("\n✨ Apply Complete. State locked.")
# ==========================================
# EXECUTION
# ==========================================
if __name__ == "__main__":
# Clean up previous run for this demo
if os.path.exists("infra_root"): shutil.rmtree("infra_root")
if os.path.exists("state.json"): os.remove("state.json")
print("========== RUN 1: INITIAL DEPLOYMENT ==========")
# Define Infrastructure
infra = [
LocalFile("app_config", "infra_root/app/config.cfg", "version=1.0.0"),
LocalFile("readme", "infra_root/README.md", "Hello World"),
]
prov = Provisioner(infra)
prov.apply()
# Verify Idempotency (Run again, should skip everything)
print("\n========== RUN 2: IDEMPOTENCY CHECK (No changes) ==========")
prov2 = Provisioner(infra)
prov2.apply()
# Simulate Drift (Manual Change)
print("\n========== RUN 3: DRIFT DETECTION (Manual Change) ==========")
with open("infra_root/app/config.cfg", "w") as f:
f.write("version=9.9.9 HACKED") # Manual change outside provisioner
prov3 = Provisioner(infra)
prov3.apply()
# Simulate Policy Violation
print("\n========== RUN 4: POLICY VIOLATION ==========")
bad_infra = [
LocalFile("bad_file", "infra_root/bad.txt", "This has FORBIDDEN_WORD in it")
]
prov4 = Provisioner(bad_infra)
prov4.apply()
How this works
1. The State File (state.json)
This is the "brain" of the provisioner. It records what the infrastructure should look like according to the last successful run. This file is the source of truth for the provisioner.
2. Idempotency Loop
Notice Run 2 in the code.
- The provisioner calculates the hash of the desired content (
version=1.0.0).
- It checks the actual file on disk.
- It checks the
state.json.
- Since
Desired == Actual == State, the engine marks it as skip. You can run this script 100 times, and it will only make changes the first time.
3. Drift Detection
Notice Run 3.
- We manually "hacked" the file to
version=9.9.9.
- The provisioner reads the Real World (
9.9.9) and compares it to the Desired Config (1.0.0).
- It flags Drift. In a strict enterprise setup, you might halt here. In this "self-healing" setup, it enforces the policy by overwriting the manual change back to
1.0.0.
4. Policy Enforcement
Notice Run 4.
- We try to create a resource with
FORBIDDEN_WORD.
- The
PolicyEngine runs before any file touches the disk.
- It raises an exception, stopping the deployment immediately.
Extending to Real Cloud Infrastructure
To make this "Cloud Ready" (AWS/Azure/GCP), you would only need to change the Resource class implementation:
- LocalFile becomes S3Bucket.
os.path.exists becomes boto3.client('s3').head_bucket(...).
state.json is uploaded to a remote backend (like S3 or Consul) so the whole team shares the state.