The user wants a "dynamic infrastructure documentation generator" with three key features:
- IaC Parsing: It needs to read Infrastructure as Code files (like Terraform, CloudFormation, Ansible).
- Dependency Graphs: It needs to understand how resources relate to each other (e.g., this EC2 instance depends on that VPC).
- Real-time State Diffing: It needs to compare the code (the intended state) with the actual cloud environment (the live state) and show the differences.
This is a complex system design problem. I need to structure the response as a high-level architectural design, covering the following aspects:
- High-Level Architecture: The main components and how they interact.
- Component Breakdown:
- Ingestion/Parsing Layer: How to handle different IaC formats.
- Graph Engine: How to build and store the relationships.
- State Fetcher: How to get real data from cloud providers (AWS, Azure, GCP).
- Diff Engine: The logic for comparison.
- Presentation Layer: UI/Dashboard.
- Data Model: How to represent resources universally.
- Technology Stack: Suggested tools and libraries.
- Challenges: Drift detection, permissions, performance.
1. High-Level Architecture:
I'll propose a microservices or modular monolith approach. Let's stick to a logical flow:
Source Code Repo -> Parser -> Normalizer -> Graph Database.
Cloud Provider -> State Fetcher -> Normalizer -> Graph Database.
Graph Database -> Diff Engine -> Documentation Generator (UI/API).
2. Component Details:
-
IaC Parsing:
- Need a pluggable system. Terraform HCL is hard to parse (use
terraform-json or libraries like python-hcl2). CloudFormation is YAML/JSON.
- Abstract Syntax Tree (AST): We parse the code into an AST, then extract resources and their attributes.
- Universal Resource Model (URM): We need a common language. A Terraform
aws_instance maps to a generic "Compute" node.
-
Dependency Graphs:
- Static Analysis: Look for references (e.g.,
subnet_id = aws_subnet.my_subnet.id).
- Storage: A Graph Database (Neo4j) is perfect here because relationships are first-class citizens.
- Edges:
DEPENDS_ON, ROUTES_TO, SECURITY_GROUP_ATTACHMENT.
-
Real-time State Diffing:
- This is the "Drift Detection" part.
- We need Cloud APIs (AWS SDK, Azure SDK).
- We need to map the Cloud API response back to the URM.
- The Diff: Compare Node A (Code) with Node B (Live). Are attributes different?
- Identity Crisis: How do we know live resource X is code resource Y? Tags! (
terraform:instance_id or standard naming tags).
3. The Dynamic Documentation:
- It shouldn't just be a text file. It should be an interactive diagram (React Flow, D3.js, or Cytoscape).
- It needs to be "Live." WebSockets or polling to update the graph as changes happen.
4. Workflow Example:
- Developer pushes Terraform code.
- Parser reads code, creates "Intended Graph".
- Scheduler triggers "Live Fetcher".
- Fetcher queries AWS, creates "Live Graph".
- Diff Engine compares Intended vs. Live.
- UI updates to show: Green (Match), Red (Drift), Blue (Planned).
5. Refining the Tech Stack:
- Language: Go or Python (strong support for parsers and SDKs).
- Graph DB: Neo4j or ArangoDB.
- Frontend: React + React Flow or Cytoscape.js.
- Backend: gRPC or GraphQL (perfect for graph data).
6. Structuring the Output:
I will present this as a System Design Specification.
- Title & Objective
- Core Architecture Diagram (Mental Model)
- Module 1: The Polyglot Parser (The "Read" side)
- Module 2: The State Fetcher (The "Real" side)
- Module 3: The Graph Engine (The Brain)
- Module 4: The Diffing & Documentation Engine (The Output)
- Tech Stack Recommendations
- Key Algorithms (Identity Mapping & Diffing)
Self-Correction during drafting:
Initial thought: Just parse Terraform.
Correction: The prompt implies general IaC. I must mention a generic interface so it supports CloudFormation/Pulumi later.
Initial thought: Just list resources.
Correction: The "dependency graph" requirement is key. The documentation must visualize connections, not just boxes.
Let's flesh out the "Diffing" logic. It's not just text diff. It's semantic diff.
- Code:
instance_type = "t2.micro"
- Live:
instance_type = "t2.large" (manually changed).
- Result: Documentation highlights the node in Orange and shows the diff.
7. Final Polish:
Make it sound professional. Use terms like "AST Extraction," "Resource Normalization," "Idempotency keys," "Drift Detection."
(Drafting the response structure...)
- System Name: "InfraGraph-Sync"
- Architecture: Event-driven.
- Data Model: Unified Cloud Resource Model (UCRM).
- UI: Interactive topology map.
Let's write it out.
This design outlines a system called "InfraGraph-Sync". It creates a living documentation platform that visualizes Infrastructure as Code (IaC), maps resource dependencies, and highlights drift between the code definition and the live cloud environment in real-time.
1. High-Level Architecture
The system operates as a continuous loop, divided into four distinct layers:
- Ingestion Layer: Parses raw IaC repositories and fetches live cloud states.
- Normalizing Layer: Converts disparate formats (Terraform HCL, CloudFormation YAML, AWS JSON) into a Universal Resource Model (URM).
- Analysis Layer: Constructs the graph and calculates differences (Diffing).
- Presentation Layer: Generates interactive documentation and diagrams.
graph LR
A[IaC Repo] --> B[Parser Module]
C[Cloud APIs] --> D[State Fetcher]
B --> E[Universal Resource Model]
D --> E
E --> F[Graph Engine]
F --> G[Diff Engine]
G --> H[Documentation Generator]
H --> I[Interactive UI / PDFs]
2. Component Design
A. The Polyglot Parser (IaC Ingestion)
Instead of writing parsers from scratch, this component leverages existing AST (Abstract Syntax Tree) generation tools to extract resource definitions.
- Terraform: Uses the
terraform-json library or parses the terraform plan -out=tfplan binary output. This ensures 100% accuracy regarding variable interpolation.
- CloudFormation: Leverages
cfn-lint or pyyaml to parse templates, resolving intrinsic functions (like !Ref and !GetAtt) logic to determine dependencies.
- Kubernetes: Parses Helm Charts or raw YAML manifests.
Output: A stream of JSON objects representing Intended Resources.
B. The State Fetcher (Reality Check)
This component queries cloud providers to discover the Actual Resources. To avoid hitting API rate limits, it uses a Regional Discovery Crawler.
- Strategy: Instead of listing all resources, it uses Resource Tagging APIs (e.g., AWS Resource Groups Tagging API) to find resources tagged with specific identifiers (like
managed-by: terraform).
- Caching: Stores raw API responses in Redis with a TTL (Time To Live) to facilitate rapid re-diffing without re-querying the cloud.
C. The Universal Resource Model (URM)
This is the core data structure that allows comparing a Terraform aws_instance with a live EC2 instance.
{
"id": "urn:aws:ec2:us-east-1:123456:instance/i-abc",
"type": "compute",
"provider": "aws",
"name": "web-server-01",
"attributes": {
"instance_type": "t3.micro",
"ami": "ami-12345",
"state": "running"
},
"dependencies": ["urn:aws:ec2:vpc/vpc-xyz", "urn:aws:iam:role/s3-access"]
}
3. The Dependency Graph Engine
This module builds a directional graph (DAG) to visualize relationships.
- Static Analysis (Code): Explicitly parses
depends_on blocks and implicit references (e.g., referencing a security group ID inside an instance resource).
- Dynamic Analysis (Live): Queries the cloud configuration aggregators (like AWS Config) to see which resources are actually attached to others.
Technology Stack: Neo4j (Graph Database).
- Nodes: Resources (Servers, DBs, Buckets).
- Edges: Relationships (
ATTACHED_TO, ROUTES_TO, SECURITY_GROUP).
Graph Logic:
// Example Cypher query to find impact analysis
MATCH (r:Resource {name: "main-db"})-[:DEPENDS_ON]->(dependency)
RETURN dependency
4. Real-Time State Diffing Engine
This is the core value proposition. It compares the Intended State (Code) vs. Actual State (Cloud).
Algorithm:
- Identity Mapping: Match code resources to live resources using unique identifiers (ARNs, IDs) or naming conventions/tags.
- Attribute Normalization: Cloud APIs often return calculated attributes (e.g.,
state_reason, public_ip). The engine filters these out to focus on user-configurable attributes (e.g., instance_type, disk_size).
- Classification:
- UNMANAGED: Exists in Cloud, not in Code (Drift/Orphan).
- MISSING: Exists in Code, not in Cloud (Destroyed externally).
- MODIFIED: Exists in both, but attributes differ.
Output:
{
"resource": "web-server",
"status": "MODIFIED",
"diff": [
{
"field": "instance_type",
"code": "t3.micro",
"cloud": "t3.large"
}
]
}
5. Documentation Generator
The documentation is generated dynamically based on the graph state.
- Visuals: Uses Cytoscape.js or React Flow on the frontend to render the graph interactively. Users can click a node to see the Diff.
- Markdown/HTML: Generates static files for ReadTheDocs/GitHub Wikis.
- Architecture Diagrams: Automatically generates Draw.io (XML) or MermaidJS diagrams.
Template Example (Jinja2):
# Infrastructure: {{ env.name }}
## Drift Detection
{% for resource in drifts %}
* **[WARN]** Resource `{{ resource.name }}` has drifted.
* Code: {{ resource.attr.code }}
* Cloud: {{ resource.attr.cloud }}
{% endfor %}
## Dependency Map
```mermaid
graph TD;
A[Load Balancer] --> B[Web Group];
B --> C[(Database)];
---
### 6. Proposed Tech Stack
* **Core Logic:** **Golang** (for high concurrency in parsing and cloud API fetching).
* **Graph Database:** **Neo4j** or **ArangoDB**.
* **Parser Libraries:**
* `python-hcl2` (for Terraform).
* `go-cloudformation` (for AWS).
* `goformit` (generic IaC parsing).
* **Frontend:** **React** + **D3.js** (for graph visualization).
* **CI/CD Integration:** A Docker container that runs within the build pipeline to generate docs as artifacts.
### 7. Advanced Features
1. **Predictive Impact Analysis:** Before a Pull Request is merged, the system parses the PR changes, applies them to the in-memory graph, and highlights which *other* resources will break due to dependency changes.
2. **Cost Estimation Hook:** Using the URM, map resources to pricing APIs (e.g., AWS Pricing API) to estimate the cost impact of the "Diff."
3. **Security Scoring:** If a Diff shows a security group opening port 80 to the world (`0.0.0.0/0`), flag it directly in the documentation.