Skip to main content

OpenTofu Import - Quick Start Guide

Created: December 1, 2025 Purpose: Automated import of staging infrastructure into OpenTofu


🚀 One-Command Import

cd /Users/halcasteel/PROJECTS/coditect-rollout-master/submodules/cloud/coditect-cloud-infra/opentofu/environments/backend-staging

./import-infrastructure.sh

That's it! The script handles everything automatically.


What the Script Does

1. Prerequisites Check ✅

  • Verifies gcloud CLI installed
  • Verifies tofu (OpenTofu) installed

2. Authentication 🔐

  • Checks if you're logged into GCP
  • Prompts for gcloud auth login if needed
  • Configures application default credentials (interactive browser auth)
  • Sets project to coditect-cloud-infra

3. OpenTofu Initialization 🏗️

  • Runs tofu init (downloads providers)
  • Skips if already initialized

4. Resource Import 📥

Imports these resources automatically:

  • ✅ Cloud SQL Instance: coditect-db
  • ✅ Cloud SQL Database: coditect
  • ✅ Cloud SQL User: coditect_app
  • ✅ Redis Instance: coditect-redis-staging

Smart Import: Skips resources already imported (idempotent)

5. Validation ✓

  • Runs tofu plan
  • Expected result: Zero changes (perfect match)
  • Shows any drift if detected

6. Remote State Setup (Optional) ☁️

  • Creates GCS bucket: coditect-terraform-state
  • Migrates state from local to GCS
  • Enables versioning for safety

7. Completion Report 📊

  • Shows all imported resources
  • Displays next steps
  • Provides Git commit command

Expected Output

========================================
OpenTofu Infrastructure Import
========================================

[INFO] CODITECT Cloud Backend - Staging Environment
[INFO] Project: coditect-cloud-infra
[INFO] Region: us-central1

========================================
Checking Prerequisites
========================================

[SUCCESS] gcloud CLI found: Google Cloud SDK 450.0.0
[SUCCESS] OpenTofu found: OpenTofu v1.6.7

========================================
Checking GCP Authentication
========================================

[SUCCESS] Authenticated as: 1@az1.ai
[SUCCESS] Project configured: coditect-cloud-infra
[SUCCESS] Application default credentials are valid

========================================
Initializing OpenTofu
========================================

[INFO] OpenTofu already initialized

========================================
Importing Infrastructure Resources
========================================

[INFO] Importing Cloud SQL Instance (coditect-db): coditect-cloud-infra/coditect-db
[SUCCESS] Cloud SQL Instance (coditect-db) imported successfully

[INFO] Importing Cloud SQL Database (coditect): coditect-cloud-infra/coditect-db/coditect
[SUCCESS] Cloud SQL Database (coditect) imported successfully

[INFO] Importing Cloud SQL User (coditect_app): coditect-cloud-infra/coditect-db/coditect_app
[SUCCESS] Cloud SQL User (coditect_app) imported successfully

[INFO] Importing Redis Instance (coditect-redis-staging): coditect-cloud-infra/us-central1/coditect-redis-staging
[SUCCESS] Redis Instance (coditect-redis-staging) imported successfully

[SUCCESS] All resources imported successfully!

========================================
Validating Import (Zero-Change Test)
========================================

[INFO] Running: tofu plan

[SUCCESS] ✅ VALIDATION PASSED: No changes detected!
[INFO] Infrastructure matches OpenTofu configuration perfectly.

========================================
Current OpenTofu State
========================================

[INFO] Imported resources:
google_redis_instance.coditect_redis
google_sql_database.coditect
google_sql_database_instance.coditect_db
google_sql_user.coditect_app

========================================
Remote State Backend Configuration
========================================

[INFO] Remote state backend configuration (optional)
[INFO] Bucket: gs://coditect-terraform-state
[INFO] Prefix: backend-staging

Configure remote state backend now? (y/N) y

[SUCCESS] Bucket exists: gs://coditect-terraform-state
[SUCCESS] providers.tf updated
[INFO] Migrating local state to GCS...
[SUCCESS] State migrated to GCS successfully

========================================
Migration Complete - Summary Report
========================================

╔════════════════════════════════════════════════════════════════╗
║ OpenTofu Infrastructure Migration Complete ║
╚════════════════════════════════════════════════════════════════╝

Resources Imported:
✅ Cloud SQL Instance: coditect-db
✅ Cloud SQL Database: coditect
✅ Cloud SQL User: coditect_app
✅ Redis Instance: coditect-redis-staging

Configuration Files:
📄 providers.tf - Provider and backend configuration
📄 variables.tf - Variable declarations
📄 main.tf - Resource definitions
📄 README.md - Documentation

Next Steps:
1. Review OpenTofu state: tofu state list
2. Verify configuration: tofu plan
3. Make infrastructure changes via OpenTofu (not manual gcloud)
4. Commit to Git:
cd /Users/halcasteel/PROJECTS/.../backend-staging
git add .
git commit -m "feat: Add OpenTofu backend-staging configuration"

[SUCCESS] Migration completed successfully! 🎉

Troubleshooting

Authentication Fails

Problem: gcloud auth application-default login fails

Solution:

# Clear existing credentials
rm -f ~/.config/gcloud/application_default_credentials.json

# Re-run script
./import-infrastructure.sh

Import Fails (Resource Not Found)

Problem: Error: Resource not found

Solution: Verify resource exists:

# Check Cloud SQL
gcloud sql instances list

# Check Redis
gcloud redis instances list --region=us-central1

# Update resource names in main.tf if needed

Validation Shows Changes

Problem: tofu plan shows changes after import

Cause: Expected on first import due to computed values

Solution:

  1. Review changes carefully
  2. If minor (IPs, timestamps), this is normal
  3. If major (resource recreation), check configuration matches actual resources
  4. Update main.tf to match actual configuration exactly

Permission Denied

Problem: Error 403: Permission denied

Solution:

# Verify you have necessary IAM roles
gcloud projects get-iam-policy coditect-cloud-infra \
--flatten="bindings[].members" \
--filter="bindings.members:user:1@az1.ai"

# Required roles:
# - roles/editor (or specific roles for SQL, Redis, Compute)

Manual Steps (If Script Fails)

If the automated script encounters issues, you can run steps manually:

# 1. Authenticate
gcloud auth login
gcloud auth application-default login
gcloud config set project coditect-cloud-infra

# 2. Navigate to directory
cd /Users/halcasteel/PROJECTS/coditect-rollout-master/submodules/cloud/coditect-cloud-infra/opentofu/environments/backend-staging

# 3. Initialize
tofu init

# 4. Import resources one by one
tofu import google_sql_database_instance.coditect_db coditect-cloud-infra/coditect-db
tofu import google_sql_database.coditect coditect-cloud-infra/coditect-db/coditect
tofu import google_sql_user.coditect_app coditect-cloud-infra/coditect-db/coditect_app
tofu import google_redis_instance.coditect_redis coditect-cloud-infra/us-central1/coditect-redis-staging

# 5. Validate
tofu plan

# 6. Check state
tofu state list

Post-Import Operations

View Resource Details

# List all resources
tofu state list

# Show specific resource
tofu state show google_sql_database_instance.coditect_db

# Show Redis details
tofu state show google_redis_instance.coditect_redis

Check for Drift

# Should show "No changes"
tofu plan

Make Infrastructure Changes

# Edit configuration
vim main.tf

# Preview changes
tofu plan

# Apply changes
tofu apply

Script Features

✅ Idempotent

  • Safe to run multiple times
  • Skips already-imported resources
  • Won't overwrite existing state

✅ Interactive Where Needed

  • Prompts for authentication if required
  • Asks before configuring remote state
  • Confirms changes if drift detected

✅ Comprehensive Error Handling

  • Validates prerequisites
  • Checks authentication
  • Provides clear error messages
  • Exits safely on failures

✅ Detailed Logging

  • Color-coded output (info, success, warning, error)
  • Progress indicators
  • Completion report

Time Estimate

Total Time: 5-10 minutes (depending on authentication)

StepTime
Prerequisites check10 seconds
Authentication1-2 minutes (if needed)
Initialization30 seconds
Import (4 resources)2-3 minutes
Validation30 seconds
Remote state (optional)1-2 minutes
Total5-10 minutes

Success Criteria

After running the script, you should have:

✅ All 4 resources imported into OpenTofu state ✅ tofu plan shows zero changes ✅ State stored in GCS (if remote state configured) ✅ Configuration files committed to Git


  • opentofu-migration-next-steps.md - Complete migration strategy (22KB)
  • backend-staging/README.md - Environment operations guide
  • staging-quick-reference.md - Staging infrastructure reference

Script Location:

/Users/halcasteel/PROJECTS/coditect-rollout-master/submodules/cloud/coditect-cloud-infra/opentofu/environments/backend-staging/import-infrastructure.sh

Created: December 1, 2025 Status: Ready to run Automation Level: 95% (only interactive browser auth required)