-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeploy-Remote.ps1
More file actions
451 lines (383 loc) · 20.9 KB
/
Deploy-Remote.ps1
File metadata and controls
451 lines (383 loc) · 20.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
<#
.SYNOPSIS
Deploys BitLockerKeyMonitor to a remote Windows Server from the build machine.
.DESCRIPTION
This script:
1. Publishes Worker and Web projects locally (unless -SkipPublish)
2. Opens a PSSession to the target server
3. Stops existing services on the target
4. Copies published artifacts via the PS session
5. Registers/updates Windows Services on the target
6. Configures SQL Server service dependency
7. Starts services in correct order
Prerequisites on the BUILD machine:
- .NET 10 SDK
- Source code in the same directory as this script
Prerequisites on the TARGET machine:
- Windows Server 2022+ (domain-joined)
- .NET 10 ASP.NET Core Runtime
- SQL Server Express (local)
- WinRM enabled (default on domain-joined servers)
- A TLS certificate in LocalMachine\My (for Kestrel HTTPS)
.PARAMETER TargetServer
Hostname or FQDN of the target server. Required.
.PARAMETER Credential
PSCredential object for the target server. If omitted, prompts interactively.
.PARAMETER InstallRoot
Installation folder on the target. Default: C:\Program Files\BitLockerKeyMonitor
.PARAMETER SqlInstanceName
SQL Server instance name on the target. Default: SQLEXPRESS
.PARAMETER SkipPublish
Skip the local dotnet publish step (use pre-built artifacts).
.PARAMETER SkipServiceRestart
Deploy binaries but do not restart services (for maintenance windows).
.PARAMETER GraphCertificateThumbprint
Optional SHA-1 thumbprint (40 hex chars) of the client certificate used to
authenticate to Microsoft Graph (Authentication:CertificateThumbprint).
When supplied, merged in-place into the WORKER's appsettings.json only —
the Web does not call Graph. The pre-edit file is preserved as
appsettings.json.bak.<ts>.
.PARAMETER HttpsCertificateThumbprint
Optional SHA-1 thumbprint (40 hex chars) of the TLS certificate used by
Kestrel for the Web service (WebServer:CertificateThumbprint). Merged
in-place into Web's appsettings.json only.
.EXAMPLE
.\Deploy-Remote.ps1 -TargetServer SRVBLKMON01
.EXAMPLE
.\Deploy-Remote.ps1 -TargetServer SRVBLKMON01 -Credential (Get-Credential)
.EXAMPLE
.\Deploy-Remote.ps1 -TargetServer SRVBLKMON01 -SkipPublish
.EXAMPLE
.\Deploy-Remote.ps1 -TargetServer SRVBLKMON01 `
-GraphCertificateThumbprint 855CDF6182DE9CBD6C7D3C95340B5CAA7222D2BA `
-HttpsCertificateThumbprint AABBCCDDEEFF00112233445566778899AABBCCDD
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$TargetServer,
[PSCredential]$Credential,
[string]$InstallRoot = "C:\Program Files\BitLockerKeyMonitor",
[string]$SqlInstanceName = "SQLEXPRESS",
[switch]$SkipPublish,
[switch]$SkipServiceRestart,
[ValidateScript({
if ($_ -match '^[A-Fa-f0-9]{40}$') { return $true }
throw "GraphCertificateThumbprint must be a 40-character hex SHA-1 thumbprint (got '$_')."
})]
[string]$GraphCertificateThumbprint,
[ValidateScript({
if ($_ -match '^[A-Fa-f0-9]{40}$') { return $true }
throw "HttpsCertificateThumbprint must be a 40-character hex SHA-1 thumbprint (got '$_')."
})]
[string]$HttpsCertificateThumbprint
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# Normalize thumbprints — appsettings comparisons are case-insensitive but cert
# stores often store uppercase; we standardize to uppercase here for consistency.
if ($GraphCertificateThumbprint) {
$GraphCertificateThumbprint = $GraphCertificateThumbprint.Trim().ToUpperInvariant()
}
if ($HttpsCertificateThumbprint) {
$HttpsCertificateThumbprint = $HttpsCertificateThumbprint.Trim().ToUpperInvariant()
}
# ── Helpers ──────────────────────────────────────────────────────────────────
function Write-Step { param([string]$msg) Write-Host "`n▶ $msg" -ForegroundColor Cyan }
function Write-Ok { param([string]$msg) Write-Host " ✓ $msg" -ForegroundColor Green }
function Write-Warn { param([string]$msg) Write-Host " ⚠ $msg" -ForegroundColor Yellow }
function Write-Err { param([string]$msg) Write-Host " ✗ $msg" -ForegroundColor Red }
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$SrcDir = Join-Path $ScriptDir "src"
$WorkerProj = Join-Path $SrcDir "BitLockerKeyMonitor.Worker\BitLockerKeyMonitor.Worker.csproj"
$WebProj = Join-Path $SrcDir "BitLockerKeyMonitor.Web\BitLockerKeyMonitor.Web.csproj"
$WorkerPubDir = Join-Path $ScriptDir "artifacts\Worker"
$WebPubDir = Join-Path $ScriptDir "artifacts\Web"
$WorkerSvc = "BitLockerKeyMonitor.Worker"
$WebSvc = "BitLockerKeyMonitor.Web"
$RemoteWorkerDest = Join-Path $InstallRoot "Worker"
$RemoteWebDest = Join-Path $InstallRoot "Web"
# ── Pre-flight ───────────────────────────────────────────────────────────────
Write-Step "Pre-flight checks"
if (-not $SkipPublish) {
if (-not (Test-Path $WorkerProj)) { Write-Err "Worker project not found: $WorkerProj"; exit 1 }
if (-not (Test-Path $WebProj)) { Write-Err "Web project not found: $WebProj"; exit 1 }
Write-Ok "Source projects found"
}
# Test connectivity
if (-not (Test-Connection -ComputerName $TargetServer -Count 2 -Quiet)) {
Write-Err "Cannot reach $TargetServer. Verify hostname and network."
exit 1
}
Write-Ok "$TargetServer is reachable"
# ── Publish locally ──────────────────────────────────────────────────────────
if (-not $SkipPublish) {
Write-Step "Publishing Worker"
& dotnet publish $WorkerProj -c Release -r win-x64 --self-contained false -o $WorkerPubDir --nologo -v q
if ($LASTEXITCODE -ne 0) { Write-Err "Worker publish failed."; exit 1 }
Write-Ok "Worker published to $WorkerPubDir"
Write-Step "Publishing Web"
& dotnet publish $WebProj -c Release -r win-x64 --self-contained false -o $WebPubDir --nologo -v q
if ($LASTEXITCODE -ne 0) { Write-Err "Web publish failed."; exit 1 }
Write-Ok "Web published to $WebPubDir"
} else {
if (-not (Test-Path $WorkerPubDir) -or -not (Test-Path $WebPubDir)) {
Write-Err "Pre-built artifacts not found in artifacts\. Run without -SkipPublish first."
exit 1
}
Write-Ok "Using pre-built artifacts"
}
# ── Connect to target ────────────────────────────────────────────────────────
Write-Step "Connecting to $TargetServer"
$sessionParams = @{ ComputerName = $TargetServer }
if ($Credential) {
$sessionParams.Credential = $Credential
} else {
Write-Host " No -Credential supplied. Prompting..." -ForegroundColor Yellow
$sessionParams.Credential = Get-Credential -Message "Enter credentials for $TargetServer"
}
try {
$session = New-PSSession @sessionParams
Write-Ok "Connected to $TargetServer"
} catch {
Write-Err "Failed to connect to $TargetServer : $_"
Write-Err "Ensure WinRM is enabled: winrm quickconfig"
exit 1
}
try {
# ── Stop services on target ──────────────────────────────────────────────
Write-Step "Stopping services on $TargetServer"
Invoke-Command -Session $session -ScriptBlock {
param($WebSvc, $WorkerSvc)
foreach ($svcName in @($WebSvc, $WorkerSvc)) {
$svc = Get-Service -Name $svcName -ErrorAction SilentlyContinue
if ($svc -and $svc.Status -ne 'Stopped') {
Stop-Service -Name $svcName -Force -ErrorAction Stop
# Wait for process to fully release file locks
Start-Sleep -Seconds 2
Write-Output "Stopped $svcName"
} elseif ($svc) {
Write-Output "$svcName already stopped"
} else {
Write-Output "$svcName not installed yet"
}
}
} -ArgumentList $WebSvc, $WorkerSvc | ForEach-Object { Write-Ok $_ }
# ── Create directories on target ─────────────────────────────────────────
Write-Step "Creating directories on $TargetServer"
Invoke-Command -Session $session -ScriptBlock {
param($InstallRoot, $WorkerDest, $WebDest)
$dirs = @($InstallRoot, $WorkerDest, $WebDest,
(Join-Path $InstallRoot "logs"),
(Join-Path $InstallRoot "output"),
(Join-Path $InstallRoot "output\secure"))
foreach ($dir in $dirs) {
if (-not (Test-Path $dir)) {
New-Item -ItemType Directory -Path $dir -Force | Out-Null
Write-Output "Created $dir"
}
}
} -ArgumentList $InstallRoot, $RemoteWorkerDest, $RemoteWebDest | ForEach-Object { Write-Ok $_ }
# ── Copy artifacts ───────────────────────────────────────────────────────
Write-Step "Copying Worker artifacts to $TargetServer"
Copy-Item -Path "$WorkerPubDir\*" -Destination $RemoteWorkerDest -ToSession $session -Recurse -Force
Write-Ok "Worker → $RemoteWorkerDest"
Write-Step "Copying Web artifacts to $TargetServer"
Copy-Item -Path "$WebPubDir\*" -Destination $RemoteWebDest -ToSession $session -Recurse -Force
Write-Ok "Web → $RemoteWebDest"
# ── Merge cert thumbprints into appsettings.json (optional) ──────────────
if ($GraphCertificateThumbprint -or $HttpsCertificateThumbprint) {
Write-Step "Merging cert thumbprints into appsettings.json on $TargetServer"
# Best-effort pre-flight: verify the referenced certs exist in LocalMachine\My.
# Missing certs are reported as warnings (not fatal) because the cert may be
# imported as a separate step or by an automation pipeline.
Invoke-Command -Session $session -ScriptBlock {
param($GraphTp, $HttpsTp)
$report = @()
foreach ($tp in @($GraphTp, $HttpsTp) | Where-Object { $_ }) {
$cert = Get-ChildItem -Path "Cert:\LocalMachine\My" -ErrorAction SilentlyContinue |
Where-Object { $_.Thumbprint -eq $tp }
if ($cert) {
$report += "Cert $($tp.Substring(0,8))... present: $($cert.Subject) (notAfter=$($cert.NotAfter.ToString('yyyy-MM-dd')))"
} else {
$report += "WARNING: cert $($tp.Substring(0,8))... NOT FOUND in LocalMachine\My — service will fail to start until it is imported"
}
}
$report
} -ArgumentList $GraphCertificateThumbprint, $HttpsCertificateThumbprint | ForEach-Object {
if ($_ -like "WARNING:*") { Write-Warn $_ } else { Write-Ok $_ }
}
Invoke-Command -Session $session -ScriptBlock {
param($WorkerDest, $WebDest, $GraphTp, $HttpsTp)
# Merge given key=value pairs (Section.Property = Value) into a JSON
# file in-place, preserving every other key already present. The
# original file is backed up to <path>.bak.<yyyyMMdd-HHmmss>.
#
# PSCustomObject path (PS 5.1 compatible — the in-box shell on
# Windows Server). On PS 7 the same code works because ConvertFrom-Json
# also returns PSCustomObject by default.
function Update-AppSettings {
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][hashtable]$Sections # @{ Section = @{ Key = Value } }
)
if (-not (Test-Path -LiteralPath $Path)) {
throw "appsettings.json not found at $Path"
}
$backup = "$Path.bak.$(Get-Date -Format 'yyyyMMdd-HHmmss')"
Copy-Item -LiteralPath $Path -Destination $backup -Force
$raw = Get-Content -LiteralPath $Path -Raw -Encoding UTF8
if ([string]::IsNullOrWhiteSpace($raw)) {
throw "appsettings.json at $Path is empty"
}
$obj = $raw | ConvertFrom-Json
$changes = @()
foreach ($sectionName in $Sections.Keys) {
$kvs = $Sections[$sectionName]
if (-not $obj.PSObject.Properties[$sectionName]) {
$obj | Add-Member -NotePropertyName $sectionName -NotePropertyValue ([pscustomobject]@{})
}
$section = $obj.$sectionName
foreach ($key in $kvs.Keys) {
$newVal = $kvs[$key]
if ($section.PSObject.Properties[$key]) {
$oldVal = $section.$key
if ("$oldVal" -ne "$newVal") {
$section.$key = $newVal
$changes += "${sectionName}:${key} updated"
} else {
$changes += "${sectionName}:${key} unchanged"
}
} else {
$section | Add-Member -NotePropertyName $key -NotePropertyValue $newVal
$changes += "${sectionName}:${key} added"
}
}
}
# Depth 32 is more than enough for any realistic appsettings tree.
# ConvertTo-Json in PS 5.1 escapes non-ASCII via \uXXXX which is
# valid JSON; .NET's configuration parser handles it transparently.
$json = $obj | ConvertTo-Json -Depth 32
[System.IO.File]::WriteAllText($Path, $json, [System.Text.UTF8Encoding]::new($false))
return [pscustomobject]@{
Path = $Path
Backup = $backup
Changes = $changes
}
}
$workerAppSettings = Join-Path $WorkerDest "appsettings.json"
$webAppSettings = Join-Path $WebDest "appsettings.json"
# Build the sections to merge per project.
$workerSections = @{}
$webSections = @{}
if ($GraphTp) {
# Worker only — the Web does not call Microsoft Graph.
$workerSections["Authentication"] = @{ CertificateThumbprint = $GraphTp }
}
if ($HttpsTp) {
$webSections["WebServer"] = @{ CertificateThumbprint = $HttpsTp }
}
# Clean up any leftover appsettings.Production.json from previous
# deploys that used the override-file pattern. If left behind, it
# would silently override the values we just merged into the base
# file and mask configuration changes — exactly the kind of stale
# state that wastes a deploy window.
foreach ($dest in @($WorkerDest, $WebDest)) {
$stale = Join-Path $dest "appsettings.Production.json"
if (Test-Path -LiteralPath $stale) {
$staleBak = "$stale.bak.$(Get-Date -Format 'yyyyMMdd-HHmmss')"
Move-Item -LiteralPath $stale -Destination $staleBak -Force
Write-Output "Renamed stale override: $stale → $staleBak"
}
}
if ($workerSections.Count -gt 0) {
$r = Update-AppSettings -Path $workerAppSettings -Sections $workerSections
foreach ($c in $r.Changes) { Write-Output "Worker $($r.Path): $c" }
Write-Output "Worker backup: $($r.Backup)"
}
if ($webSections.Count -gt 0) {
$r = Update-AppSettings -Path $webAppSettings -Sections $webSections
foreach ($c in $r.Changes) { Write-Output "Web $($r.Path): $c" }
Write-Output "Web backup: $($r.Backup)"
}
} -ArgumentList $RemoteWorkerDest, $RemoteWebDest, $GraphCertificateThumbprint, $HttpsCertificateThumbprint |
ForEach-Object { Write-Ok $_ }
}
# ── Register services + configure dependency ─────────────────────────────
Write-Step "Registering services on $TargetServer"
Invoke-Command -Session $session -ScriptBlock {
param($InstallRoot, $WorkerSvc, $WebSvc, $SqlInstanceName)
$workerExe = Join-Path $InstallRoot "Worker\BitLockerKeyMonitor.Worker.exe"
$webExe = Join-Path $InstallRoot "Web\BitLockerKeyMonitor.Web.exe"
foreach ($entry in @(
@{ Name = $WorkerSvc; Exe = $workerExe; Display = "BitLocker Key Monitor - Worker" },
@{ Name = $WebSvc; Exe = $webExe; Display = "BitLocker Key Monitor - Web (Kestrel)" }
)) {
$existing = Get-Service -Name $entry.Name -ErrorAction SilentlyContinue
if ($existing) {
& sc.exe config $entry.Name binPath= "`"$($entry.Exe)`"" start= delayed-auto | Out-Null
Write-Output "Updated service $($entry.Name)"
} else {
& sc.exe create $entry.Name `
binPath= "`"$($entry.Exe)`"" `
DisplayName= $entry.Display `
start= delayed-auto | Out-Null
Write-Output "Created service $($entry.Name)"
}
# Recovery policy: restart after 60s on first/second failure
& sc.exe failure $entry.Name reset= 86400 actions= restart/60000/restart/60000// | Out-Null
# SQL Server dependency — ensures services start AFTER SQL Express
& sc.exe config $entry.Name depend= "MSSQL`$$SqlInstanceName" | Out-Null
Write-Output " Dependency set: $($entry.Name) → MSSQL`$$SqlInstanceName"
}
} -ArgumentList $InstallRoot, $WorkerSvc, $WebSvc, $SqlInstanceName | ForEach-Object { Write-Ok $_ }
# ── Start services ───────────────────────────────────────────────────────
if (-not $SkipServiceRestart) {
Write-Step "Starting services on $TargetServer"
Invoke-Command -Session $session -ScriptBlock {
param($WorkerSvc, $WebSvc)
Start-Service -Name $WorkerSvc
Write-Output "Started $WorkerSvc"
# Brief pause to let DB initialize on first run
Start-Sleep -Seconds 5
Start-Service -Name $WebSvc
Write-Output "Started $WebSvc"
# Verify both are running
Start-Sleep -Seconds 3
foreach ($svcName in @($WorkerSvc, $WebSvc)) {
$svc = Get-Service -Name $svcName
if ($svc.Status -eq 'Running') {
Write-Output "$svcName is running ✓"
} else {
Write-Output "WARNING: $svcName status is $($svc.Status)"
}
}
} -ArgumentList $WorkerSvc, $WebSvc | ForEach-Object { Write-Ok $_ }
} else {
Write-Warn "Skipping service restart (-SkipServiceRestart)"
}
# ── Summary ──────────────────────────────────────────────────────────────
Write-Host ""
Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Green
Write-Host " BitLockerKeyMonitor deployed to $TargetServer!" -ForegroundColor Green
Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Green
Write-Host ""
Write-Host " Target server : $TargetServer"
Write-Host " Install root : $InstallRoot"
Write-Host " Worker service : $WorkerSvc"
Write-Host " Web service : $WebSvc"
Write-Host " SQL dependency : MSSQL`$$SqlInstanceName"
if ($GraphCertificateThumbprint) {
Write-Host " Graph cert : $($GraphCertificateThumbprint.Substring(0,8))... (Authentication:CertificateThumbprint)"
}
if ($HttpsCertificateThumbprint) {
Write-Host " HTTPS cert : $($HttpsCertificateThumbprint.Substring(0,8))... (WebServer:CertificateThumbprint)"
}
Write-Host ""
} finally {
# Always clean up the session
if ($session) {
Remove-PSSession -Session $session -ErrorAction SilentlyContinue
Write-Ok "PS session closed"
}
}