Skip to content

Latest commit

 

History

History
265 lines (197 loc) · 6.27 KB

File metadata and controls

265 lines (197 loc) · 6.27 KB

Terraform Wrapper Script

Overview

The terraform-wrapper.sh script automatically manages the terraprem backend by:

  1. Detecting backend "terraprem" in your Terraform configuration
  2. Starting kubectl port-forward automatically
  3. Temporarily rewriting the config to use backend "remote"
  4. Running the terraform command
  5. Restoring the original configuration
  6. Stopping the port-forward

Result: Users just run terraform init and everything works automatically!

Installation

Option 1: Replace terraform binary (Recommended)

# Backup existing terraform (optional)
mv ~/.local/bin/terraform ~/.local/bin/terraform-real

# Install wrapper
cp scripts/terraform-wrapper.sh ~/.local/bin/terraform
chmod +x ~/.local/bin/terraform

# Ensure ~/.local/bin is in PATH
export PATH="$HOME/.local/bin:$PATH"

Option 2: Create alias

# Add to ~/.bashrc or ~/.zshrc
alias terraform='$HOME/Documents/Projects/TfCloudCopy/scripts/terraform-wrapper.sh'

Option 3: Symlink

ln -s $HOME/Documents/Projects/TfCloudCopy/scripts/terraform-wrapper.sh ~/.local/bin/terraform

Usage

1. Configure Backend

In your main.tf (or any .tf file):

terraform {
  backend "terraprem" {
    k8s_context = "your-k8s-context"  # Required
    namespace   = "terraprem"          # Required (default: "terraprem")
    service     = "terraprem-backend"  # Required
    local_port  = 8080                 # Optional (default: 8080)
    remote_port = 8080                 # Optional (default: 8080)
    organization = "terraprem"         # Required
    workspaces {
      name = "my-workspace"            # Required
    }
  }
}

2. Run Terraform

Just run terraform commands normally:

terraform init
terraform plan
terraform apply

The wrapper automatically:

  • Detects the backend "terraprem" configuration
  • Starts kubectl port-forward
  • Rewrites config to backend "remote"
  • Runs the terraform command
  • Restores original config
  • Stops port-forward

How It Works

Detection

The wrapper scans all .tf files in the current directory for backend "terraprem" blocks.

Port-Forward Management

  • Starts kubectl port-forward svc/<service> <local_port>:<remote_port> -n <namespace> --context <k8s_context>
  • Waits for port to be ready (checks with nc or curl)
  • Stores PID in /tmp/terraprem-port-forward.pid
  • Stops on script exit (handles Ctrl+C gracefully)

Config Hot-Swap

  1. Backup: All .tf files are backed up to /tmp/terraprem-backup-<timestamp>/
  2. Rewrite: Backend block is rewritten from backend "terraprem" to backend "remote" with:
    • hostname = "localhost:<local_port>"
    • organization = "<organization>"
    • workspaces { name = "<workspace>" }
  3. Execute: Terraform runs with the rewritten config
  4. Restore: Original files are restored from backup

Cleanup

The wrapper always cleans up on exit:

  • Stops port-forward process
  • Restores original .tf files
  • Removes backup directories
  • Preserves terraform exit code

Configuration Options

Required Fields

  • k8s_context - Kubernetes context name
  • service - Kubernetes service name
  • organization - Terraform organization
  • workspace - Workspace name (in workspaces { name = "..." })

Optional Fields

  • namespace - Kubernetes namespace (default: "terraprem")
  • local_port - Local port for port-forward (default: 8080)
  • remote_port - Remote port on service (default: 8080)

Error Handling

The wrapper handles various error scenarios:

  1. Missing required fields: Shows which field is missing
  2. Port already in use: Checks before starting port-forward
  3. kubectl not found: Validates kubectl is installed
  4. Port-forward fails: Shows error and exits
  5. Config parsing fails: Shows parsing error
  6. Interrupt (Ctrl+C): Cleans up everything gracefully

Troubleshooting

Port Already in Use

If you see "Port X is already in use":

# Check what's using the port
lsof -ti:8080

# Kill the process
kill $(lsof -ti:8080)

kubectl Not Found

Make sure kubectl is installed and in PATH:

which kubectl
kubectl version --client

Config Not Detected

  • Ensure backend "terraprem" is in a .tf file in the current directory
  • Check for typos: backend "terraprem" (not backend "terraprem" or backend terraprem)
  • Ensure the backend block is inside a terraform {} block

Port-Forward Dies

Check the logs:

cat /tmp/terraprem-port-forward.log

Verify Kubernetes access:

kubectl get svc -n terraprem terraprem-backend

Files Not Restored

If something goes wrong, backups are in /tmp/terraprem-backup-*/:

ls -la /tmp/terraprem-backup-*

Examples

Basic Configuration

terraform {
  backend "terraprem" {
    k8s_context = "my-context"
    namespace   = "terraprem"
    service     = "terraprem-backend"
    organization = "terraprem"
    workspaces {
      name = "prod"
    }
  }
}

Custom Ports

terraform {
  backend "terraprem" {
    k8s_context = "my-context"
    namespace   = "terraprem"
    service     = "terraprem-backend"
    local_port  = 9090  # Custom local port
    remote_port = 8080
    organization = "terraprem"
    workspaces {
      name = "prod"
    }
  }
}

Comparison

Before (Manual)

# Terminal 1
kubectl port-forward -n terraprem svc/terraprem-backend 8080:8080

# Terminal 2
terraform init
terraform apply

After (Automatic)

# Just one command!
terraform init
terraform apply

Dependencies

  • kubectl - Must be in PATH
  • terraform - Real terraform binary (found automatically)
  • nc or curl - For port checking
  • Standard Unix tools: grep, sed, awk

Limitations

  1. HCL Parsing: Uses simple regex/awk parsing. Complex HCL with unusual formatting may not parse correctly.
  2. Single Backend: Only handles one backend "terraprem" block per directory.
  3. Port Conflicts: Doesn't handle port conflicts automatically (shows error).
  4. Multiple Terraform Commands: Port-forward stays alive between commands (by design).

Future Enhancements

  • Better HCL parsing (use HCL library)
  • Handle multiple backend blocks
  • Auto-detect and reuse existing port-forwards
  • Support for backend config in separate files
  • Better error messages with line numbers