Files
hats-app/deploy.ps1
Ichsan Kurniawan d0db9ee429 Add VPS deployment automation
This change adds staging and production deployment configuration for the VPS setup, including `.env.deploy.example`, `.env.staging`, and updated production environment values. It also introduces a PowerShell deployment script that builds the app, packages the Next.js artifact, uploads it to the server, and reloads PM2. Package scripts were added for staging and production deploys, and the TypeScript config now excludes legacy `.old` files.
2026-10-05 19:52:11 +07:00

406 lines
18 KiB
PowerShell

<#
.SYNOPSIS
Script Deployment Otomatis untuk hats-app (Next.js 16 / React 19) dari Windows ke Server VPS.
.DESCRIPTION
1. Membaca konfigurasi kredensial VPS dari .env.deploy atau parameter CLI.
2. Menjalankan proses build: Next.js build dengan environment target (staging / production).
3. Menyesuaikan path di '.next/required-server-files.json' agar kompatibel dengan lingkungan Linux VPS.
4. Mengompresi folder .next, public, package.json, dan next.config.ts menjadi arsip .tar.gz (mengecualikan cache & dev artifacts).
5. Mengunggah arsip ke /tmp di VPS via SCP dengan autentikasi Password / Key non-interaktif.
6. Mengekstrak arsip di server VPS ke direktori target (/home/repositories/...).
7. Mereload service PM2 (hats-app / hats-app-dev) di VPS dan membersihkan file arsip sementara.
.PARAMETER Target
Target environment: 'staging' (default) atau 'production'.
.PARAMETER ConfigFile
Path ke file konfigurasi deploy (default: .env.deploy).
.PARAMETER SkipBuild
Lewati langkah build jika folder .next sudah siap.
.PARAMETER UploadEnv
Unggah file environment (.env.staging / .env.production) ke VPS.
.PARAMETER InstallDeps
Jalankan 'npm install --legacy-peer-deps' di VPS jika ada perubahan package dependencies.
.PARAMETER GitPull
Mode alternatif: Jalankan git pull & restart PM2 langsung di VPS tanpa build lokal.
.PARAMETER Force
Abaikan validasi branch master saat deployment ke production.
.EXAMPLE
.\deploy.ps1 staging
.\deploy.ps1 production
.\deploy.ps1 staging -SkipBuild
.\deploy.ps1 staging -InstallDeps
.\deploy.ps1 staging -GitPull
.\deploy.ps1 production -Force
#>
[CmdletBinding()]
param (
[Parameter(Position = 0)]
[ValidateSet("staging", "stag", "dev", "development", "production", "prod")]
[string]$Target = "staging",
[string]$ConfigFile = ".env.deploy",
[string]$HostOverride = "",
[string]$UserOverride = "",
[string]$PasswordOverride = "",
[switch]$SkipBuild,
[switch]$UploadEnv,
[switch]$InstallDeps,
[switch]$GitPull,
[switch]$Force
)
$ErrorActionPreference = "Stop"
# Pindah ke direktori root hats-app
$ScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $ScriptRoot
Write-Host "=======================================================" -ForegroundColor Cyan
Write-Host "[DEPLOYER] HATS-APP - WINDOWS VPS AUTO DEPLOYER (NEXT.JS)" -ForegroundColor Cyan
Write-Host "=======================================================" -ForegroundColor Cyan
# 1. Cek & Muat Konfigurasi .env.deploy
if (-not (Test-Path $ConfigFile)) {
if (Test-Path ".env.deploy.example") {
Write-Host "[WARN] File konfigurasi '$ConfigFile' belum ditemukan." -ForegroundColor Yellow
Write-Host " Menyalin template '.env.deploy.example' ke '$ConfigFile'..." -ForegroundColor Yellow
Copy-Item ".env.deploy.example" $ConfigFile
Write-Host "[STOP] Silakan buka '$ConfigFile' dan sesuaikan kredensial VPS Anda!" -ForegroundColor Red
exit 1
} else {
Write-Host "[ERROR] File konfigurasi '$ConfigFile' tidak ditemukan." -ForegroundColor Red
exit 1
}
}
# Parsing file konfigurasi key=value
$config = @{}
Get-Content $ConfigFile | ForEach-Object {
$line = $_.Trim()
if ($line -and -not $line.StartsWith("#") -and $line -match "^([^=]+)=(.*)$") {
$key = $matches[1].Trim()
$val = $matches[2].Trim().Trim('"').Trim("'")
$config[$key] = $val
}
}
# Helper untuk mendapatkan nilai dengan fallback ke env variable
function Get-ConfigValue($key, $defaultValue = "") {
$envVal = [System.Environment]::GetEnvironmentVariable($key)
if ($envVal) { return $envVal }
if ($config.ContainsKey($key) -and $config[$key]) { return $config[$key] }
return $defaultValue
}
# Parameter mapping
$isProd = ($Target -in @("production", "prod"))
$targetName = if ($isProd) { "production" } else { "staging" }
$targetEnvFile = if ($isProd) { ".env.production" } else { ".env.staging" }
$vpsHost = if ($HostOverride) { $HostOverride } else { Get-ConfigValue "VPS_HOST" "36.66.3.44" }
$vpsPort = Get-ConfigValue "VPS_PORT" "22"
$vpsUser = if ($UserOverride) { $UserOverride } else { Get-ConfigValue "VPS_USER" "root" }
$vpsPassword = if ($PasswordOverride) { $PasswordOverride } else { Get-ConfigValue "VPS_PASSWORD" "" }
$vpsKeyPath = Get-ConfigValue "VPS_KEY_PATH" ""
# Target path di VPS
$defaultStagingPath = "/home/repositories/hats-app-dev/hats-app"
$defaultProductionPath = "/home/repositories/hats-app"
$vpsBasePath = if ($isProd) {
Get-ConfigValue "VPS_PATH_PRODUCTION" $defaultProductionPath
} else {
Get-ConfigValue "VPS_PATH_STAGING" $defaultStagingPath
}
# Nama aplikasi PM2
$defaultPm2App = if ($isProd) { "hats-app" } else { "hats-app-dev" }
$pm2AppName = if ($isProd) {
Get-ConfigValue "PM2_APP_PRODUCTION" $defaultPm2App
} else {
Get-ConfigValue "PM2_APP_STAGING" $defaultPm2App
}
$targetPort = if ($isProd) {
Get-ConfigValue "PM2_PORT_PRODUCTION" "7002"
} else {
Get-ConfigValue "PM2_PORT_STAGING" "7005"
}
$customPostDeploy = Get-ConfigValue "POST_DEPLOY_CMD" ""
$postDeployCmd = if ($customPostDeploy) {
$customPostDeploy
} else {
"if pm2 describe $pm2AppName > /dev/null 2>&1; then echo '[PM2] Mereload service $pm2AppName...' && (pm2 reload $pm2AppName --update-env || pm2 restart $pm2AppName --update-env); else echo '[PM2] Service $pm2AppName tidak ditemukan. Mendaftarkan service PM2 baru...' && cd '$vpsBasePath' && pm2 start npm --name '$pm2AppName' -- start && pm2 save; fi"
}
# Validasi Kredensial
if (-not $vpsHost) {
Write-Host "[ERROR] Host VPS belum ditentukan di '$ConfigFile' (VPS_HOST)." -ForegroundColor Red
exit 1
}
if (-not $vpsPassword -and -not $vpsKeyPath) {
Write-Host "[ERROR] Password VPS (VPS_PASSWORD) atau SSH Key (VPS_KEY_PATH) belum diisi di '$ConfigFile'." -ForegroundColor Red
exit 1
}
# Cek Git Branch Saat Ini
$currentBranch = ""
try {
$currentBranch = (git branch --show-current 2>$null).Trim()
if (-not $currentBranch) {
$currentBranch = (git rev-parse --abbrev-ref HEAD 2>$null).Trim()
}
} catch {
$currentBranch = "unknown"
}
Write-Host ("[INFO] Target Environment : " + $targetName.ToUpper()) -ForegroundColor Green
Write-Host ("[INFO] Current Git Branch : " + $currentBranch) -ForegroundColor Green
Write-Host ("[INFO] Target Env File : " + $targetEnvFile) -ForegroundColor Green
Write-Host ("[INFO] Target App Port : " + $targetPort) -ForegroundColor Green
Write-Host ("[INFO] VPS Host : " + $vpsHost + ":" + $vpsPort) -ForegroundColor Green
Write-Host ("[INFO] SSH User : " + $vpsUser) -ForegroundColor Green
Write-Host ("[INFO] Target Path di VPS : " + $vpsBasePath) -ForegroundColor Green
Write-Host ("[INFO] PM2 Service Name : " + $pm2AppName) -ForegroundColor Green
Write-Host "=======================================================" -ForegroundColor Cyan
# Validasi Branch Khusus Target Production
if ($isProd -and $currentBranch -ne "master") {
if ($Force) {
Write-Host "[WARN] TARGET ADALAH PRODUCTION DAN BRANCH BUKAN 'master' ('$currentBranch')!" -ForegroundColor Yellow
Write-Host " Melanjutkan proses karena flag -Force aktif..." -ForegroundColor Yellow
} else {
Write-Host "=======================================================" -ForegroundColor Red
Write-Host "[BLOCKED] DEPLOYMENT KE PRODUCTION DIBATALKAN!" -ForegroundColor Red
Write-Host " Branch git aktif : '$currentBranch'" -ForegroundColor Yellow
Write-Host " Deployment production HANYA diperbolehkan dari branch 'master'." -ForegroundColor Yellow
Write-Host " Silakan pindah atau merge ke branch 'master' terlebih dahulu:" -ForegroundColor Yellow
Write-Host " git checkout master" -ForegroundColor Cyan
Write-Host " git merge $currentBranch" -ForegroundColor Cyan
Write-Host " (Atau gunakan flag -Force jika benar-benar berniat mem-bypass)" -ForegroundColor Gray
Write-Host "=======================================================" -ForegroundColor Red
exit 1
}
}
# Setup Autentikasi Non-Interaktif Windows OpenSSH
$tempAskPass = [System.IO.Path]::GetTempFileName() + ".bat"
"@echo $vpsPassword" | Out-File -FilePath $tempAskPass -Encoding ascii -Force
$env:SSH_ASKPASS = $tempAskPass
$env:SSH_ASKPASS_REQUIRE = "force"
$env:DISPLAY = "dummy:0"
$env:VPS_PASSWORD = $vpsPassword
$sshOptions = @(
"-P", $vpsPort,
"-o", "StrictHostKeyChecking=no",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "LogLevel=ERROR"
)
$sshCmdOptions = @(
"-p", $vpsPort,
"-o", "StrictHostKeyChecking=no",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "LogLevel=ERROR"
)
if ($vpsKeyPath -and (Test-Path $vpsKeyPath)) {
$sshOptions += @("-i", $vpsKeyPath)
$sshCmdOptions += @("-i", $vpsKeyPath)
}
$remoteUserHost = "$vpsUser@$vpsHost"
$archiveFile = "hats_app_build_" + (Get-Date -Format "yyyyMMdd_HHmmss") + ".tar.gz"
$serverFilesJson = ".next\required-server-files.json"
$serverFilesBak = ".next\required-server-files.json.bak"
$pkgJsonPath = "package.json"
$pkgJsonBak = "package.json.bak"
$tempEnvProdLocal = ".env.production.local"
$hasTempEnv = $false
try {
# Mode Alternatif: Git Pull langsung di VPS
if ($GitPull) {
Write-Host "[GIT] Mode -GitPull aktif: Menjalankan git pull & restart PM2 di server..." -ForegroundColor Yellow
$gitCmd = "cd '$vpsBasePath' && git pull"
if ($InstallDeps) {
$gitCmd += " && npm install --legacy-peer-deps"
}
$gitCmd += " && $postDeployCmd && pm2 status $pm2AppName"
& ssh.exe @sshCmdOptions $remoteUserHost $gitCmd
if ($LASTEXITCODE -ne 0) {
throw "Gagal menjalankan git pull atau reload PM2 di server (Exit code: $LASTEXITCODE)"
}
Write-Host "[SUCCESS] Git pull dan reload service berhasil!" -ForegroundColor Green
return
}
# Step 1: Build Application (Next.js build)
if (-not $SkipBuild) {
Write-Host "[BUILD] [1/4] Menjalankan build Next.js untuk $targetName..." -ForegroundColor Yellow
# Persiapkan environment file untuk build
if (-not $isProd -and (Test-Path $targetEnvFile)) {
Write-Host " Menyiapkan '$targetEnvFile' -> '$tempEnvProdLocal' untuk build staging..." -ForegroundColor Cyan
Copy-Item $targetEnvFile $tempEnvProdLocal -Force
$hasTempEnv = $true
}
$buildStart = Get-Date
# Jalankan build melalui npm.cmd (menghindari restriction PowerShell execution policy)
cmd /c "npm run build"
if ($LASTEXITCODE -ne 0) {
throw "Build Next.js gagal! Silakan periksa pesan error di atas."
}
$buildDuration = (Get-Date) - $buildStart
$seconds = [math]::Round($buildDuration.TotalSeconds, 1)
Write-Host "[OK] Build Next.js berhasil dalam $seconds detik." -ForegroundColor Green
} else {
Write-Host "[SKIP] [1/4] Melewati proses build (--SkipBuild aktif)." -ForegroundColor Gray
}
# Verifikasi folder .next
if (-not (Test-Path ".next")) {
throw "Folder '.next' tidak ditemukan! Pastikan proses build berhasil."
}
# Step 2: Normalisasi path untuk runtime Linux & Kompresi Artifact
Write-Host "[PREP] [2/4] Menyesuaikan konfigurasi runtime server Next.js..." -ForegroundColor Yellow
if (Test-Path $serverFilesJson) {
Copy-Item $serverFilesJson $serverFilesBak -Force
node -e "const fs = require('fs'); const p = process.argv[1]; const target = process.argv[2]; if (fs.existsSync(p)) { const d = JSON.parse(fs.readFileSync(p, 'utf8')); d.appDir = target; if (d.config && d.config.turbopack) d.config.turbopack.root = target; d.files = (d.files || []).map(f => f.replace(/\\\\/g, '/')); fs.writeFileSync(p, JSON.stringify(d, null, 2)); }" $serverFilesJson $vpsBasePath
Write-Host " Konfigurasi path di '$serverFilesJson' disesuaikan untuk Linux." -ForegroundColor Gray
}
if (Test-Path $pkgJsonPath) {
Copy-Item $pkgJsonPath $pkgJsonBak -Force
node -e "const fs = require('fs'); const p = process.argv[1]; const port = process.argv[2]; if (fs.existsSync(p)) { const pkg = JSON.parse(fs.readFileSync(p, 'utf8')); if (pkg.scripts) { pkg.scripts.start = 'next start -p ' + port; fs.writeFileSync(p, JSON.stringify(pkg, null, 2)); } }" $pkgJsonPath $targetPort
Write-Host " Script start pada '$pkgJsonPath' disesuaikan ke port $targetPort." -ForegroundColor Gray
}
Write-Host "[ZIP] [2/4] Mengompresi build artifact menjadi '$archiveFile'..." -ForegroundColor Yellow
if (Test-Path $archiveFile) { Remove-Item $archiveFile -Force }
$tarItems = @(".next", "public", "package.json")
if (Test-Path "next.config.ts") { $tarItems += "next.config.ts" }
if (Test-Path "next.config.mjs") { $tarItems += "next.config.mjs" }
if (Test-Path "next.config.js") { $tarItems += "next.config.js" }
# Jika user memilih -UploadEnv, sertakan env yang sesuai
if ($UploadEnv -and (Test-Path $targetEnvFile)) {
Write-Host " Menyertakan $targetEnvFile dalam arsip..." -ForegroundColor Cyan
$tarItems += $targetEnvFile
}
# Buat arsip tar.gz dengan exclude cache, dev, dan diagnostics
tar.exe -czf $archiveFile `
--exclude=".next/cache" `
--exclude=".next\cache" `
--exclude=".next/dev" `
--exclude=".next\dev" `
--exclude=".next/diagnostics" `
--exclude=".next\diagnostics" `
--exclude="*.log" `
@tarItems
if ($LASTEXITCODE -ne 0 -or -not (Test-Path $archiveFile)) {
throw "Gagal mengompresi artifact ke $archiveFile!"
}
$archiveSize = [math]::Round((Get-Item $archiveFile).Length / 1MB, 2)
Write-Host "[OK] Berhasil dikompresi: $archiveSize MB" -ForegroundColor Green
# Step 3: Upload archive ke Server VPS
$remoteTempArchive = "/tmp/hats_app_build_" + (Get-Date -Format "yyyyMMdd_HHmmss") + ".tar.gz"
Write-Host "[UPLOAD] [3/4] Mengunggah $archiveFile ke $vpsHost`:$remoteTempArchive..." -ForegroundColor Yellow
$remoteDest = "$remoteUserHost`:$remoteTempArchive"
$uploadStart = Get-Date
& scp.exe @sshOptions $archiveFile $remoteDest
if ($LASTEXITCODE -ne 0) {
throw "Gagal mentransfer file melalui SCP (Exit code: $LASTEXITCODE)"
}
$uploadDuration = (Get-Date) - $uploadStart
$uploadSeconds = [math]::Round($uploadDuration.TotalSeconds, 1)
Write-Host "[OK] Upload selesai dalam $uploadSeconds detik." -ForegroundColor Green
# Step 4: Ekstrak arsip di Server VPS & Restart PM2
Write-Host "[EXTRACT] [4/4] Mengekstrak file ke $vpsBasePath di server VPS..." -ForegroundColor Yellow
$remoteCommands = @(
"mkdir -p '$vpsBasePath'",
"tar -xzf '$remoteTempArchive' -C '$vpsBasePath'",
"rm -f '$remoteTempArchive'"
)
if ($UploadEnv -and (Test-Path $targetEnvFile)) {
$envFilename = Split-Path -Leaf $targetEnvFile
$remoteCommands += "cp -f '$vpsBasePath/$envFilename' '$vpsBasePath/.env.production'"
}
if ($InstallDeps) {
Write-Host "[DEPS] Menjalankan npm install di server..." -ForegroundColor Yellow
$remoteCommands += "cd '$vpsBasePath' && npm install --legacy-peer-deps"
}
if ($postDeployCmd) {
Write-Host "[RELOAD] Menjalankan reload service PM2 ($pm2AppName)..." -ForegroundColor Yellow
$remoteCommands += $postDeployCmd
}
$fullRemoteCmd = $remoteCommands -join " && "
& ssh.exe @sshCmdOptions $remoteUserHost $fullRemoteCmd
if ($LASTEXITCODE -ne 0) {
throw "Gagal mengekstrak atau mereload service di server remote (Exit code: $LASTEXITCODE)"
}
Write-Host "[OK] File berhasil diekstrak dan service direload." -ForegroundColor Green
# Tampilkan status PM2
Write-Host "[STATUS] Memeriksa status proses PM2..." -ForegroundColor Yellow
$statusCmd = "pm2 status $pm2AppName"
& ssh.exe @sshCmdOptions $remoteUserHost $statusCmd
} catch {
Write-Host "[ERROR] Terjadi error saat deployment: $_" -ForegroundColor Red
exit 1
} finally {
# 1. Pulihkan required-server-files.json lokal jika tadi di-backup
if (Test-Path $serverFilesBak) {
Copy-Item $serverFilesBak $serverFilesJson -Force
Remove-Item $serverFilesBak -Force -ErrorAction SilentlyContinue
}
# 2. Pulihkan package.json lokal jika tadi disesuaikan
if (Test-Path $pkgJsonBak) {
Copy-Item $pkgJsonBak $pkgJsonPath -Force
Remove-Item $pkgJsonBak -Force -ErrorAction SilentlyContinue
}
# 3. Hapus temporary .env.production.local
if ($hasTempEnv -and (Test-Path $tempEnvProdLocal)) {
Remove-Item $tempEnvProdLocal -Force -ErrorAction SilentlyContinue
}
# 3. Hapus arsip lokal
if (Test-Path $archiveFile) {
Remove-Item $archiveFile -Force -ErrorAction SilentlyContinue
}
# 4. Hapus askpass bat dan bersihkan environment variables
if (Test-Path $tempAskPass) {
Remove-Item $tempAskPass -Force -ErrorAction SilentlyContinue
}
Remove-Item Env:\SSH_ASKPASS -ErrorAction SilentlyContinue
Remove-Item Env:\SSH_ASKPASS_REQUIRE -ErrorAction SilentlyContinue
Remove-Item Env:\VPS_PASSWORD -ErrorAction SilentlyContinue
Remove-Item Env:\DISPLAY -ErrorAction SilentlyContinue
}
Write-Host "=======================================================" -ForegroundColor Cyan
Write-Host "[SUCCESS] DEPLOYMENT HATS-APP SELESAI DENGAN SUKSES!" -ForegroundColor Green
Write-Host "[PATH] Server Path : $vpsBasePath" -ForegroundColor Green
Write-Host "[PM2] App Name : $pm2AppName" -ForegroundColor Green
Write-Host "=======================================================" -ForegroundColor Cyan