v1.31.0
conocimientocicd-architecttemplates/27.111 B

azure-pipelines.fase2.dotnet.yml.template

Fichero que /hv:cicd-architect usa o materializa en el proyecto. Se muestra tal cual está en el plugin.

cicd-architectskill
templatescarpeta
27.111 Btamaño
2026-10-02último cambio del pack
# =============================================================================
# {{PROYECTO_NOMBRE}} — Pipeline CI + CD (Fase 2 completa, stack .NET)
# Ovillo cicd-architect dotnet @ {{TEMPLATE_STAMP}}   (sello de plantilla; /cicd-status detecta drift)
# Reglas: .claude/skills/cicd-runtime/SKILL.md (G1-G19)
# Limitaciones Azure DevOps Server 2020: .claude/skills/cicd-architect/references/azure-devops-server-2020-quick-ref.md
# Diseno: .claude/skills/cicd-architect/references/diseno-stages.md
#
# RAMAS CONDICIONALES que /cicd-init aplica al generar (NO asumir que el template fijo vale tal cual):
#   (a) SIN proyecto de test detectado -> ELIMINAR 'dotnet test' + 'Publish coverage' + gate R18 (nada que medir).
#   (b) SIN endpoint /health -> sustituir 'steps/smoke-strict-dotnet.yml' por 'steps/smoke-besteffort-spa.yml'
#       (GET best-effort a la raiz/endpoint conocido, NO throw). El smoke estricto asume /health/* + 401.
#   (c) Inyeccion de secretos .NET: este stack NO usa XmlVariableSubstitution (eso es netfx/Web.config). Opciones:
#       - appsettings por entorno + 'FileTransform@1' (folderPath drop, fileType json) ANTES del IIS deploy, o
#       - variables de entorno 'ASPNETCORE_' / '__' en el app pool (Configuration provider las lee sin transform).
#       El VG '{{PIPELINE_NAME}}-secrets' alimenta ambas vias; el fail-fast R16 solo valida que existan.
# =============================================================================

name: $(date:yyyyMMdd)$(rev:.r)

trigger:
  # R21: branches segun configuracion.branching.estrategia (ESTADO_PROYECTO.json).
  #   push-directo (github-flow-simplificado / trunk-based / developer-branch) -> solo {{RAMA_BASE}}, SIN branch policy build-validation (bloquearia el push directo).
  #   con-PR (github-flow / gitflow / release-flow / oneflow / gitlab-flow) -> /cicd-init anade ramas en el marcador + RECOMIENDA branch policy para el gate en PR.
  branches:
    include:
      - {{RAMA_BASE}}
      # {{TRIGGER_BRANCHES_EXTRA}}  <- /cicd-init R21: gitflow=+develop ; release-flow/oneflow=+'release/*' ; gitlab-flow=+pre-production/+production ; push-directo=eliminar este marcador
  paths:
    # R7: workaround Azure DevOps Server 2020 doble patron
    include:
      - 'src/**'
      - 'src/**/*'
      - 'ops/testing/**'
      - 'ops/testing/**/*'
      - 'azure-pipelines.yml'

pr: none

variables:
  # R16: Variable Group para secretos
  - group: {{PIPELINE_NAME}}-secrets
  # R20 (TEC-009, piloto GuiasDocentes): deploy on-demand. DeployEnv NO se declara aqui — es
  # variable de la DEFINICION (settable at queue time, default '', la pone /cicd-init FASE 2.5).
  # Declararla en el YAML la ECLIPSA: en runtime vale siempre '' y los stages de deploy quedan
  # SIEMPRE skipped (CD on-demand no dispara). /cicd-deploy --env <dev|pre|pro> la pone al encolar.
  - name: BuildConfiguration
    value: 'Release'
  - name: solutionPath
    value: '{{SLN_PATH}}'
  - name: apiProject
    value: '{{API_CSPROJ}}'
  - name: testProject
    value: '{{TESTS_CSPROJ}}'
  - name: coverageLineThreshold
    value: '70'
  - name: coverageBranchThreshold
    value: '60'
  # G7: el gate de cobertura es nativo (parsea el XML Cobertura); no requiere herramienta externa.
  - name: iisVirtualApp
    value: '{{IIS_VIRTUAL_APP}}'
  - name: iisAppPool
    value: '{{IIS_APP_POOL}}'
  - name: iisPhysicalPath         # R15: ruta fisica REAL de la vApp en disco. Vacio = C:\inetpub\wwwroot\<vApp>.
    value: '{{IIS_PHYSICAL_PATH}}'  # Rellenar si la vApp NO cuelga de wwwroot (ej. C:\inetpub\wwwroot\MyApp.api\miapp). La consumen backup-pre-deploy.yml + rollback-on-fail.yml.
  - name: backupRoot              # R15: raiz de backups pre-deploy. Override si el server no tiene unidad D:.
    value: 'C:\Backups'
  # {{QUALITY_SYNC_VARS}}  <- /cicd-init FASE 2.7 (QR de calidad al dashboard): si se incluye, anade aqui
  #   - name: qualityProjectId / value: '<GUID del proyecto en el hub = mcpSync.projectId>'
  #   - name: codeSearchBase   / value: 'https://devops.example.org/<COL>/<PROJ>/_search?type=code&text='
  #   (el secreto HUB_SERVICE_KEY va en el Variable Group, isSecret, NO aqui). Si se declina, eliminar este marcador.

stages:
  # ───────────────────────────────────────────────────────────────────────
  # STAGE 1: BUILD (auto)
  # ───────────────────────────────────────────────────────────────────────
  - stage: Build
    displayName: 'Build & Test'
    jobs:
      - job: BuildAndTest
        pool:
          name: {{BUILD_POOL}}                                     # R1
          demands:
            - Agent.ComputerName -equals {{BUILD_AGENT}}             # R1
        timeoutInMinutes: 30
        steps:
          # R16: Fail-fast secretos
          - task: PowerShell@2
            displayName: 'Fail-fast: validar VG secretos'
            inputs:
              targetType: inline
              script: |
                # R2: TLS 1.2+
                try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13 } catch { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 }
                $required = @({{LISTA_SECRETOS_VG}})
                $missing = $required | Where-Object { [string]::IsNullOrWhiteSpace((Get-Item "env:$_" -EA SilentlyContinue).Value) }
                if ($missing.Count -gt 0) {
                  Write-Error "Secretos vacios: $($missing -join ', '). Rellenar en VG '{{PIPELINE_NAME}}-secrets'."
                  exit 1
                }

          # R12 warning-only: linter anti-patterns
          - task: PowerShell@2
            displayName: 'Linter anti-patterns (warning-only)'
            continueOnError: true
            inputs:
              targetType: inline
              script: |
                Write-Host "Checking R12 anti-patterns..."
                # R12.1: paths absolutos en build configs
                # R12.2: HintPath absoluto en .csproj
                # R12.4: localhost hardcoded en tests
                # Hallazgos -> Write-Warning, NO exit 1

          - task: UseDotNet@2                                # R4
            displayName: 'Install .NET SDK {{NET_VERSION}}'
            inputs:
              packageType: 'sdk'
              version: '{{NET_VERSION}}.x'

          - task: DotNetCoreCLI@2
            displayName: 'dotnet restore'
            inputs:
              command: 'restore'
              projects: '$(solutionPath)'
              feedsToUse: 'config'                     # usar el nuget.config del repo (feed interno de la organización), NO solo nuget.org -> evita NU1101
              nugetConfigPath: '{{NUGET_CONFIG_PATH}}' # ruta detectada por /cicd-init (0.2). Si el repo NO tiene nuget.config, /cicd-init ELIMINA estas 2 lineas (default nuget.org)

          - task: DotNetCoreCLI@2
            displayName: 'dotnet build (Release)'
            inputs:
              command: 'build'
              projects: '$(solutionPath)'
              arguments: '--configuration $(BuildConfiguration) --no-restore'

          # HALLAZGO H (V5): el agente self-hosted NO limpia $(Agent.TempDirectory) entre builds.
          # Borrar cobertura/opencover previos para que R18/PublishCodeCoverage/reporte no lean uno OBSOLETO (0% falso).
          - task: PowerShell@2
            displayName: 'Limpiar cobertura/opencover obsoletos del temp del agente (HALLAZGO H)'
            inputs:
              targetType: inline
              script: |
                Get-ChildItem $env:AGENT_TEMPDIRECTORY -Recurse -File -ErrorAction SilentlyContinue |
                  Where-Object { $_.Name -like '*cobertura.xml' -or $_.Name -like '*opencover.xml' } |
                  Remove-Item -Force -ErrorAction SilentlyContinue
          # FB-002 (piloto Portal): apuntar a la SOLUCION, no a un unico $(testProject). 'dotnet test'
          # sobre el .sln auto-descubre TODOS los *.Tests presentes y futuros (Portal crecio a 3 proyectos
          # de test y CI solo corria 1). 'dotnet build $(solutionPath)' previo ya los compilo -> --no-build vale.
          # BLOQUE OMITIBLE: si /cicd-init NO detecta NINGUN proyecto de test, ELIMINA este step +
          # 'Publish coverage' + el gate G7 entero (no hay nada que medir). Ver cicd-init FASE 0.2.
          - task: DotNetCoreCLI@2
            displayName: 'dotnet test (solucion completa, with coverage)'
            inputs:
              command: 'test'
              projects: '$(solutionPath)'
              # TRAMPA HALLAZGO H: NO anadir --results-directory (el task ya lo inyecta; duplicarlo rompe dotnet test)
              # Emitir cobertura (gate G7) + opencover (reporte HTML rico con CRAP/complejidad/hotspots, b2).
              # {{TEST_FILTER}} = filter de tests (vacio por defecto). /cicd-init lo rellena si el equipo excluye
              #   tests que no pueden correr en el agente de build (ej. integracion con Docker/Testcontainers, FB-008):
              #   ' --filter "FullyQualifiedName!~Integration"' (con espacio inicial). Persistido en cicd[].testFilter
              #   y re-aplicado en Opcion 4 (NO usar # CUSTOM para esto: duplicaria el step en el re-render).
              arguments: '--configuration $(BuildConfiguration) --no-build{{TEST_FILTER}} --collect:"XPlat Code Coverage" -- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=cobertura,opencover'

          - task: PublishCodeCoverageResults@1               # R4 NO @2
            displayName: 'Publish coverage'
            inputs:
              codeCoverageTool: 'Cobertura'
              summaryFileLocation: '$(Agent.TempDirectory)/**/*cobertura.xml'

          # G7: gate de COBERTURA (nativo, sin herramienta propietaria). WARN-first: reporta y
          # avisa si < umbral, NO bloquea. Parsea el XML Cobertura mas reciente (line-rate/branch-rate).
          # HALLAZGO H: el temp del agente self-hosted persiste entre builds -> ordenar por fecha.
          - template: steps/coverage-gate.yml           # G7 (R18): ops/cicd/scripts/coverage-gate.ps1, sin herramientas externas
            parameters:
              thresholdLine: $(coverageLineThreshold)
              thresholdBranch: $(coverageBranchThreshold)
              mode: warn
                }
                [xml]$cov = Get-Content $xml
                $inv = [System.Globalization.CultureInfo]::InvariantCulture
                $line   = [math]::Round(100 * [double]::Parse($cov.coverage.'line-rate',   $inv), 1)
                $branch = [math]::Round(100 * [double]::Parse($cov.coverage.'branch-rate', $inv), 1)
                Write-Host "G7: cobertura line=$line% branch=$branch% (umbral line>=$(coverageLineThreshold) branch>=$(coverageBranchThreshold)) -> $xml"
                if ($line -lt $(coverageLineThreshold) -or $branch -lt $(coverageBranchThreshold)) {
                  Write-Warning "G7: cobertura por debajo del umbral -> AVISO (WARN-first, no bloquea; politica hooks.policy)."
                }
                exit 0

          # b2: reporte HTML rico de cobertura (ReportGenerator, tool publica de nuget.org).
          # Additivo, NO gatea (continueOnError). Se publica como artefacto 'CoverageReport'.
          # OJO: se genera en $(Agent.TempDirectory), NO en ArtifactStagingDirectory, para no
          # contaminar el artefacto 'drop' que se despliega a IIS.
          - task: PowerShell@2
            displayName: 'Reporte HTML de cobertura (ReportGenerator)'
            continueOnError: true
            inputs:
              targetType: inline
              script: |
                $toolsDir = Join-Path $env:USERPROFILE '.dotnet	ools'
                if (Test-Path $toolsDir) { $env:PATH = "$env:PATH;$toolsDir" }
                & dotnet tool update --global dotnet-reportgenerator-globaltool --ignore-failed-sources 2>&1 | ForEach-Object { Write-Host "    [rg] $_" }
                $global:LASTEXITCODE = 0
                $rg = Join-Path $toolsDir 'reportgenerator.exe'
                if (-not (Test-Path $rg)) { Write-Host "ReportGenerator no disponible (sin acceso a nuget.org); se omite el reporte HTML."; exit 0 }
                # Preferir OpenCover (lleva complejidad); si no hay, usar Cobertura.
                $oc  = Get-ChildItem $env:AGENT_TEMPDIRECTORY -Recurse -Filter '*opencover.xml' -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1 -ExpandProperty FullName
                $cob = Get-ChildItem $env:AGENT_TEMPDIRECTORY -Recurse -Filter '*cobertura.xml' -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1 -ExpandProperty FullName
                $covXml = if ($oc) { $oc } else { $cob }
                if (-not $covXml) { Write-Host "Sin XML de cobertura; se omite el reporte HTML."; exit 0 }
                $reportDir = Join-Path $env:AGENT_TEMPDIRECTORY 'coverage-report'
                & $rg -reports:"$covXml" -targetdir:"$reportDir" -reporttypes:HtmlInline_AzurePipelines
                $global:LASTEXITCODE = 0
                Write-Host "Reporte HTML de cobertura generado en $reportDir (fuente: $covXml)"

          - task: PublishBuildArtifacts@1
            displayName: 'Publish CoverageReport (HTML)'
            continueOnError: true
            inputs:
              PathtoPublish: '$(Agent.TempDirectory)/coverage-report'
              ArtifactName: 'CoverageReport'

          # {{QUALITY_SYNC_STEP}}  <- /cicd-init FASE 2.7 (QR de calidad al dashboard): si el equipo lo acepta,
          # SUSTITUIR esta linea por  '- template: steps/quality-sync.yml'  (materializa el step desde
          # skills/cicd-architect/templates/steps/). Best-effort: continueOnError + sale 0 sin HUB_SERVICE_KEY,
          # NO gatea (eso es el gate G7). El opencover que consume ya lo emite el 'dotnet test' de arriba
          # (Format=cobertura,opencover) -> NO hace falta el coverage.runsettings de la skill. Si se declina, eliminar esta linea.

          # R22: gate de ciberseguridad (verdict-file). NO tumba el Build (continueOnError).
          # Publica el artefacto 'security-report' que parsean los stages de deploy.
          - template: steps/security-scan-build.yml
            parameters:
              stack: dotnet

          - task: DotNetCoreCLI@2
            displayName: 'dotnet publish'
            inputs:
              command: 'publish'
              projects: '$(apiProject)'
              arguments: '--configuration $(BuildConfiguration) --no-build --output $(Build.ArtifactStagingDirectory) /p:GenerateBuildInfoConfigFile=false'

          - task: PublishBuildArtifacts@1
            displayName: 'Publish artifact drop'
            inputs:
              PathtoPublish: '$(Build.ArtifactStagingDirectory)'
              ArtifactName: 'drop'

  # ───────────────────────────────────────────────────────────────────────
  # STAGE 2: DEPLOY DEV (auto)
  # ───────────────────────────────────────────────────────────────────────
  - stage: DeployDev
    displayName: 'Deploy a DEV (on-demand)'
    dependsOn: Build
    condition: and(succeeded(), eq(variables['DeployEnv'], 'dev'))    # R20: solo si /cicd-deploy --env dev
    jobs:
      - job: DeployToDev
        pool:
          name: {{BUILD_POOL}}
          demands:
            - DeployTarget -equals {{DEPLOY_DEMAND_DEV}}   # R1/R25: <env>-<app|svc> (app=dev01, svc=svc01)
        timeoutInMinutes: 15
        steps:
          - checkout: none                                   # R8
          - template: steps/security-verdict-gate.yml        # R22 (DEV = WARN)
            parameters:
              mode: warn
          - template: steps/download-artifact-rest.yml       # R3
{{CONFIG_INJECT_STEP}}
          - task: IISWebAppDeploymentOnMachineGroup@0        # R4
            inputs:
              WebSiteName: 'Default Web Site'
              VirtualApplication: '$(iisVirtualApp)'
              Package: '$(MsDeployPackage)'
              RemoveAdditionalFilesFlag: true
              TakeAppOfflineFlag: true                       # R10 .NET in-process

  # ───────────────────────────────────────────────────────────────────────
  # STAGE 3: DEPLOY DEMO (on-demand: DeployEnv=pre es el gate)
  # ───────────────────────────────────────────────────────────────────────
  - stage: DeployDemo
    displayName: 'Deploy a DEMO/Pre (on-demand)'
    dependsOn: Build
    condition: and(succeeded(), eq(variables['DeployEnv'], 'pre'))    # R20: /cicd-deploy --env pre (DEMO = staging / pre)
    jobs:
      # DEMO/Pre SIN ManualValidation en on-demand. El gate ya es la condicion
      # DeployEnv=='pre' + el comando /cicd-deploy --env pre (la aprobacion explicita). PROD si gatea.
      # (Modelo 'auto' -DEMO se despliega en push sin DeployEnv-: re-anadir aqui un job WaitForApproval con
      #  ManualValidation@0 + 'dependsOn: WaitForApproval' en DeployToDemo. Ver P2-bis en /cicd-init.)
      - job: DeployToDemo
        condition: succeeded()
        pool:
          name: {{BUILD_POOL}}
          demands:
            - DeployTarget -equals {{DEPLOY_DEMAND_PRE}}   # R1/R25 (app=demo01, svc=demosvc01)
        timeoutInMinutes: 30
        steps:
          - checkout: none
          - template: steps/security-verdict-gate.yml        # R22 (DEMO/Pre = BLOCK)
            parameters:
              mode: block
          - template: steps/download-artifact-rest.yml
{{CONFIG_INJECT_STEP}}
          - template: steps/backup-pre-deploy.yml            # R15 capa 1
          - task: IISWebAppDeploymentOnMachineGroup@0
            inputs:
              WebSiteName: 'Default Web Site'
              VirtualApplication: '$(iisVirtualApp)'
              Package: '$(MsDeployPackage)'
              RemoveAdditionalFilesFlag: true
              TakeAppOfflineFlag: true
              AdditionalArguments: '-enableRule:DoNotDeleteRule'  # R15 capa 2
          - template: steps/smoke-strict-dotnet.yml          # R11 estricto .NET
          - template: steps/rollback-on-fail.yml             # R15 capa 3

  # ───────────────────────────────────────────────────────────────────────
  # STAGE 4: DEPLOY PROD (on-demand, 2 servers rolling) [PLACEHOLDER]
  # ───────────────────────────────────────────────────────────────────────
  # TEC-006 (CRITICO): NO usar `deployment` job con `environment:` mientras PROD sea
  # placeholder. Azure DevOps valida el `environment` AL ENCOLAR -> ANTES de evaluar las `condition`
  # -> un environment inexistente tumba TODO el pipeline (Build incluido), aunque PROD este
  # gateado por DeployEnv (la condition NO exime de validar recursos). Ademas un name CON
  # PUNTO ('{{PROYECTO_NOMBRE}}-Prod' = 'MyCompany.Xxx-Prod') Azure DevOps lo parsea como
  # environmentName.resourceName ("MyCompany"."Xxx-Prod"). Por eso PROD son `job` normales:
  # los `demands` se evaluan en RUNTIME, no en validacion.
  #
  # PROD nodos por tipo (R1/R25): app -> APPNODE01/APPNODE02_DEPLOY ; svc -> STORM01/STORM02_DEPLOY
  # (STORM02 apagado: /cicd-init deja solo el nodo A para svc hasta que se encienda).
  # AL APROVISIONAR PROD (agentes {{PROD_NODE_A}}/{{PROD_NODE_B}} + grupo aprobador >=2):
  #   1) Crear el Environment en Azure DevOps con name SIN PUNTOS: '{{PROYECTO_SLUG}}Prod'.
  #   2) Convertir DeployToProd_A a `deployment` con `environment: '{{PROYECTO_SLUG}}Prod'`
  #      + `strategy: { runOnce: { deploy: { steps: [...] } } }` (activa el approval de grupo).
  - stage: DeployProd
    displayName: 'Deploy a PROD (on-demand, 2 servers rolling) [PLACEHOLDER hasta aprovisionar]'
    dependsOn: Build                                                 # R20: independiente, NO encadenado tras Demo
    condition: and(succeeded(), eq(variables['DeployEnv'], 'pro'))    # R20: /cicd-deploy --env pro
    jobs:
      - job: DeployToProd_A
        pool:
          name: {{BUILD_POOL}}
          demands:
            - Agent.Name -equals {{PROD_NODE_A}}               # R1/R25 (app=APPNODE01_DEPLOY, svc=STORM01_DEPLOY); solo runtime, no rompe la validacion
        timeoutInMinutes: 30
        steps:
          - checkout: none
          - template: steps/security-verdict-gate.yml        # R22 (PROD = BLOCK)
            parameters:
              mode: block
          - template: steps/download-artifact-rest.yml
{{CONFIG_INJECT_STEP}}
          - template: steps/backup-pre-deploy.yml
          - task: IISWebAppDeploymentOnMachineGroup@0
            inputs:
              WebSiteName: 'Default Web Site'
              VirtualApplication: '$(iisVirtualApp)'
              Package: '$(MsDeployPackage)'
              RemoveAdditionalFilesFlag: true
              TakeAppOfflineFlag: true
              AdditionalArguments: '-enableRule:DoNotDeleteRule'
          - template: steps/smoke-strict-dotnet.yml
          - template: steps/rollback-on-fail.yml

      - job: DeployToProd_B
        dependsOn: DeployToProd_A
        condition: succeeded()
        pool:
          name: {{BUILD_POOL}}
          demands:
            - Agent.Name -equals {{PROD_NODE_B}}               # R1/R25 (app=APPNODE02_DEPLOY, svc=STORM02_DEPLOY; /cicd-init lo omite si el nodo B esta apagado)
        timeoutInMinutes: 30
        steps:
          - checkout: none
          - template: steps/security-verdict-gate.yml        # R22 (PROD = BLOCK)
            parameters:
              mode: block
          - template: steps/download-artifact-rest.yml
{{CONFIG_INJECT_STEP}}
          - template: steps/backup-pre-deploy.yml
          - task: IISWebAppDeploymentOnMachineGroup@0
            inputs:
              WebSiteName: 'Default Web Site'
              VirtualApplication: '$(iisVirtualApp)'
              Package: '$(MsDeployPackage)'
              RemoveAdditionalFilesFlag: true
              TakeAppOfflineFlag: true
              AdditionalArguments: '-enableRule:DoNotDeleteRule'
          - template: steps/smoke-strict-dotnet.yml
          - template: steps/rollback-on-fail.yml

# =============================================================================
# Placeholders a sustituir por /cicd-init:
#   {{PROYECTO_NOMBRE}}, {{PROYECTO_SLUG}}, {{RAMA_BASE}}, {{PIPELINE_NAME}}, {{NET_VERSION}},
#   {{SLN_PATH}}, {{API_CSPROJ}}, {{TESTS_CSPROJ}}, {{IIS_VIRTUAL_APP}},
#   {{IIS_APP_POOL}}, {{APPROVER_EMAIL}}, {{LISTA_SECRETOS_VG}},
#   {{TEMPLATE_STAMP}} (sello version, FASE 2.8), {{TEST_FILTER}} (filter tests, def. vacio, FASE 2),
#   {{QUALITY_SYNC_STEP}} + {{QUALITY_SYNC_VARS}} (QR de calidad, FASE 2.7; rellenar o eliminar)
#   {{CONFIG_INJECT_STEP}} (FB-001/R23 .NET SDK-style, en CADA stage de deploy tras download-artifact):
#     - Modo Key Vault -> ELIMINAR la linea (la app lee de KV; el deploy no inyecta).
#     - Modo VG-injection (sin KV) -> /cicd-init genera un step PowerShell que sustituye por clave
#       las secretas ("clave": "" -> valor del VG via env:, escape JSON, Set-Content UTF8 R13, fail-fast)
#       sobre $(MsDeployPackage)\appsettings.json + anade `variables: - group: <App>-<env>` al stage.
#       NUNCA FileTransform@1 (JSONC + claves con puntos). Rollback: excluir tambien appsettings.json.
#   {{PROYECTO_SLUG}} = name SIN PUNTOS para Environments Azure DevOps (ej. 'MyAppWeb' /
#                       'WebPortal'); NUNCA con '.' (TEC-006: 'A.B-Prod' se parsea env.resource).
#
# Templates de steps (referenciados con `template: steps/...`) viven en steps/ JUNTO
# a azure-pipelines.yml (raiz del repo). /cicd-init los materializa desde
# skills/cicd-architect/templates/steps/:
#   download-artifact-rest.yml     - R3 REST API download
#   security-scan-build.yml        - R22 scan en Build (verdict-file, continueOnError)
#   security-verdict-gate.yml      - R22 gate en deploy (warn DEV / block PRE-PROD)
#   backup-pre-deploy.yml          - R15 capa 1
#   smoke-strict-dotnet.yml        - R11 estricto .NET
#   rollback-on-fail.yml           - R15 capa 3
#
# Para Fase 1 (sin CD), eliminar stages DeployDev/Demo/Prod y dejar solo Build.
# Para stack Vue+Vite+TS ver azure-pipelines.fase2.vue.yml.template.
#
# ── Modelo de deploy (R20) ───────────────────────────────────────────────────
# Este template usa el model ON-DEMAND (default):
#   - push/`/cicd-release` => DeployEnv vacio => solo corre Build (NINGUN deploy)
#   - `/cicd-deploy --env dev|pre|pro` => encola con DeployEnv=<env> => activa ese stage
#   - PRE/PROD mantienen sus gates (ManualValidation / Environment approval) como
#     gobierno adicional, ademas de la condicion DeployEnv.
#   - Mapeo: --env pre -> stage DeployDemo (staging = pre).
#
# Para el model AUTO/promocion (CD continuo a DEV en cada push), /cicd-init lo
# genera ajustando:
#   - DeployDev:  condition: succeeded()        (sin DeployEnv)
#   - DeployProd: dependsOn: DeployDemo          (encadenado, no independiente)
#   y eliminando la variable DeployEnv. La eleccion del model de deploy es la
# pregunta P2-bis de /cicd-init FASE 1 (on-demand / auto / branch-gated).#
# ── Modelo BRANCH-GATED (R24) ──────────────────────────────────────
# Para estrategias con ramas por entorno (gitlab-flow, gitflow): on-demand + gate
# por rama origen. /cicd-init lo genera ajustando este template:
#   - trigger.branches.include: AMBAS ramas ({{ramaBase}} + {{ramaDevelop}}, R21)
#   - DeployDev/DeployDemo: condition += eq(variables['Build.SourceBranch'], 'refs/heads/{{ramaDevelop}}')
#   - DeployProd:           condition += eq(variables['Build.SourceBranch'], 'refs/heads/{{ramaBase}}')
#   - /cicd-deploy deriva el sourceBranch del entorno pedido (mapeo R24)
# Asi un build de {{ramaDevelop}} NUNCA puede desplegar a PROD. Para netfx existe la
# variante completa azure-pipelines.fase2.netfx.branch-gated.yml.template (3 VSBuild
# condicionales por rama + drop-dev/pre/pro, R23 hibrido).
# =============================================================================

← Volver a la ficha de cicd-architect