Files
roa2web-service-auto/deployment/windows/docs/DEPLOYMENT_AUTOMATION.md
Marius Mutu 87859e5510 Add deployment automation system with build/publish workflow and fix path resolution
This commit introduces a complete deployment automation system for Windows Server deployment:

New Features:
- Publish-And-Deploy.ps1: Interactive console for building locally and transferring to server
  * Supports auto-detection of transfer method (Windows Share or SSH)
  * Configurable via deploy-config.json
  * Integrated with Build-ROA2WEB.ps1 for consistent builds
- Check-And-Deploy.ps1: Server-side auto-deployment script
  * Monitors transfer directory for new packages
  * Automatically deploys when new version detected
  * Integrates with ROA2WEB-Console.ps1 for deployment
- Setup-AutoDeploy.ps1: Configures scheduled task for auto-deployment
- DEPLOYMENT_AUTOMATION.md: Complete documentation for automation workflow

Bug Fixes:
- Fix path resolution in Publish-And-Deploy.ps1: Added Resolve-FullPath function to correctly resolve ../deploy-package path
- Fix ROA2WEB-Console.ps1 exit codes: Properly return boolean values and exit codes in non-interactive mode
- Fix Build-ROA2WEB.ps1 script copying: Added debug output and force deletion to avoid caching issues

Enhancements:
- ROA2WEB-Console.ps1: Support for ROA2WEB_SOURCE environment variable for flexible source paths
- Build-ROA2WEB.ps1: Enhanced debug output for troubleshooting script copying issues

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-14 14:59:47 +02:00

22 KiB

ROA2WEB - Automated Deployment System

📋 Overview

This document describes the automated deployment system for ROA2WEB Windows Server deployment. The system enables:

  • Build locally on dev machine (WSL/Windows)
  • Auto-transfer via Windows Share (LAN) or SSH (remote)
  • Auto-deploy on server (no manual intervention needed)
  • Interactive menus for easy configuration
  • No Remote Desktop required

🏗️ Architecture

┌─────────────────────────────────────────────────────────────────┐
│ Dev Machine (WSL/Windows)                                       │
│                                                                  │
│  Publish-And-Deploy.ps1 (Interactive Menu)                     │
│    ├─ Load deploy-config.json                                  │
│    ├─ Build-ROA2WEB.ps1 (create deploy-package/)              │
│    └─ Transfer:                                                 │
│       ├─ Auto: Try Windows Share → fallback SSH                │
│       ├─ Windows Share: \\10.0.20.36\ROA2WEB-Deploy           │
│       └─ SSH: scp to 10.0.20.36:22122                         │
└─────────────────────────────────────────────────────────────────┘
                             │
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│ Windows Server                                                   │
│                                                                  │
│  C:\Temp\                                                        │
│    └─ deploy-20241112-153045\                                  │
│       ├─ backend/                                               │
│       ├─ frontend/                                              │
│       ├─ telegram-bot/                                          │
│       └─ scripts/ROA2WEB-Console.ps1                           │
└─────────────────────────────────────────────────────────────────┘
                             │
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│ Scheduled Task: ROA2WEB-AutoDeploy (every 5 minutes)           │
│                                                                  │
│  Check-And-Deploy.ps1                                           │
│    ├─ Scan C:\Temp\ for deploy-* folders                       │
│    ├─ Find newest package (by LastWriteTime)                   │
│    ├─ Compare with last-deploy.json                            │
│    └─ If newer:                                                 │
│       ├─ Set $env:ROA2WEB_SOURCE = package path                │
│       ├─ Execute ROA2WEB-Console.ps1 -Action DeployAll         │
│       └─ Update last-deploy.json                               │
└─────────────────────────────────────────────────────────────────┘

🚀 Quick Start Guide

Dev Machine Setup (One-Time)

  1. Edit Configuration (optional, defaults are provided):
cd deployment/windows/scripts
notepad deploy-config.json

Default configuration:

{
  "server": {
    "host": "10.0.20.36",
    "sshPort": 22122,
    "sshUser": "Administrator",
    "sshKeyPath": "~\\.ssh\\id_ed25519",
    "windowsShare": "\\\\10.0.20.36\\Temp"
  }
}
  1. Test Connections:
.\Publish-And-Deploy.ps1
# Menu: [2] Test Connections

Server Setup (One-Time)

  1. Windows Share (already exists):
# Share already exists: \\10.0.20.36\Temp
# Maps to: C:\Temp on server

# Create scripts directory (if not exists)
New-Item -Path "C:\Temp\ROA2WEB-Scripts" -ItemType Directory -Force
  1. Run Setup Wizard:
# Copy Setup-AutoDeploy.ps1 to server, then:
cd C:\path\to\scripts
.\Setup-AutoDeploy.ps1

The wizard will:

  • Create directory structure (C:\Temp, C:\Temp\ROA2WEB-Scripts)
  • Copy Check-And-Deploy.ps1 to scripts folder
  • Create Scheduled Task (ROA2WEB-AutoDeploy)
  • Configure auto-deploy (every 5 minutes)

📖 Usage

Interactive Deployment (Dev Machine)

cd deployment/windows/scripts
.\Publish-And-Deploy.ps1

Main Menu:

[1] Build & Publish Package
    → Select Component (All/Frontend/Backend/TelegramBot)
    → Select Transfer Method (Auto/WindowsShare/SSH)
    → Build + Transfer automatically

[2] Test Connections
    → Test Windows Share accessibility
    → Test SSH connection

[3] Configure Settings
    → Edit server host, SSH port, paths, etc.

[4] View Current Configuration
    → Display active settings

[Q] Quit

Non-Interactive Deployment (Dev Machine)

# Quick deploy (auto-detect transfer method)
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component All

# Force Windows Share (LAN)
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component All -TransferMethod WindowsShare

# Force SSH (remote/WAN)
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component Frontend -TransferMethod SSH

# Test connections only
.\Publish-And-Deploy.ps1 -NonInteractive -Action TestConnections

Server-Side Management

Manual Check & Deploy (Server)

cd C:\ROA2WEB-Scripts

# Interactive menu
.\Check-And-Deploy.ps1 -Interactive

# Non-interactive check + deploy
.\Check-And-Deploy.ps1

# Check only (no deploy)
.\Check-And-Deploy.ps1 -CheckOnly

Manage Scheduled Task (Server)

# View task
Get-ScheduledTask -TaskName "ROA2WEB-AutoDeploy"

# Start task manually (trigger check now)
Start-ScheduledTask -TaskName "ROA2WEB-AutoDeploy"

# Disable auto-deploy temporarily
Disable-ScheduledTask -TaskName "ROA2WEB-AutoDeploy"

# Re-enable auto-deploy
Enable-ScheduledTask -TaskName "ROA2WEB-AutoDeploy"

# View logs
Get-Content "C:\ROA2WEB-Scripts\Logs\check-and-deploy.log" -Tail 50

📁 File Structure

Dev Machine

deployment/windows/scripts/
├── deploy-config.json           # Configuration file (edit server settings)
├── Publish-And-Deploy.ps1       # Interactive build & publish script
├── Build-ROA2WEB.ps1           # Existing build script (unchanged)
├── ROA2WEB-Console.ps1         # Existing deployment script (updated)
└── Setup-AutoDeploy.ps1        # Server setup wizard

Server

C:\Temp\                                    # Monitored folder (Windows Share)
├── ROA2WEB-Scripts\                       # Scripts and state (permanent)
│   ├── Check-And-Deploy.ps1               # Monitoring script (runs via scheduled task)
│   ├── Setup-AutoDeploy.ps1               # Setup wizard (optional, for debug)
│   ├── last-deploy.json                   # Tracks last deployed package
│   └── Logs\
│       └── check-and-deploy.log           # Deployment logs
│
├── deploy-20241112-153045\               # Timestamped deployment packages
│   ├── backend/
│   ├── frontend/
│   ├── telegram-bot/
│   └── scripts/
│       └── ROA2WEB-Console.ps1
│
└── deploy-20241111-120000\               # Previous package (kept as backup)

🔧 Configuration Reference

deploy-config.json

{
  "server": {
    "host": "10.0.20.36",                          // Server IP/hostname
    "sshPort": 22122,                              // SSH port
    "sshUser": "Administrator",                    // SSH username
    "sshKeyPath": "~\\.ssh\\id_ed25519",          // SSH private key path
    "windowsShare": "\\\\10.0.20.36\\Temp",       // Network share path
    "deployPath": "C:\\Temp"                       // Server-side deploy path
  },
  "build": {
    "defaultComponent": "All",                     // Default: All/Frontend/Backend/TelegramBot
    "outputPath": "./deploy-package"               // Local build output
  },
  "transfer": {
    "defaultMethod": "Auto",                       // Auto/WindowsShare/SSH
    "scpRemotePath": "C:/Temp",                    // SCP remote path (Windows format)
    "retryAttempts": 3,                            // Transfer retry attempts
    "timeout": 300                                 // Transfer timeout (seconds)
  },
  "deployment": {
    "autoDeployEnabled": true,                     // Auto-deploy when new package found
    "checkIntervalMinutes": 5                      // How often to check (minutes)
  }
}

Editing Configuration:

Option 1: Edit JSON file directly:

notepad deployment/windows/scripts/deploy-config.json

Option 2: Use interactive configuration editor:

.\Publish-And-Deploy.ps1
# Menu: [3] Configure Settings

🔄 Transfer Methods

.\Publish-And-Deploy.ps1 -TransferMethod Auto
  • LAN: Tries Windows Share first (fast, ~30 seconds)
  • Remote: Falls back to SSH if share not accessible
  • Smart: Automatically chooses best method

Windows Share (LAN Only)

.\Publish-And-Deploy.ps1 -TransferMethod WindowsShare
  • Speed: Very fast (LAN)
  • Requirements: Dev machine in same network as server
  • Protocol: SMB (port 445)
  • Use case: Office/home network

SSH/SCP (LAN or Remote)

.\Publish-And-Deploy.ps1 -TransferMethod SSH
  • Speed: Decent (depends on bandwidth)
  • Requirements: SSH key configured, server accessible
  • Protocol: SSH (port 22122)
  • Use case: Remote work, VPN, internet

🛠️ Troubleshooting

Dev Machine Issues

Error: "Windows Share is not accessible"

# Test share access
Test-Path "\\10.0.20.36\Temp"

# Check network connectivity
Test-NetConnection -ComputerName 10.0.20.36 -Port 445

# Solution: Use SSH instead
.\Publish-And-Deploy.ps1 -TransferMethod SSH

Error: "SSH connection failed"

# Test SSH manually
ssh -i ~\.ssh\id_ed25519 -p 22122 Administrator@10.0.20.36

# Common issues:
# 1. Wrong key path → Edit deploy-config.json
# 2. Key permissions → Ensure key file has correct Windows permissions
# 3. Server not reachable → Check firewall/VPN

Error: "Configuration file not found"

# Script will auto-create default config on first run
.\Publish-And-Deploy.ps1

# Or create manually from example:
Copy-Item deploy-config.json.example deploy-config.json
notepad deploy-config.json

Server Issues

Scheduled Task Not Running

# Check task status
Get-ScheduledTask -TaskName "ROA2WEB-AutoDeploy" | Select-Object State, LastRunTime, LastTaskResult

# View task history
Get-ScheduledTaskInfo -TaskName "ROA2WEB-AutoDeploy"

# Check logs
Get-Content "C:\ROA2WEB-Scripts\Logs\check-and-deploy.log" -Tail 50

# Solution: Run setup wizard again
.\Setup-AutoDeploy.ps1

Deployment Not Triggered

# Check if new package exists
Get-ChildItem "C:\Temp" -Directory | Where-Object { $_.Name -like "deploy-*" } | Sort-Object LastWriteTime -Descending

# Check last deployment state
Get-Content "C:\Temp\ROA2WEB-Scripts\last-deploy.json" | ConvertFrom-Json

# Manual trigger
cd C:\Temp\ROA2WEB-Scripts
.\Check-And-Deploy.ps1 -Interactive
# Menu: [2] Check and Deploy Now

Package Found But Not Deployed

# Check if package is newer than last deployment
$state = Get-Content "C:\Temp\ROA2WEB-Scripts\last-deploy.json" | ConvertFrom-Json
$latest = Get-ChildItem "C:\Temp\deploy-*" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
Write-Host "Last deployed: $($state.lastDeployment.packageName)"
Write-Host "Latest package: $($latest.Name)"

# Solution: Delete state file to force redeploy
Remove-Item "C:\Temp\ROA2WEB-Scripts\last-deploy.json"
cd C:\Temp\ROA2WEB-Scripts
.\Check-And-Deploy.ps1

📊 Monitoring & Logs

View Deployment Logs (Server)

# Real-time log monitoring
Get-Content "C:\ROA2WEB-Scripts\Logs\check-and-deploy.log" -Wait

# Last 100 lines
Get-Content "C:\ROA2WEB-Scripts\Logs\check-and-deploy.log" -Tail 100

# Search for errors
Select-String -Path "C:\ROA2WEB-Scripts\Logs\check-and-deploy.log" -Pattern "ERROR"

View Deployment History (Server)

# Interactive menu
.\Check-And-Deploy.ps1 -Interactive
# Menu: [3] View Deployment History

# Or view state file directly
Get-Content "C:\ROA2WEB-Scripts\last-deploy.json" | ConvertFrom-Json | Format-List

Check Service Status (Server)

# After deployment, verify services
Get-Service -Name "ROA2WEB-Backend", "ROA2WEB-TelegramBot"

# Or use ROA2WEB-Console.ps1
cd C:\inetpub\wwwroot\roa2web\scripts
.\ROA2WEB-Console.ps1 -NonInteractive -Action Status

🔐 Security Considerations

SSH Key Management

  • Never commit SSH private keys to Git
  • Store keys in secure location (~/.ssh/ with chmod 600)
  • Use separate key for deployment (not personal key)
  • Rotate keys periodically

Windows Share Permissions

# Restrict share access to specific users (recommended for production)
New-SmbShare -Name "ROA2WEB-Deploy" -Path "C:\ROA2WEB-Deploy" -FullAccess "DOMAIN\DeployUser"

# Or keep "Everyone" for internal network (development)

Scheduled Task Security

  • Task runs as SYSTEM account (full privileges)
  • Ensure C:\ROA2WEB-Deploy is on local drive (not network share)
  • Review logs regularly for unauthorized deployments

🎯 Best Practices

1. Test Before Production

# Always test connections first
.\Publish-And-Deploy.ps1 -NonInteractive -Action TestConnections

# Then test with small component
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component Backend

2. Backup Before Deploy

  • ROA2WEB-Console.ps1 automatically creates backups
  • Backups stored in C:\inetpub\wwwroot\roa2web\backups\
  • Last 10 backups retained

3. Monitor Deployments

# Set up email alerts for failed deployments (optional)
# Add to Check-And-Deploy.ps1:
if (-not $deploySuccess) {
    Send-MailMessage -To "admin@company.com" -Subject "Deployment Failed" ...
}

4. Regular Cleanup

# Clean old deployment packages (keep last 5)
Get-ChildItem "C:\ROA2WEB-Deploy\deploy-*" |
  Sort-Object LastWriteTime -Descending |
  Select-Object -Skip 5 |
  Remove-Item -Recurse -Force

📚 Advanced Configuration

Custom Check Interval

# Edit scheduled task interval (e.g., every 10 minutes)
$trigger = Get-ScheduledTask -TaskName "ROA2WEB-AutoDeploy" | Get-ScheduledTaskTrigger
$trigger.Repetition.Interval = "PT10M"
Set-ScheduledTask -TaskName "ROA2WEB-AutoDeploy" -Trigger $trigger

Deploy Specific Components Only

# Backend only
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component Backend

# Frontend only
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component Frontend

# Telegram Bot only
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component TelegramBot

Custom SSH Port Forwarding

# If server is behind NAT/firewall, use port forwarding
# Router: Forward external port 2222 → 10.0.20.36:22122

# Edit deploy-config.json:
{
  "server": {
    "host": "public-ip-or-domain.com",
    "sshPort": 2222,
    ...
  }
}

🆘 Support

Common Commands Reference

Dev Machine:

# Quick deploy
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component All

# Test connections
.\Publish-And-Deploy.ps1 -NonInteractive -Action TestConnections

# View config
.\Publish-And-Deploy.ps1 -NonInteractive -Action ViewConfig

Server:

# Check for updates
.\Check-And-Deploy.ps1 -CheckOnly

# Deploy now
.\Check-And-Deploy.ps1

# Interactive menu
.\Check-And-Deploy.ps1 -Interactive

# View logs
Get-Content "C:\ROA2WEB-Scripts\Logs\check-and-deploy.log" -Tail 50

📝 Migration from Manual Deployment

If you were previously using manual deployment (Build-ROA2WEB.ps1 + manual copy):

  1. One-time server setup:
# Copy Setup-AutoDeploy.ps1 to server
.\Setup-AutoDeploy.ps1
  1. Update workflow:
# OLD: Manual build + copy + Remote Desktop deploy
.\Build-ROA2WEB.ps1
# ... manual copy ...
# ... Remote Desktop to server ...
# ... run ROA2WEB-Console.ps1 ...

# NEW: One command, fully automated
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component All
# → Server auto-deploys within 5 minutes
  1. Benefits:
  • ⏱️ Time saved: 15 minutes → 2 minutes
  • 🎯 Zero manual steps: No Remote Desktop needed
  • 🔄 Consistent: Same process every time
  • 📊 Audit trail: Full logs and deployment history

🧪 Testing the Complete Workflow

End-to-End Testing Guide

After completing the setup, test the entire automated deployment workflow:

Step 1: Server Setup (One-Time)

# On Dev Machine: Copy scripts to server via Windows Share
Copy-Item -Path ".\Check-And-Deploy.ps1" -Destination "\\10.0.20.36\Temp\ROA2WEB-Scripts\"
Copy-Item -Path ".\Setup-AutoDeploy.ps1" -Destination "\\10.0.20.36\Temp\ROA2WEB-Scripts\"
# On Server: Run setup wizard (via Remote Desktop - only once)
cd C:\Temp\ROA2WEB-Scripts
.\Setup-AutoDeploy.ps1

# Follow wizard prompts:
# - Monitor Path: C:\Temp (default)
# - Scripts Path: C:\Temp\ROA2WEB-Scripts (default)
# - Check Interval: 5 minutes (default)
# - Auto-Deploy: Yes (default)
# - Create Scheduled Task: Yes (default)

Step 2: Test Connections (Dev Machine)

cd /mnt/e/proiecte/roa2web/deployment/windows/scripts

# Run connection tests
.\Publish-And-Deploy.ps1
# Select: [2] Test Connections

# Expected output:
# ✅ Windows Share accessible: \\10.0.20.36\Temp
# ✅ SSH connection successful: Administrator@10.0.20.36:22122

Step 3: First Deployment Test (Dev Machine)

# Build and publish a test package
.\Publish-And-Deploy.ps1

# Menu workflow:
# [1] Build & Publish Package
#   → Component: [1] All (or test with Backend only)
#   → Transfer Method: [1] Auto (recommended)
#   → Confirm: Y

# Expected output:
# ✅ Building deployment package...
# ✅ Transferring via Windows Share...
# ✅ Package copied: \\10.0.20.36\Temp\deploy-20241113-HHMMSS\
# ✅ Server will auto-deploy within 5 minutes

Step 4: Verify Auto-Deploy (Server)

# Wait 1-5 minutes, then check deployment logs on server:
Get-Content "C:\Temp\ROA2WEB-Scripts\Logs\check-and-deploy.log" -Tail 30

# Expected log entries:
# [2024-11-13 HH:MM:SS] [INFO] === Check and Deploy Started ===
# [2024-11-13 HH:MM:SS] [SUCCESS] Found 1 package(s), latest: deploy-20241113-HHMMSS
# [2024-11-13 HH:MM:SS] [SUCCESS] New package detected
# [2024-11-13 HH:MM:SS] [INFO] Executing deployment via ROA2WEB-Console.ps1...
# [2024-11-13 HH:MM:SS] [SUCCESS] Deployment completed successfully
# Verify services are running:
Get-Service -Name "ROA2WEB-Backend", "ROA2WEB-TelegramBot"

# Expected output:
# Status   Name                   DisplayName
# ------   ----                   -----------
# Running  ROA2WEB-Backend        ROA2WEB Backend Service
# Running  ROA2WEB-TelegramBot    ROA2WEB Telegram Bot Service

Step 5: Verify Web Application

# Open browser and test:
http://10.0.20.36/          # Frontend should load
http://10.0.20.36/api/docs  # Backend API docs should be accessible

Manual Testing (Optional)

If you want to test without waiting for Scheduled Task:

# On Server: Manual deployment test
cd C:\Temp\ROA2WEB-Scripts
.\Check-And-Deploy.ps1 -Interactive

# Menu workflow:
# [1] Check for Updates (No Deploy) - verify package is detected
# [2] Check and Deploy Now - force immediate deployment
# [3] View Deployment History - see deployment records

Troubleshooting Failed Tests

If Windows Share test fails:

# Verify network connectivity
Test-NetConnection -ComputerName 10.0.20.36 -Port 445

# Try manual access
Test-Path "\\10.0.20.36\Temp"

# Fallback: Use SSH transfer instead
.\Publish-And-Deploy.ps1 -TransferMethod SSH

If SSH test fails:

# Test SSH manually
ssh -i ~\.ssh\id_ed25519 -p 22122 Administrator@10.0.20.36

# If key path is wrong, update config:
notepad deploy-config.json
# Update: "sshKeyPath": "correct\\path\\to\\key"

If auto-deploy doesn't trigger:

# Verify scheduled task is running (on server):
Get-ScheduledTask -TaskName "ROA2WEB-AutoDeploy" | Select-Object State, LastRunTime

# Manually trigger task:
Start-ScheduledTask -TaskName "ROA2WEB-AutoDeploy"

# Check for errors in logs:
Select-String -Path "C:\Temp\ROA2WEB-Scripts\Logs\check-and-deploy.log" -Pattern "ERROR"

🎉 Success!

You've now set up the automated deployment system for ROA2WEB! Deployments are now as simple as:

.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component All

Server auto-deploys within 5 minutes - no Remote Desktop, no manual steps! 🚀