conocimientocicd-architecttemplates/5276 B
deploy-scheduled-task.yml
Fichero que /hv:cicd-architect usa o materializa en el proyecto. Se muestra tal cual está en el plugin.
# =============================================================================
# steps/deploy-scheduled-task.yml — Deploy de Console/Worker como TAREA PROGRAMADA
# R25. Mecanismo recomendado para sync periodico (proceso fresco por
# ejecucion -> deploy = file-sync, sin locks entre runs).
#
# Corre en el agente del SERVIDOR DESTINO (checkout:none R8, descarga REST R3).
# Secuencia: parar tarea -> backup (R15) -> file-sync del publish -> (re)registrar la
# tarea -> verificar. Rollback inline si el sync/registro falla.
#
# Variables esperadas (las define el YAML del pipeline / VG):
# taskName nombre de la tarea programada (ej. MyCompany.Billing.Sync)
# deployFolder carpeta destino en el servidor (ej. D:\Apps\Billing)
# consoleExe nombre del exe publicado (ej. MyCompany.Billing.Console.exe)
# taskScheduleArgs args de schedule de schtasks (ej. '/SC HOURLY' o '/SC DAILY /ST 02:00')
# taskRunAccount cuenta de ejecucion (R6: 'NT AUTHORITY\SYSTEM' por defecto)
# backupRoot raiz de backups (R15)
# MsDeployPackage carpeta del artefacto descargado (la pone download-artifact-rest.yml)
# =============================================================================
parameters:
- name: mode # warn | block (gate de seguridad R22)
type: string
default: block
steps:
- checkout: none # R8
- template: security-verdict-gate.yml # R22
parameters:
mode: ${{ parameters.mode }}
- template: download-artifact-rest.yml # R3
# {{CONFIG_INJECT_STEP}} <- /cicd-init (R23 .NET SDK-style sin Key Vault): si aplica, inyecta los
# secretos del VG en $(MsDeployPackage)\appsettings.json ANTES del file-sync. Si Key Vault o sin
# config por entorno -> eliminar este marcador. (El file-sync de abajo NO pisa appsettings*.json del
# servidor: lleva /XF, asi un servidor ya configurado conserva su config.)
- task: PowerShell@2
displayName: 'Deploy Console/Worker -> Tarea Programada (stop/backup/sync/register)'
inputs:
targetType: inline
script: |
$ErrorActionPreference = 'Stop'
try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13 } catch { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } # R2
$task = '$(taskName)'
$dest = '$(deployFolder)'
$exe = '$(consoleExe)'
$src = '$(MsDeployPackage)'
if ([string]::IsNullOrWhiteSpace($task) -or [string]::IsNullOrWhiteSpace($dest) -or [string]::IsNullOrWhiteSpace($exe)) {
Write-Error "Faltan variables: taskName/deployFolder/consoleExe. Configurar en el pipeline o VG."; exit 1
}
# 1) Parar la tarea si esta corriendo (libera el exe; proceso fresco en el proximo run)
& schtasks /End /TN "$task" 2>$null; $global:LASTEXITCODE = 0
# 2) Backup R15 (capa 1): copia timestamped de la carpeta actual (si existe)
$bak = $null
if (Test-Path $dest) {
$bak = Join-Path '$(backupRoot)' ("$task-" + (Get-Date -Format 'yyyyMMdd-HHmmss'))
New-Item -ItemType Directory -Force -Path $bak | Out-Null
robocopy $dest $bak /MIR /NFL /NDL /NJH /NJS /NP | Out-Null
if ($LASTEXITCODE -ge 8) { Write-Error "Backup pre-deploy fallo (robocopy $LASTEXITCODE)"; exit 1 }
$global:LASTEXITCODE = 0
}
try {
# 3) File-sync del publish -> destino. /XF preserva la config por-entorno del servidor
# (appsettings*.json) que NO viene en el paquete o se inyecta aparte (R23).
New-Item -ItemType Directory -Force -Path $dest | Out-Null
robocopy $src $dest /MIR /XF appsettings.Production.json appsettings.Development.json /NFL /NDL /NJH /NJS /NP | Out-Null
if ($LASTEXITCODE -ge 8) { throw "File-sync fallo (robocopy $LASTEXITCODE)" }
$global:LASTEXITCODE = 0
# 4) (Re)registrar la tarea programada apuntando al exe desplegado
$exePath = Join-Path $dest $exe
if (-not (Test-Path $exePath)) { throw "No se encuentra el exe desplegado: $exePath" }
& schtasks /Create /F /TN "$task" /TR "`"$exePath`"" $(taskScheduleArgs) /RU "$(taskRunAccount)" /RL HIGHEST
if ($LASTEXITCODE -ne 0) { throw "schtasks /Create fallo ($LASTEXITCODE)" }
$global:LASTEXITCODE = 0
# 5) Verificar que la tarea quedo registrada
& schtasks /Query /TN "$task" 1>$null
if ($LASTEXITCODE -ne 0) { throw "La tarea '$task' no quedo registrada" }
$global:LASTEXITCODE = 0
Write-Host "OK: Console/Worker desplegado en $dest + tarea '$task' registrada ($(taskScheduleArgs))"
}
catch {
Write-Warning "Deploy fallo: $_"
# Rollback R15 (capa 3): restaurar el backup si lo hubo
if ($bak -and (Test-Path $bak)) {
Write-Warning "Rollback: restaurando $dest desde $bak"
robocopy $bak $dest /MIR /NFL /NDL /NJH /NJS /NP | Out-Null
$global:LASTEXITCODE = 0
}
Write-Error "Deploy de Console/Worker abortado (rollback aplicado si habia backup)."
exit 1
}