Skip to content

Import Orphaned Resources #6

Import Orphaned Resources

Import Orphaned Resources #6

name: Import Orphaned Resources
on:
workflow_dispatch:
inputs:
confirmation:
description: 'Type "IMPORT" to proceed with importing resources'
required: true
default: ''
dry_run:
description: 'Run in dry-run mode (validate only, no actual imports)'
required: false
default: 'true'
type: choice
options:
- 'true'
- 'false'
SSH_PRIVATE_KEY:
description: 'The GitHub secret containing the SSH private key for terraform access'
required: true
default: 'SSH_PRIVATE_KEY'
env:
# Repository-level secrets for cloud credentials
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
jobs:
import-resources:
runs-on: ubuntu-latest
if: github.event.inputs.confirmation == 'IMPORT'
# Use dynamic environment based on current branch name
environment: ${{ github.ref_name }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
ref: testgrid
- name: Skip SSH Host key verification
run: |
mkdir -p ~/.ssh
echo -e "Host *\n StrictHostKeyChecking no" > ~/.ssh/config
- name: Setup ufw firewall
run: |
sudo ufw enable
sudo ufw allow ssh
sudo ufw allow 443/tcp
sudo ufw allow 51820/udp
sudo ufw status
- name: Install WireGuard
run: sudo apt-get install -y wireguard
- name: Configure WireGuard
run: |
# WG_CONFIG comes from environment-level secrets (dynamic based on branch name)
if [ -z "${{ secrets.TF_WG_CONFIG }}" ]; then
echo "❌ ERROR: TF_WG_CONFIG secret is not configured for environment '${{ github.ref_name }}'"
echo "Please configure the WireGuard configuration secret for this branch/environment"
exit 1
fi
# Debug: Check if secret is available (without exposing content)
echo "🔍 Checking TF_WG_CONFIG secret..."
if [ ${#TF_WG_CONFIG} -eq 0 ]; then
echo "❌ ERROR: TF_WG_CONFIG environment variable is empty"
echo "Secret may contain only whitespace or special characters"
exit 1
fi
echo "✅ Secret length: ${#TF_WG_CONFIG} characters"
# Create config file with proper handling of multiline content
echo "Creating /etc/wireguard directory with proper permissions..."
sudo mkdir -p /etc/wireguard
sudo chmod 755 /etc/wireguard
sudo chown root:root /etc/wireguard
# Write config directly with sudo
printf '%s' "$TF_WG_CONFIG" > /tmp/wg0.conf.tmp
sudo tee /etc/wireguard/wg0.conf < /tmp/wg0.conf.tmp > /dev/null
rm -f /tmp/wg0.conf.tmp
# Set proper permissions
sudo chmod 600 /etc/wireguard/wg0.conf
sudo chown root:root /etc/wireguard/wg0.conf
# Start WireGuard
echo "Starting WireGuard interface..."
sudo wg-quick up wg0
# Verify connection
echo "WireGuard status:"
sudo wg show
env:
TF_WG_CONFIG: ${{ secrets.TF_WG_CONFIG }}
- name: Setup Terraform
uses: hashicorp/setup-terraform@v2
with:
terraform_version: 1.5.0
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ap-south-1
- name: Terraform Init
run: |
cd terraform/implementations/aws/infra
echo "🔄 Initializing Terraform..."
terraform init
- name: Generate Resource Configurations
run: |
cd terraform/implementations/aws/infra
echo "📋 Generating terraform plan to understand resource structure..."
terraform plan -var-file="aws.tfvars" -out=plan.out || echo "Plan may fail due to missing resources - this is expected"
env:
TF_VAR_ssh_private_key: ${{ secrets[github.event.inputs.SSH_PRIVATE_KEY] }}
- name: Create Enhanced Import Script
run: |
cd terraform/implementations/aws/infra
echo "📝 Creating enhanced import script with error handling..."
cat > import_enhanced.sh << 'SCRIPT_END'
#!/bin/bash
set +e
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
imported_count=0
failed_count=0
import_resource() {
local tf_address="$1"
local aws_id="$2"
local description="$3"
echo -e "${YELLOW}Importing: $description${NC}"
echo " Terraform Address: $tf_address"
echo " AWS Resource ID: $aws_id"
if terraform import "$tf_address" "$aws_id" 2>/dev/null; then
echo -e "${GREEN}✅ Successfully imported: $description${NC}"
((imported_count++))
else
echo -e "${RED}❌ Failed to import: $description${NC}"
echo " Resource configuration may be missing or resource doesn't exist"
((failed_count++))
fi
echo ""
}
echo "=================================================="
echo "🔄 Starting Enhanced Import Process"
echo "This handles missing resource configurations gracefully"
echo "=================================================="
SCRIPT_END
# Append the original import commands
tail -n +30 ../../../../scripts/import_resources.sh >> import_enhanced.sh
# Add summary section
cat >> import_enhanced.sh << 'SUMMARY_END'
echo ""
echo "=================================================="
echo "📊 Enhanced Import Summary"
echo "=================================================="
echo -e "${GREEN}✅ Successfully imported: $imported_count resources${NC}"
echo -e "${RED}❌ Failed imports: $failed_count resources${NC}"
echo ""
if [ $imported_count -gt 0 ]; then
echo "Resources now in terraform state:"
terraform state list | sort
fi
SUMMARY_END
chmod +x import_enhanced.sh
- name: Execute Import Script
run: |
cd terraform/implementations/aws/infra
echo "📝 Copying original import script..."
cp ../../../../scripts/import_resources.sh ./
chmod +x import_resources.sh
if [ "${{ github.event.inputs.dry_run }}" == "true" ]; then
echo "🧪 DRY RUN MODE - Validating import commands"
sed 's/terraform import/echo "DRY RUN: terraform import"/g' import_resources.sh > import_dry.sh
chmod +x import_dry.sh
./import_dry.sh
else
echo "🚀 LIVE MODE - Performing imports with enhanced error handling"
./import_enhanced.sh
echo ""
echo "📊 Final resources in state: $(terraform state list | wc -l)"
fi
env:
TF_VAR_ssh_private_key: ${{ secrets[github.event.inputs.SSH_PRIVATE_KEY] }}
- name: Verify and Commit State
if: github.event.inputs.dry_run != 'true'
run: |
cd terraform/implementations/aws/infra
if [ -f terraform.tfstate ]; then
echo "✅ State file created: \$(du -h terraform.tfstate)"
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git add -f terraform.tfstate
git commit -s -m "Import orphaned resources - nginx server (15.206.88.253) and all infrastructure"
git push origin testgrid
echo "✅ State file committed successfully"
fi
- name: Summary
run: |
echo "=================================================="
if [ "${{ github.event.inputs.dry_run }}" == "true" ]; then
echo "🧪 DRY RUN COMPLETED - No changes made"
echo "Ready for live import (set dry_run=false)"
else
echo "✅ ENHANCED IMPORT COMPLETED"
echo "✅ Process handles missing resource configurations gracefully"
echo "✅ Resources successfully imported are now manageable"
echo "✅ NGINX server (15.206.88.253) recovery attempted"
echo "✅ Infrastructure recovery with error handling"
fi
echo "=================================================="