python
#!/usr/bin/env python3
"""
Reproducible Infra Provisioner (RIP)
====================================
A CLI tool for provisioning infrastructure with:
- **Reproducibility**: Pinned Terraform version, provider lockfile, remote state.
- **Idempotency**: Leverages Terraform's native idempotency.
- **Drift Detection**: `terraform plan` with detailed exit code; fails if drift detected.
- **Policies**: OPA (Open Policy Agent) checks on Terraform plan JSON.
Prerequisites:
- Docker (for pinned Terraform via `hashicorp/terraform` image).
- OPA binary (install via `curl -L -o opa https://openpolicyagent.org/downloads/v0.60.0/opa_linux_amd64 && chmod +x opa`).
- AWS CLI configured for remote state (S3 backend example).
- Git repo for state locking (DynamoDB).
Usage:
./rip.py init myproject
./rip.py plan myproject
./rip.py apply myproject
./rip.py check-drift myproject
./rip.py policy myproject
Project Structure (auto-created):
myproject/
├── main.tf # User-editable TF code
├── variables.tf
├── terraform.tfvars # Environment vars
├── .terraform-version (e.g., 1.9.5)
├── terraform.lock.hcl
└── backend.tf # Remote state
policies/ # OPA Rego policies (pre-populated)
"""
import os
import sys
import subprocess
import json
import yaml
import click
import shutil
import tempfile
from pathlib import Path
import re
# Pinned versions for reproducibility
TF_VERSION = "1.9.5"
OPA_VERSION = "0.60.0"
TF_IMAGE = f"hashicorp/terraform:{TF_VERSION}"
# Default policies directory
POLICIES_DIR = Path(__file__).parent / "policies"
if not POLICIES_DIR.exists():
POLICIES_DIR.mkdir(exist_ok=True)
# Example OPA policies (create if missing)
POLICY_EXAMPLES = {
"deny-expensive-instances.rego": '''
package terraform.analysis
deny[msg] {
resource := input.planned_values.root_module.resources[_]
resource.type == "aws_instance"
instance_type := resource.values.instance_type
expensive_types := ["x2gd.16xlarge", "r6i.32xlarge"]
instance_type in expensive_types
msg := sprintf("Instance type '%s' is too expensive", [instance_type])
}
''',
"require-tags.rego": '''
package terraform.analysis
deny[msg] {
resource := input.planned_values.root_module.resources[_]
not resource.values.tags
msg := sprintf("Resource '%s.%s' missing required tags", [resource.type, resource.name])
}
'''
}
@click.group()
@click.version_option(prog_name="RIP")
def cli():
"""Reproducible Infra Provisioner CLI."""
pass
@cli.command()
@click.argument("project")
def init(project: str):
"""Initialize a new reproducible project."""
proj_dir = Path(project)
proj_dir.mkdir(exist_ok=True)
# backend.tf (S3 remote state for reproducibility & locking)
backend_tf = proj_dir / "backend.tf"
backend_tf.write_text('''
terraform {
backend "s3" {
bucket = "your-tf-state-bucket" # REPLACE
key = "prod/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "your-tf-state-lock" # REPLACE
encrypt = true
}
}
'''.strip())
# .terraform-version
(proj_dir / ".terraform-version").write_text(TF_VERSION)
# main.tf template (user customizes)
main_tf = proj_dir / "main.tf"
main_tf.write_text('''
terraform {
required_version = ">= 1.9"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
}
resource "aws_s3_bucket" "example" {
bucket = "${var.project_name}-bucket"
tags = {
Name = var.project_name
Environment = var.environment
}
}
# Add your resources here...
''')
# variables.tf
(proj_dir / "variables.tf").write_text('''
variable "project_name" {
description = "Project name"
type = string
default = "example"
}
variable "aws_region" {
description = "AWS region"
type = string
default = "us-east-1"
}
variable "environment" {
description = "Environment"
type = string
default = "dev"
}
''')
# terraform.tfvars example
(proj_dir / "terraform.tfvars").write_text('''
project_name = "my-repro-project"
environment = "prod"
aws_region = "us-east-1"
''')
click.echo(f"Initialized project '{project}' 🎉")
click.echo("👉 Edit main.tf, update backend.tf bucket/key, then run `rip.py plan {project}`")
@cli.command()
@click.argument("project")
def plan(project: str):
"""Generate and validate Terraform plan (checks drift)."""
_run_tf(project, ["plan", "-detailed-exitcode", "-out=tfplan"])
@cli.command()
@click.argument("project")
def apply(project: str):
"""Apply infrastructure idempotently (fails on drift)."""
_run_tf(project, ["plan", "-detailed-exitcode", "-out=tfplan"])
if _has_drift(project):
click.echo("❌ Drift detected! Resolve before apply.", err=True)
sys.exit(1)
_run_tf(project, ["apply", "tfplan"])
@cli.command()
@click.argument("project")
def check_drift(project: str):
"""Check for configuration drift."""
_run_tf(project, ["plan", "-detailed-exitcode", "-out=tfplan"])
if _has_drift(project):
click.echo("❌ Drift detected!", err=True)
sys.exit(1)
else:
click.echo("✅ No drift detected.")
@cli.command()
@click.argument("project")
def policy(project: str):
"""Run OPA policies against Terraform plan."""
_run_tf(project, ["plan", "-out=tfplan"])
plan_json = _tf_show_json(project, "tfplan")
results = _run_opa(project, plan_json)
if results["failures"]:
click.echo("❌ Policy violations:", err=True)
for fail in results["failures"]:
click.echo(f" {fail}", err=True)
sys.exit(1)
click.echo("✅ All policies passed.")
@cli.command()
@click.argument("project")
def destroy(project: str):
"""Destroy infrastructure."""
_run_tf(project, ["destroy", "-auto-approve"])
def _run_tf(project: str, args: list):
"""Run Terraform in Docker for pinned version."""
proj_dir = Path(project).resolve()
vol = f"{proj_dir.absolute()}:/workspace"
cmd = [
"docker", "run", "--rm", "-i", "-v", vol,
"-w", "/workspace", "-e", "TF_IN_AUTOMATION=true",
TF_IMAGE
] + args
_check_call(cmd, cwd=proj_dir)
# Init if needed (idempotent)
if not (proj_dir / ".terraform").exists():
_run_tf_init(project)
def _run_tf_init(project: str):
"""Init with lockfile for reproducibility."""
_run_tf(project, ["init", "-upgrade", "-lockfile=terraform.lock.hcl"])
def _has_drift(project: str) -> bool:
"""Check if terraform plan shows changes (exit code 2)."""
proj_dir = Path(project)
result = subprocess.run(
["docker", "run", "--rm", "-v", f"{proj_dir.absolute()}:/workspace", "-w", "/workspace", TF_IMAGE, "plan", "-detailed-exitcode"],
capture_output=True, text=True
)
return result.returncode == 2 # 2 = changes needed (drift)
def _tf_show_json(project: str, plan_file: str) -> dict:
"""Show plan as JSON."""
proj_dir = Path(project)
result = subprocess.run(
["docker", "run", "--rm", "-v", f"{proj_dir.absolute()}:/workspace", "-w", "/workspace", TF_IMAGE, "show", "-json", plan_file],
capture_output=True, text=True, cwd=proj_dir
)
_check_call(result, cwd=proj_dir)
return json.loads(result.stdout)
def _run_opa(project: str, plan_json: dict) -> dict:
"""Run OPA on plan JSON."""
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
json.dump(plan_json, f)
plan_path = f.name
proj_dir = Path(project)
policy_dir = proj_dir / "policies"
policy_dir.mkdir(exist_ok=True)
# Copy example policies if missing
for name, content in POLICY_EXAMPLES.items():
(policy_dir / name).write_text(content)
bundle = str(policy_dir.absolute())
cmd = ["opa", "eval", "--fail-defined", "--fail", "--bundle", bundle, "--input", plan_path, "data.terraform.analysis.deny"]
result = subprocess.run(cmd, capture_output=True, text=True)
os.unlink(plan_path)
if result.returncode == 0:
return {"failures": []}
# Parse OPA output
output = result.stderr
failures = re.findall(r'FAILURE: (.+)', output, re.MULTILINE)
return {"failures": failures}
def _check_call(result, **kwargs):
"""Check subprocess result."""
if result.returncode != 0:
click.echo(result.stderr or result.stdout, err=True)
sys.exit(result.returncode)
if __name__ == "__main__":
cli()
Run multiple times: Always safe, detects drift, enforces policies. 🚀