simpleterraform 1.0.5
Automated Infrastructure as Code Generator
Requires Python: >=3.7


# ⚡ SimpleTerraform 
**❤️ By Sourav Kumar Singh**
**Email:** 1109souravkumar@gmail.com

> **Automated Infrastructure-as-Code (IaC) Generator**
> 
> Build production-ready Terraform modules in seconds using an interactive CLI.

![Python](https://img.shields.io/badge/Python-3.7%2B-blue.svg)
![Terraform](https://img.shields.io/badge/Terraform-1.0%2B-purple.svg)

**SimpleTerraform** removes the boilerplate from Terraform. Instead of writing hundreds of lines of HCL from scratch, answer a few questions in your terminal, and let the tool generate best-practice infrastructure for you.

---

## 🚀 Features

* **Interactive UI:** Beautiful terminal interface with arrow-key navigation and validation.
* **Modular Architecture:** Generates clean, reusable Terraform modules.
* **Smart Linking:** Automatically detects dependencies (e.g., links EC2 instances to your specific VPCs).
* **Validation:** Prevents errors before they happen (validates CIDRs, S3 names, AMI formats).
* **State Management:** Saves your configuration to JSON so you can regenerate or modify later without re-typing everything.

## 📦 Installation

### Option 1: Install via PyPI (Recommended)
```bash
pip install simpleterraform
```

-----

## 🏗️ Usage

Once installed, simply run the command:

```bash
simpleterraform
```

### The Workflow

1.  **Start the tool:** You will see the main menu.
2.  **Generate Networking:** Start by creating a VPC (Networking module).
3.  **Add Layers:** Add Security Groups, Compute, Databases, or Kubernetes clusters.
4.  **Deploy:** The tool generates a `root/` folder with `main.tf`.

<!-- end list -->

```bash
cd root
terraform init
terraform apply
```

-----

## 🏗️ System Architecture

Understanding how SimpleTerraform works under the hood helps you utilize it better. It follows a **Model-View-Controller (MVC)** pattern adapted for a CLI.

[Image of software architecture diagram]

1.  **Input Layer (UI):** Captures user intent via interactive prompts (`questionary`).
2.  **Validation Layer (Model):** Strictly validates data (CIDR ranges, naming conventions) using `Pydantic`.
3.  **State Layer:** Persists valid configurations into `metadata/<project>.json`.
4.  **Generator Layer:** Reads the JSON state and renders Jinja2 templates into valid Terraform (`.tf`) files.

-----

## ⚠️ Important Warnings & Best Practices

While this tool automates code generation, Infrastructure-as-Code requires careful management.

1.  **Always Audit the Code:**

      * The tool generates standard Terraform code. **Always** review the generated `.tf` files in `root/` and `terraform_modules/` before running `apply`.
      * Ensure the instance types and scaling limits fit your budget.

2.  **Terraform Plan is Mandatory:**

      * Never run `terraform apply` blindly. Always run `terraform plan` first to see exactly what AWS resources will be created, modified, or destroyed.

3.  **State Management:**

      * This tool generates a **local** Terraform state setup. For production teams, you should manually configure a **Remote Backend** (S3 + DynamoDB) in the generated `root/main.tf` file to handle state locking.

4.  **Cost Implications:**

      * Resources like NAT Gateways, Application Load Balancers, and RDS instances cost money per hour. Remember to `terraform destroy` if you are just testing.

-----

## 📏 Operational Rules

To ensure the tool works correctly, follow these rules:

1.  **Dependency Order Matters:**

      * You cannot create an **EC2 Instance** without a **Network**.
      * You cannot create a **Load Balancer** without **Security Groups**.
      * *The Tool will block you if you try to skip steps, but keep this logical flow in mind.*

2.  **Do Not Edit Metadata Manually:**

      * The files inside `metadata/` are the source of truth for the generator. If you edit them manually and make a syntax error, the tool may fail to load your project.

3.  **Regeneration Overwrites:**

      * If you run the generator again for the same project, it will overwrite the `.tf` files. If you made manual changes to the *generated* files, they will be lost. **Make your changes via the CLI tool whenever possible.**

-----

## 🔮 What You Can Do From Here

The generated code is a **foundation**. Here is how you can take it to the next level:

  * **Integration with CI/CD:** Commit the generated `root/` and `terraform_modules/` folders to GitHub/GitLab and set up a pipeline to deploy automatically.
  * **Add Custom Providers:** The tool defaults to `us-east-1`. You can easily change the `provider "aws"` block in `root/main.tf` to deploy to other regions or add providers like Cloudflare or Datadog.
  * **Secret Management:** The tool accepts passwords for RDS. For production, replace these hardcoded strings in `main.tf` with references to **AWS Secrets Manager** or **Terraform Variables**.

-----

## 🛡️ Supported Modules

| Module | Description | Key Features |
| :--- | :--- | :--- |
| **Networking** | VPC, Subnets, IGW, NAT | Automatic subnet calculation, Multi-AZ support. |
| **Security** | Security Groups | Rule descriptions, Ingress/Egress management. |
| **Compute** | EC2 Instances | Root volume encryption, Public/Private placement. |
| **Auto Scaling** | ASG & Launch Templates | Dynamic scaling policies, Health checks. |
| **EKS** | Kubernetes Clusters | Managed Node Groups, IAM Roles handling. |
| **ECS** | Fargate Clusters | Serverless containers, Task Definitions. |
| **Database** | RDS (Postgres/MySQL) | Storage encryption, Multi-AZ, Subnet groups. |
| **Load Balancer** | ALB | HTTP-\>HTTPS redirection, Target Groups. |
| **Storage** | S3 Buckets | Versioning, Server-side encryption, Public access block. |
| **IAM** | Roles & Policies | Least privilege policy builder. |
| **Monitoring** | CloudWatch & SNS | Alarms for CPU, Database connections, and 5xx errors. |

-----

## 📂 Project Structure

When you run the tool, it creates the following structure in your working directory:

```text
.
├── metadata/               # JSON files storing your answers (The State)
├── terraform_modules/      # Generated reusable modules (The Logic)
│   ├── my-project-networking-1/
│   ├── my-project-security-1/
│   └── ...
└── root/                   # The entry point for Terraform
    ├── main.tf             # Connects all modules together
    ├── variables.tf
    └── outputs.tf
```

---

# System Overview

The architecture is divided into three distinct planes:
1.  **The Interaction Plane:** Captures and validates user intent.
2.  **The State Plane:** The persistent "Source of Truth."
3.  **The Execution Plane:** The engine that reconciles state into infrastructure code.

## Component Breakdown

### A. The Interface Gateway (CLI Controller)
* **Component:** `main.py` & `ui.py`
* **Role:** The entry point for all operations.
* **Function:** It acts as the API Server for the system. It routes user requests (Generate, View, Exit) to the appropriate logic handlers. It does not process data itself; it delegates tasks to the underlying controllers.

### B. The Admission Controller (Validation Engine)
* **Component:** `src/models.py` (Pydantic)
* **Role:** The Guardrails.
* **Function:** Before any data is persisted to the state, it passes through this layer. It enforces strict schema rules (e.g., CIDR format, S3 naming conventions, dependency existence). If the data violates the schema, it is rejected immediately, preventing corruption of the state.

### C. The Persistent State Store (Source of Truth)
* **Component:** `metadata/*.json`
* **Role:** The Database.
* **Function:** This is the immutable record of the infrastructure. Unlike typical scripts that "fire and forget," this system saves the user's intent. This allows for idempotency—running the tool multiple times produces the exact same result without duplication.

### D. The Reconciliation Engine (The Generator)
* **Component:** `src/generator.py`
* **Role:** The Operator.
* **Function:** This component runs a continuous reconciliation loop.
    1.  **Watch:** It reads the current configuration from the **State Store**.
    2.  **Diff:** It determines which modules need to be created or updated.
    3.  **Act:** It loads the appropriate **Blueprints** and renders the final Terraform code to the disk.

### E. The Blueprint Store (Template Repository)
* **Component:** `templates/**/*.j2`
* **Role:** The Spec Definitions.
* **Function:** These are logic-less, parameterized definitions of resources. They define the "Gold Standard" of how infrastructure should look. The Reconciliation Engine hydrates these blueprints with data from the State Store.

---

### 3. The Data Flow (The Lifecycle of a Request)

1.  **Gateway:** The User initiates a request via the **Interface Gateway**.
2.  **Validation:** The input is sent to the **Admission Controller**. If invalid, it returns an error.
3.  **Persistence:** Validated data is committed to the **Persistent State Store**.
4.  **Trigger:** The commit triggers the **Reconciliation Engine**.
5.  **Render:** The Engine pulls data from the State Store and schemas from the **Blueprint Store**.
6.  **Output:** The system writes the final artifacts (`.tf` files) to the `root/` and `terraform_modules/` directories.

---

### 4. Key Architectural Principles

* **Declarative Configuration:** The system focuses on the desired end-state (stored in JSON), not the step-by-step commands to get there.
* **Idempotency:** You can run the generator 100 times; if the State Store hasn't changed, the output code remains consistent.
* **Decoupled Logic:** The templates (how code looks) are completely separated from the Python logic (how data is collected). This allows you to update Terraform versions in the templates without touching the Python codebase.
* **Self-Healing Output:** If a user accidentally deletes a generated `.tf` file, running the generator again immediately restores it from the State Store.