Files
mtusi2026lab7/scripts/bootstrap-secrets.ps1
T

29 lines
1.1 KiB
PowerShell

[CmdletBinding()]
param([string]$Destination, [switch]$Force)
$ErrorActionPreference = 'Stop'
if ([string]::IsNullOrWhiteSpace($Destination)) {
$Destination = Join-Path $PSScriptRoot '..\.env'
}
if ((Test-Path -LiteralPath $Destination) -and -not $Force) {
throw "$Destination already exists; use -Force only for an intentional full credential rotation"
}
$template = Join-Path $PSScriptRoot '..\.env.example'
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
try {
$lines = foreach($line in [System.IO.File]::ReadAllLines($template)) {
if ($line -match '^(?<name>[A-Z][A-Z0-9_]*)=replace-with-') {
$bytes = [byte[]]::new(32)
$rng.GetBytes($bytes)
$secret = [Convert]::ToBase64String($bytes).TrimEnd('=').Replace('+','-').Replace('/','_')
"$($Matches.name)=$secret"
} else {
$line
}
}
} finally {
$rng.Dispose()
}
[System.IO.File]::WriteAllLines($Destination,$lines,[System.Text.UTF8Encoding]::new($false))
Write-Host "Created local stand credentials in $Destination; values were not printed."