Azure DevOps Hour 5: Production-Grade Pipelines

Templates, multi-stage promotion, deployment strategies, Azure Artifacts, version numbers, and quality gates, turning a “pipeline that runs” into a production pipeline that is reusable, auditable, and rollback-ready
Azure DevOps ServicesYAML templates · extendsAzure ArtifactsPublishCodeCoverageResults@2Verified against learn.microsoft.com · 2026-11-15
Overall learning objectives
  • Distinguish includes template and extends template, write typed parameters (stepList,object,values: validation), and use ${{ each }} / ${{ if }} to generate structure at compile time, and keep templates in a separate repo, referenced at a resources.repositories + ref pinned version.
  • Explain the three hard limits of templates: at most 100 YAML files, at most 100 levels of nesting, and at most 20 MB of parse memory; understand the full sequence: compile-time expansion, then generation of the final plan, then checks on protected resources before a stage starts.
  • Design dev → prod multi-stage pipelines: dependsOn,condition,ManualValidation@1, and cross-stage output variables (dependencies and stageDependencies two syntaxes).
  • Use in a deployment job runOnce / rolling / canary and lifecycle hooks preDeploy → deploy → routeTraffic → postRouteTraffic → on.success/failure, implementing a real canary with Container Apps revision weights.
  • Operations Azure Artifacts: organization- and project-scoped feeds, upstream sources, views @local/@prerelease/@release, retention policies (package exemptions in views), npm/NuGet/pip/Maven/Universal Packages authentication tasks, and publishing the myapp Python package to a feed.
  • Use the name: build number format,counter() and GitVersion to generate semantic versions, automatically create Git tags, and generate release notes; migrate classic releases to YAML; and build quality gates from test results, code coverage, and branch policies.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (project myapp-lab)
0Before classPrep: shared template repoReuse the service connection and Container Apps from Lesson 3, and create a new pipeline-templates repo and Artifacts feedProduction readiness self-assessmentTwo repos + one feed + two environments
100–08Template deep diveincludes vs extends, parameter types and validation, cross-repo templates and ref pinning, each/if, template limits, Required template checksCore animation: extends expansion and protected resource checksBuild template + required extends
208–15Multi-stage and environment promotionstage dependency graph, conditions, ManualValidation, cross-stage output variables, lockBehaviorDependency graph and condition evaluation simulatordev → prod promotion
315–22Deployment strategiesdeployment job, runOnce/rolling/canary, hook order, output variable namingCanary hook timeline (failures can be injected)Container Apps 10% → 50% → 100%
422–30Azure ArtifactsFeeds and scopes, upstream sources, views, retention policies, 5 package types and authentication tasks, 2 GiB free storagePackage resolution: local → upstream → savePublish the myapp Python package and promote it to @release
530–36Version numbers, tags, and release notesBuild number format, counter, GitVersion 6, Git tags, release notes automationCounter calculatorAutomatic versioning + tagging
636–43Migrating classic releases to YAMLConcept mapping, Export to YAML limitations, migration path, new organizations have classic pipelines disabled by defaultClassic → YAML mapping cardRewrite a classic release as YAML
743–52Tests, code coverage, and quality gatesPublishTestResults@2, PublishCodeCoverageResults@2, diff coverage and PR status, branch policies, Test PlansQuality gate evaluatorpytest + coverage gate
852–60Recap, self-check, and cleanupKnowledge map for the first five hours, troubleshooting tree, costs, and cleanupInteractive troubleshooting treeClean up resources
—After classCheat sheet · Capstone labShared template repo + required extends + dev→prod canary + Python package + coverage gateFinal quiz, 12 questionsCapstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key syntax / commandsLab
Write reusable templates (parameters, each/if)✓✓✓··✓·✓template:,parameters:,${{ each }}M1 lab
Enforce compliance with extends + Required template✓······✓extends:, Approvals and checksRequired template
Multi-stage promotion and manual approval·✓✓··✓··dependsOn,ManualValidation@1dev→prod
Pass output variables across jobs / stages·✓✓·✓··✓isOutput=true,stageDependenciesPassing image tags
Deployment strategies and rollback hooks··✓··✓··strategy: canary,on.failureContainer Apps canary
Package management and upstream sources···✓✓··✓TwineAuthenticate@1,PipAuthenticate@1Python packages
Semantic versions and release notes···✓✓···name:,counter(), GitVersionautomatic tagging
Classic → YAML migration·✓···✓··Export to YAML, environmentsRewrite a classic release
Tests, coverage, and quality gates······✓✓PublishTestResults@2,azurepipelines-coverage.ymlcoverage gate

Topics not covered in this lesson (and where to learn them)

TopicWhy it is not in this lessonWhere to learn it
YAML basics, triggers, variables, pipeline artifactsCovered in Lesson 2; used directly in this lessonHour 2
Workload identity federation service connections, Environments approvals, deploying to Container Apps/AKSBuilt in Lesson 3; reused in this lessonHour 3
Enforcing templates at organization scale, protected resource governance, Key Vault variable groups, GHAzDOBelongs to the security and governance topic; this lesson only covers Required template on a single service connectionHour 6
Agent performance, caching deep dive, Managed DevOps PoolsBelongs to the performance and troubleshooting topicHour 7
Packaging and OCI publishing of Helm chartsCovered in the Helm courseHelm 8-hour course

How to use this courseware

10 pages per module
Theory · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · narration · video. Start with “Theory” and the Module 1 core animation, then do the “Lab.”
Learning progress
A quiz score of 70% or more, or clicking “Mark this module complete,” counts toward progress. Progress is saved in this browser (if local storage is disabled, it is cleared on refresh).
Chinese narration
The “Audio” page uses the browser's built-in Web Speech API (en-US) to read the narration script aloud; if no Chinese voice pack is installed, you can read the script directly.
Version notes Azure DevOps Services is a continuously released SaaS and has no “version number.” The facts in this lesson were verified against learn.microsoft.com on 2026-11-15: template limits (100 files / 100 levels / 20 MB), parameter type table (stringList cannot be used in templates),ManualValidation@1 (can only be used in agentless jobs, with a maximum wait of 30 days), check execution order (static checks → pre-approval → dynamic checks → post-approval → exclusive lock),PublishCodeCoverageResults@2, Azure Artifacts views and retention policies, Artifacts free storage of 2 GiB per organization, and classic pipeline creation disabled by default for new organizations (from Sprint 226). For GitVersion, the GitTools task v4.7.0 + GitVersion 6.8.x is authoritative (GitHub releases, 2026-07). Some defaults in the on-premises Azure DevOps Server differ (for example, the default for ManualValidation allowApproversToApproveTheirOwnRuns default), so switch the documentation version selector.

Module 0 · Prep: shared template repo (complete before class)

Reuse the Azure resources and service connection from Lesson 3, and create a template repo, an Artifacts feed, and two environments
Before class ≈ 10 minProject myapp-lab
Prerequisites
  • CompletedLesson 2(the myapp repo has a working azure-pipelines.yml) andLesson 3(resource group rg-ado-lab, region canadacentral, ACR, Container Apps environment and app ca-myapp-dev / ca-myapp-prod, ARM service connection sc-azure-myapp, of type workload identity federation).
  • If your organization cannot run Microsoft-hosted agents (free parallel jobs must be requested; until approved, use the self-hosted agent pool registered in Lesson 2 lab-pool instead; in the YAML below, make the matching change at the pool location(s) accordingly).
  • Local machine: Azure CLI 2.6x+ and the azure-devops extension, Git, and Python 3.12 (used in labs M4/M7).
  • Permissions: Project Administrator (to create repos, environments, and checks); Feed Owner on the Artifacts feed (automatically granted to the feed creator).
Naming conventions This lesson uses the following names. If you used different names in Lesson 3, replace them consistently throughout the lesson: organization https://dev.azure.com/<org>, project myapp-lab, app repo myapp, template repo pipeline-templates, service connection sc-azure-myapp, environments myapp-dev / myapp-prod, Artifacts feed myapp-feed (project scope), ACR acrmyapp<random suffix> (Lesson 3 ACR=acrmyapp$RANDOM, example acrmyapp21877), Container Apps app ca-myapp-dev and ca-myapp-prod (Lesson 3's APP_DEV / APP_PROD).

Step 1: Set CLI defaults and check existing resources

az login
az devops configure --defaults organization=https://dev.azure.com/<org> project=myapp-lab
az devops service-endpoint list --query "[].{name:name,type:type,scheme:authorization.scheme}" -o table
az pipelines list --query "[].{id:id,name:name}" -o table
az containerapp list -g rg-ado-lab --query "[].{name:name,fqdn:properties.configuration.ingress.fqdn}" -o table
Name             Type     Scheme
---------------  -------  ------------------------
sc-azure-myapp   azurerm  WorkloadIdentityFederation

Id    Name
----  ----------
12    myapp-ci

Name       Fqdn
---------  ----------------------------------------------------
myapp-dev  myapp-dev.purplesea-1a2b3c4d.canadacentral.azurecontainerapps.io
myapp      myapp.purplesea-1a2b3c4d.canadacentral.azurecontainerapps.io

If Lesson 3 created only one app, create the second one using the Module 4 commands from Lesson 3 ca-myapp-dev (the same Container Apps environment is fine; scaling to 0 replicas when idle costs almost nothing).

Step 2: Create the template repo and push the skeleton

az repos create --name pipeline-templates
git clone https://dev.azure.com/<org>/myapp-lab/_git/pipeline-templates
cd pipeline-templates
mkdir -p templates/steps templates/jobs templates/stages
cat > README.md <<'EOF'
# pipeline-templates
Shared YAML templates. Consumers must pin the version using resources.repositories + ref: refs/tags/vX.Y.Z.
EOF
git add . && git commit -m "chore: init template repo" && git push
git tag v0.1.0 && git push origin v0.1.0

Step 3: Create the Artifacts feed and two environments

# Project-scoped feed (organization-scoped feeds are created in the portal: Artifacts → Create Feed → Scope: Organization)
az artifacts feed create --name myapp-feed 2>/dev/null || echo "If the CLI does not support this, create it in the portal: Artifacts → Create Feed"
# Environments: create via the REST API (or in Pipelines → Environments → New environment)
for e in myapp-dev myapp-prod; do
  az devops invoke --area distributedtask --resource environments \
    --route-parameters project=myapp-lab --http-method POST --api-version 7.1 \
    --in-file <(echo "{\"name\":\"$e\",\"description\":\"part5 lab\"}") -o none
done
az devops invoke --area distributedtask --resource environments --route-parameters project=myapp-lab --api-version 7.1 --query "value[].name"
[
  "myapp-dev",
  "myapp-prod"
]
Caveataz artifacts The command group is mainly az artifacts universal is primary; whether it is provided feed create depends on the extension version. If the commands above fail, create the resource in the portal directly; the course does not depend on them. az devops invoke of the --in-file Process substitution does not work in Windows PowerShell, so write the JSON to a file first.

Step 4: Grant the build identity permissions on the feed

Pipelines publishes packages using the Build Service identity: project-level myapp-lab Build Service (<org>), and organization-level Project Collection Build Service (<org>). Open Artifacts → myapp-feed → ⚙ Feed settings → Permissions → Add users/groups, and set both identities to Feed Publisher (Contributor). If you skip this step, Module 4's twine upload will get a 403.

Warm-up: answer from memory (30 seconds)

Lesson 2's - template: x.yml and extends: template: what is the difference?

The former takes the template content and inserts it at the current location (includes); the latter makes the entire pipeline use the template as its skeleton, and the pipeline can only supply content to the template through parameters. This is exactly the structure that Required template checks can verify.

Are approvals written in YAML?

No. Approvals and checks are configured on protected resources (environments, service connections, agent pools, variable groups, secure files, repositories), and people who edit YAML cannot bypass them. In Lesson 3 you already tried this on myapp-prod the relevant resource.

Production readiness self-assessment (10 items)

Check off the myapp pipeline items you have already achieved (saved in this browser). Check them off again after completing the capstone lab.

Environment self-check checklist

Module 1 · Template deep dive: includes, extends, and parameters

00:00 – 08:00 · Templates are expanded at “compile time,” so no templates remain in the final plan; checks run against protected resources before a stage starts
8 min100 files / 100 levels / 20 MBstringList cannot be used in templates★★★★★
Learning objectives
  • Explain the difference between includes and extends templates in structural control, and why only extends can enforce “compliance” together with Required template checks.
  • Choose the correct data type for template parameters (string/number/boolean/object/step/stepList/job/jobList/deployment/deploymentList/stage/stageList), use values: for enum validation, and understand that scalars without a declared type are treated as strings.
  • Put templates in a separate repo, use resources.repositories to reference them, and use ref: refs/tags/vX.Y.Z or a 40-character SHA to pin the version; know that when no ref is given, the default is refs/heads/main.
  • Use ${{ each }},${{ if/elseif/else }} to generate job/step at compile time, and identify the cause when the 100 files / 100 levels / 20 MB limits are exceeded.
Prerequisites: Lesson 2, Module 7 (template basics). Importance:★★★★★ (foundational for all platform teams)

What: two kinds of templates

  • Includes template (insertion): - template: steps/build.yml Written in the steps/jobs/stages/variables list; template content is inserted as-is at the point of reference, similar to a programming language's #include include. A variable template can only define variables.
  • Extends template (inheritance): the top level of the pipeline declares extends: template: secure-pipeline.yml@templates, the structure of the entire pipeline is determined by the template, and consumers can only “fill in the blanks” through parameters. The template can check, filter, and reject steps in parameters (the official example rejects CmdLine@2 and script).

Why: why templates are needed

If 50 services each write their own pipeline, you quickly end up with 50 different ways of doing security scanning, signing, and deployment. Templates consolidate “how to build and deploy” into one repo; the platform team changes it once and tags it, and every consumer gets the same behavior after upgrading its ref. extends + Required template checks also ensure that anyone who wants to use a production service connection must go through a platform-approved template.

How: processing sequence (core)

  1. Resolve repository resources: resolved only once at the start of the run resources.repositories, after which the entire run uses the same commit.
  2. Compile-time expansion: read the entry-point YAML and template: and extends: recursively load files, substitute parameters, and evaluate all ${{ }} (compile-time expressions, which can see parameters and static variables but not runtime variables), and expand each, and prune if.
  3. Limit checks: during expansion, count files (≤ 100), nesting depth (≤ 100), and parse memory (≤ 20 MB, roughly equal to 600 KB–2 MB of YAML on disk).
  4. Generate the final plan: the result is a tree containing only stages, jobs, and steps,with no templates left (visible via “Download full YAML” on the run page). The run also records which template was extended (repo, ref, path).
  5. Run checks before the stage starts: for each protected resource used by the stage, run checks in category order: static checks (Branch control,Required template, Evaluate artifact) → pre-approval → dynamic checks (Approval, Invoke Azure Function/REST API, Business hours, Azure Monitor) → post-approval → exclusive lock. If any check ends in a final failure, the stage does not run.
  6. Run: jobs are queued, an agent picks them up,$[ ] runtime expressions and $( ) macros are evaluated only at this point.

Parameter type quick reference (official table)

TypeDescriptionTypical use
string / number / booleannumber Usable values: Restricted values; boolean can only be true/falseImage names, replica counts, switches
objectAny YAML structureEnvironment lists, key-value maps; in templates, replaces stringList
step / stepLista single step / step sequenceLets consumers insert custom build steps
job / jobList,deployment / deploymentList,stage / stageListStructured type, validated against the YAML schema; jobList/deploymentList/stageList can take templateContextan extends template receives the consumer's job/stage and wraps pre- and post-steps
stringListMulti-select list,cannot be used in templates (only usable for pipeline runtime parameters)Select multiple regions at runtime

Pitfall: Undeclared type scalar parameters are treated as strings; eq(true, parameters['x']) non-empty strings in 'false' are converted to True. Parameter default values must be literals and cannot reference variables.

When: which one to choose

ScenarioRecommendationReason
Reusing a few steps (installing dependencies, running tests)includes (steps template)Simple, non-intrusive
Standardizing multi-environment deployment stagesincludes (stage template + parameters)Instantiating dev/test/prod from the same template
Must guarantee scanning, signing, and use of only approved tasksextends + Required template checksThe template controls the structure, checks run server-side, and YAML edits cannot override them
Centralizing variable definitionsvariables templateA variables template can contain only variables

Comparison with similar technologies

Azure Pipelines templateGitHub ActionsGitLab CI
Reuse stepssteps templatecomposite actioninclude: + !reference
Reuse an entire pipelineextends templatereusable workflow (workflow_call)include: + extends:
Server-side enforcementRequired template checks (resource-level)Organization rulesets with required workflowsCompliance pipelines (paid)
Version pinningref: Tag / branch / SHA@v1 / SHAref:
Common misconceptions① “A template can decide which steps to insert at runtime based on the previous step's result.” No. Templates are expanded at compile time; runtime results can only be used with condition conditions to control whether existing steps run. ② “Scripts in the template repo can be called directly.” No. Only the template file is used; to use scripts from the template repo, you must explicitly check out that repo in the job checkout: templates. ③ “If you omit ref, the latest tag is used.” The default is refs/heads/main the latest commit of the branch; as soon as the platform team pushes, every consumer's next run changes.

Architecture diagram: where templates come from and where they are expanded during a run

myapp repo azure-pipelines.ymlresources.repositories:templates @ refs/tags/v1.2.0extends: …@templates pipeline-templates repo templates/secure-pipeline.ymltemplates/jobs/build-python.ymltemplates/stages/deploy-aca.ymltag v1.2.0 → commit 9f3c… Pipelines orchestration service (compile time) ① Resolve repositories (resolved only once) ② Load entry point + extends template ③ Validate parameter types / values ④ Evaluate ${{ }}: each / if / parameters ⑤ Count: files ≤100 · depth ≤100 · memory ≤20MB ⑥ Generate final plan (no templates) Record extends source: repo / ref / path Failure → the run reports the YAML error immediately, without queuing Before the stage starts: checks Resources: sc-azure-myapp / myapp-prod 1 Static: Branch control · Required template 2 Pre-approval → 3 Dynamic: Approval, REST… 4 Post-approval → 5 Exclusive lock Any final failure → the stage does not run Runtime Job queued → agent picks it up → $[ ] and $( ) evaluated Logs / artifacts / deployment records
Figure 1-1: templates are expanded at compile time in the orchestration service; checks on protected resources run before each stage starts, and only the extends source recorded in the final plan is trusted

Flowchart: structural differences between includes and extends

includes: the pipeline is the skeleton, templates are the parts stages (structure decided by the pipeline author) - template: build.yml script: any command - template: deploy.yml Authors can add any step before or after the template, so it cannot be “enforced” extends: the template is the skeleton, the pipeline only fills in parameters Template: pre-scan (fixed) ${{ parameters.buildSteps }} (filtered by the template) Template: sign + deploy (fixed) Required template checks verify “whether it extends this template”
Figure 1-2: only extends lets the platform team control the structure, which suits security and compliance

Core animation: extends template expansion and protected resource checks

After you select a scenario, play it step by step: pipeline YAML → merge template → expand each/if → generate final plan → run checks against the service connection/environment → run. The left side shows the “current document” processed by the orchestration service, the right side is the checks panel, and the terminal below shows the real information you would see on the run page.

Document in the orchestration service
Checks panel (sc-azure-myapp / myapp-prod)

Core syntax and commands

Syntax / commandPurposeNotes
- template: path.yml + parameters:Insert steps/jobs/stages/variables templateA path starting with / is an absolute path within the repo; otherwise, it is relative to the current file
extends: { template: x.yml@templates, parameters: {...} }Uses the template as the skeletonA pipeline has only one extends
resources.repositories[].refPin the template versionrefs/tags/v1.2.0,refs/heads/release or a 40-character SHA; if omitted, it defaults to refs/heads/main
@selfReference the consumer repo's files in an extends templatee.g. - template: BuildJobs.yml@self
${{ each x in parameters.list }}Compile-time loopIterates over object, stepList, and jobList; can also iterate over parameters itself (key-value pairs)
${{ if }} / ${{ elseif }} / ${{ else }}Compile-time conditional insertionCan only be used at mapping or sequence key positions
az pipelines run --parameters k=vStart with runtime parametersType-validate parameter values
Run page ⋯ → Download full YAMLView the expanded final YAMLThe preferred way to check whether each/if expanded as expected

steps template: typed and validated parameters

parameters:
- name: pythonVersion
  type: string
  default: '3.12'
  values: ['3.11', '3.12', '3.13']     # enum validation: passing 3.10 fails compilation immediately
- name: coverageThreshold
  type: number
  default: 80
- name: extraSteps
  type: stepList                        # consumers can insert custom steps
  default: []

steps:
- task: UsePythonVersion@0
  inputs: { versionSpec: '${{ parameters.pythonVersion }}' }
- script: |
    python -m pip install -U pip
    pip install -r requirements.txt -r requirements-dev.txt
  displayName: Install deps
- ${{ each step in parameters.extraSteps }}:
  - ${{ step }}
- script: pytest --junitxml=test-results.xml --cov=app --cov-report=xml --cov-fail-under=${{ parameters.coverageThreshold }}
  displayName: pytest (coverage ≥ ${{ parameters.coverageThreshold }}%)

Reference a cross-repo template and pin the version

resources:
  repositories:
  - repository: templates          # alias, used in @templates
    type: git                      # Azure Repos; for GitHub use type: github + endpoint
    name: myapp-lab/pipeline-templates
    ref: refs/tags/v1.2.0          # pin to the tag

stages:
- stage: Build
  jobs:
  - job: Test
    pool: { vmImage: ubuntu-latest }
    steps:
    - template: templates/steps/python-test.yml@templates
      parameters:
        pythonVersion: '3.12'
        coverageThreshold: 80

each + if: use one object parameter to generate stages for multiple environments

parameters:
- name: environments
  type: object
  default:
  - { name: dev,  app: myapp-dev, approval: false }
  - { name: prod, app: myapp,     approval: true }

stages:
- ${{ each env in parameters.environments }}:
  - stage: Deploy_${{ env.name }}
    jobs:
    - ${{ if eq(env.approval, true) }}:
      - job: Confirm_${{ env.name }}
        pool: server
        steps:
        - task: ManualValidation@1
          inputs: { notifyUsers: '', instructions: 'Confirm deploy to ${{ env.name }}' }
    - deployment: Deploy
      ${{ if eq(env.approval, true) }}:
        dependsOn: Confirm_${{ env.name }}
      environment: myapp-${{ env.name }}
      pool: { vmImage: ubuntu-latest }
      strategy:
        runOnce:
          deploy:
            steps:
            - script: echo "deploy to ${{ env.app }}"

How to verify: After the run, download the full YAML from the run page; you should see two stages: Deploy_dev,Deploy_prod, and only prod contains Confirm_prod. Common mistakes: Putting ${{ if }} in a list item value position (for example, with the wrong indentation) - ${{ if … }}: script: … produces the error “A template expression is not allowed in this context.”

Lab 1: Build template + required extends (about 8 min)

Write the extends skeleton in the template repo: it fixes the pre-checks and release steps, allows consumers to supply only build steps, and rejects script/CmdLine@2 (only allows bash and tasks, to simplify auditing).
parameters:
- name: buildSteps
  type: stepList
  default: []
- name: deployStages
  type: stageList
  default: []

stages:
- stage: Build
  jobs:
  - job: Build
    pool: { vmImage: ubuntu-latest }
    steps:
    - checkout: self
      fetchDepth: 0
    - bash: echo "##[section]platform pre-build: secret scan / policy check"
      displayName: 'Platform: pre-build'
    - ${{ each step in parameters.buildSteps }}:
      - ${{ each pair in step }}:
          ${{ if in(pair.key, 'script', 'powershell') }}:
            '${{ pair.key }} is not allowed by platform template': error
          ${{ elseif eq(pair.value, 'CmdLine@2') }}:
            '${{ pair.value }} is not allowed by platform template': error
          ${{ else }}:
            ${{ pair.key }}: ${{ pair.value }}
    - bash: echo "##[section]platform post-build: SBOM / sign"
      displayName: 'Platform: post-build'
- ${{ parameters.deployStages }}
cd pipeline-templates
mkdir -p templates && $EDITOR templates/secure-pipeline.yml   # paste the content above
git add . && git commit -m "feat: secure extends template" && git push
git tag v1.0.0 && git push origin v1.0.0

This follows the official example's rejection technique: generate an invalid key in a mapping (such as 'script is not allowed…': error), which triggers a YAML error at compile time, so the pipeline is not queued.

Change myapp to extends:
trigger: [ main ]
resources:
  repositories:
  - repository: templates
    type: git
    name: myapp-lab/pipeline-templates
    ref: refs/tags/v1.0.0
extends:
  template: templates/secure-pipeline.yml@templates
  parameters:
    buildSteps:
    - task: UsePythonVersion@0
      inputs: { versionSpec: '3.12' }
    - bash: pip install -r requirements.txt && python -m compileall app
      displayName: Build
git add azure-pipelines.yml && git commit -m "ci: extend platform template v1.0.0" && git push
az pipelines runs list --pipeline-ids $(az pipelines show --name myapp-ci --query id -o tsv) --top 1 -o table
Run ID    Number      Status     Result     Pipeline ID    Pipeline Name    Source Branch
--------  ----------  ---------  ---------  -------------  ---------------  ---------------
318       20261115.3  completed  succeeded  12             myapp-ci         refs/heads/main

On the first reference to another repo, the run may wait for “This pipeline needs permission to access a resource”; click View → Permit. The log should show these, in order: Platform: pre-build,Build,Platform: post-build.

Verify the rejection logic: add a line to buildSteps - script: curl http://example.com | sh and push.
/azure-pipelines.yml (Line: 1, Col: 1): Unexpected value 'script is not allowed by platform template'

The run fails immediately and no job is queued; this is a compile-time rejection. Revert this line before continuing.

Add a Required template check on the service connection: Project settings → Service connections → sc-azure-myapp → ⋯ → Approvals and checks → + → Required template: Repository type Azure Repos, Repository pipeline-templates, Ref refs/tags/v1.0.0, Path templates/secure-pipeline.yml. Add the same check to the environment myapp-prod as well.
Verify the check: create a temporary pipeline that does not extend bypass-test.yml, and in a job directly AzureCLI@2 use sc-azure-myapp:
pool: { vmImage: ubuntu-latest }
steps:
- task: AzureCLI@2
  inputs:
    azureSubscription: sc-azure-myapp
    scriptType: bash
    scriptLocation: inlineScript
    inlineScript: az group list -o table
Required template   Failed
The pipeline does not extend the required template
myapp-lab/pipeline-templates@refs/tags/v1.0.0:templates/secure-pipeline.yml

Checks run before the stage starts; if they fail, the stage does not run, and credentials are never sent to the agent. When the lab is finished, delete this temporary pipeline: az pipelines delete --id <id> --yes.

The correct way to upgrade the template version: template repo change → tag v1.1.0 → first change the Ref of the Required template check to allow the new tag (you can keep both check entries at once, so both versions are accepted during the transition) → then batch-update consumers' ref. Reversing the order would cause every consumer's production deployment to be blocked by the checks.

Case 1: a single template repo push causes 40 pipelines to fail at once

Problem: The platform team renamed build.yml 's parameter dotnetVersion to sdkVersion and pushed to main, and the next runs for all 40 services fail with “Unexpected parameter 'dotnetVersion'”. Root cause: Consumers did not specify a ref ref, so by default they followed refs/heads/main. Fix: Pin all consumers to refs/tags/vX.Y.Z; enable branch policies and PR builds on the template repo (use one “template self-test pipeline” that extends each template once); breaking changes get a major version bump and keep the old parameter for one version cycle. Limitation: Tags can be moved or deleted; for immutability, use a 40-character SHA and restrict force-push permissions on tags in the template repo.

Case 2: use extends to force production deployments through a standard process

Problem: An audit found that some teams call az webapp deploy directly in YAML to deploy to production, skipping scanning and change records. Fix: Add Required template checks to both the production service connection and the production environment; the template fixes the scan, SBOM, and change-ticket steps; consumers only supply build steps. Configuration: Checks are added on protected resources, not in the YAML, so people who edit the pipeline cannot remove them. Limitation: Required template only verifies that the pipeline “extends the template at the specified repo/ref/path”; if the template itself allows arbitrary bash, content filtering in the template is still needed; for organization-level governance at scale, see Lesson 6.

Case 3: a large monorepo hits the 20 MB parse memory limit

Problem: A monorepo uses each to generate stages for 120 services × 4 environments and inserts 6 templates into each stage; the run reports that template limits are exceeded. Fix: Split into one pipeline per service (path triggers), each expanding only itself; move the environment matrix from compile time each to a few stages plus runtime strategy.matrix. Limitation: Official limits are at most 100 files, 100 levels of nesting, and 20 MB of parse memory; they cannot be increased on request.

Common errors and fixes

/azure-pipelines.yml: File /templates/steps/build.yml not found in repository https://dev.azure.com/org/myapp-lab/_git/pipeline-templates branch refs/tags/v1.0.0

Cause: Wrong relative/absolute path; the file does not exist at the specified ref (the new file has not yet been included in a tag); the repository alias points to the wrong project.

git -C pipeline-templates ls-tree -r --name-only v1.0.0 | grep build.yml
git -C pipeline-templates show v1.0.0 --stat

Fix: Using @templates to reference, paths are relative to the template repo root; new files must be included in a new tag, and the consumer's ref ref must be updated.

The 'pythonVersion' parameter value '3.10' is not a valid value.

Cause: The parameter declares values:, and the passed value is not in the list. Similar errors: Expected a boolean value,Expected a sequence (passing a mapping to a stepList).

Fix: Pass values as documented in the template; a stepList must be a sequence beginning with - .

Unexpected parameter 'dotnetVersion'

Cause: A parameter that the template does not declare was passed; usually the template was upgraded and renamed it, or the consumer misspelled it.

Fix: Compare with the parameters: in the template's current ref; pin the ref to avoid “passive upgrades.”

An error occurred while loading the YAML build pipeline. The repository pipeline-templates in project … could not be retrieved. Verify the name and credentials being used.

Cause: When referencing across projects, the current project's build identity lacks read permission on the target repo; or the project setting “Limit job authorization scope to current project” is enabled; or cross-organization access is not configured for the endpoint service connection.

az repos show --repository pipeline-templates --project <templates-project> --query "{id:id,project:project.name}"

Fix: In the template repo's Security settings, grant <project> Build Service (<org>) Grant Read; or disable the corresponding job authorization scope limit (this reduces isolation, so review it); for cross-organization use, use an Azure Repos/TFS-type service connection and write endpoint:. On the first run, click Permit on the “needs permission” prompt.

Maximum number of included files (100) exceeded / Template nesting depth exceeded / exceeded the maximum memory

Cause: Exceeds the 100 files / 100 levels / 20 MB limits; commonly caused by recursive templates or each generating an overly large structure.

Fix: Split the pipeline, reduce the number of templates inserted per stage, and convert some compile-time loops to a runtime matrix.

A template expression is not allowed in this context

Cause:${{ if }}/${{ each }} Can only appear at a mapping key or sequence item position, not in the middle of a string value; or it is used in trigger and similar positions that do not support expressions.

Fix: Adjust the indentation and promote the condition to a key; compare against Download full YAML.

Command-line exercise
1. Write the resources.repositories snippet that pins the template repo to a specific commit.
resources:
  repositories:
  - repository: templates
    type: git
    name: myapp-lab/pipeline-templates
    ref: 9f3c2a1b7d4e5f60718293a4b5c6d7e8f9012345   # 40-character SHA
2. Write a steps template snippet that iterates over the object parameter regions, printing one echo line per region.
parameters:
- name: regions
  type: object
  default: [canadacentral, canadaeast]
steps:
- ${{ each r in parameters.regions }}:
  - bash: echo "deploy to ${{ r }}"
Scenario analysis
The security team requires that “any run using a production service connection must go through a standard scan.” Someone proposes including a scanning template in each service's YAML and calling it done. What is your assessment?

An include cannot enforce anything: the author can delete that line or add arbitrary steps afterward. The correct approach is to write an extends template that fixes the scan steps, and configure Required template checks (specifying repo, ref, and path) on the production service connection and production environment. Checks run server-side before the stage starts, and YAML cannot override them. The template must also filter consumer steps (for example, reject script), pin the template ref, and protect the template repo with branch policies.

Verified teaching videos

▶
Templates in Azure Pipelines: What, Why, and How — CoderDave
English · Explains the motivation for step/job/stage templates and extends (recorded before this lesson's verification date; use this lesson for limit values)
▶
Templates in Azure DevOps Yaml Pipelines — Houssem Dellai
English · Demonstrates template parameters and cross-repo references

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video or MP3 files; the storyboard below can be given to a video tool to produce them.

Shot 1 · 0–20s
Visual: two repo icons; myapp's YAML contains only extends and parameters, with an arrow pointing to the v1.2.0 tag in the template repo.
Narration: the pipeline only states “which template and which version I inherit”; the real structure lives in the template repo.
Shot 2 · 20–45s
Visual: template files merge like puzzle pieces; each duplicates the dev and prod stages, and if removes dev's approval job.
Narration: all of this happens at compile time, and the run page lets you download the fully expanded YAML.
Shot 3 · 45–70s
Visual: the final plan reaches the “production service connection” gate; Required template lights green, and approval lights yellow, waiting.
Narration: before the stage starts, the server checks each protected resource one by one; YAML cannot skip them.
Shot 4 · 70–90s
Visual: another pipeline that does not extend hits a red light, and its stage grays out.
Narration: without going through the approved template, you cannot get production credentials.
or score ≥ 70% on the quiz

Module 2 · Multi-stage pipelines and environment promotion

08:00 – 15:00 · One YAML describes Build → Dev → Prod: the dependency graph sets the order, conditions decide whether a stage runs, and checks decide whether it can start
7 minManualValidation@1agentless job · up to 30 days★★★★★
Learning objectives
  • Use dependsOn to build a stage dependency graph (fan-out/fan-in), knowing that by default each stage depends on the previous stage, and dependsOn: [] lets stages run in parallel immediately.
  • Distinguish three kinds of “gates”: condition (controlled by the YAML author),checks and approvals (controlled by the resource owner, configured on the environment),ManualValidation@1 (pausing within the pipeline; requires an agentless job).
  • Correctly write output variables across jobs and stages: dependencies.<stage>.outputs['job.step.var'] (stage condition) and stageDependencies.<stage>.<job>.outputs['step.var'] (job variables/conditions).
  • Use lockBehavior + exclusive lock checks to prevent two runs from deploying to prod at the same time.
Prerequisites: Lesson 2 YAML structure, Lesson 3 Environments approvals. Importance:★★★★★

What: multi-stage pipelines

Define multiple stage, each stage contains jobs (regular jobs, deployment jobs, or agentless jobs). A stage is the unit of checks and approvals: Before a stage starts, all checks on the protected resources used by all jobs in that stage must pass.

Why: replaces “build pipeline + classic release”

  • Build, deployment, and promotion logic is versioned with code and goes through PR review;
  • Environments record the commits, work items, and runs of each deployment, forming a traceable deployment history;
  • approvals and checks are attached to resources and cannot be changed in YAML, which is safer than the classic release's “pre-stage approvals.”

How: when a stage starts

  1. Dependencies satisfied: dependsOn the stages in it have all finished. If it is not written, dependsOn the stage depends on the previous stage in the YAML.
  2. Condition is true: the default is condition: succeeded()—all dependencies succeeded or partially succeeded. It can be changed to and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main')) which deploys prod only on main.
  3. Checks pass: checks are evaluated only after the condition is true (official FAQ: checks start after the stage condition is met). Order: static checks → pre-approval → dynamic checks → post-approval → exclusive lock. If an approval times out, the stage is skipped.
  4. Jobs queued: jobs within a stage are controlled by job-level dependsOn settings and run in parallel by default.

Comparison of the three gates

conditionApproval check on the environmentManualValidation@1
Who defines itYAML authorResource administrator (portal)YAML author
Can it be bypassed by editing YAML?YesNoYes
Pause locationNo pause, skip directlyBefore the stage startsAgentless job inside the stage
Who can approve—Specified approvers (can prevent approving your own runs)approvers Specified; if none, those with Queue builds permission
Timeout—Configured on the check; the stage is skipped on timeoutTask timeoutInMinutes or 30 days, whichever is earlier,onTimeout: reject|resume
Use caseBranch/parameter filteringProduction compliance approvalManual check of configuration before deployment, confirmation after migration scripts run

Output variable syntax (most error-prone)

Reference locationSyntax
Another job in the same stage$[ dependencies.JobA.outputs['stepName.var'] ]
The next stage's job variables / job conditions$[ stageDependencies.StageA.JobA.outputs['stepName.var'] ]
The next stage's stage conditionseq(dependencies.StageA.outputs['JobA.stepName.var'], 'true')
From a runOnce deployment job (no resource)job name repeated once: stageDependencies.StageA.DeployJob.outputs['DeployJob.stepName.var']
From a deployment job with a resource…outputs['Deploy_<resource>.stepName.var']

Set by: echo "##vso[task.setvariable variable=imageTag;isOutput=true]$TAG", and that step must have a name: (not displayName). Output variables can only be referenced in a place that depends on the job/stage.

When: when to split into multiple pipelines

A multi-stage pipeline suits “one artifact, one promotion path.” When build and deployment cadences differ (dozens of builds a day, one release a week), or when artifacts from multiple repos are deployed together, use a pipeline resource (resources.pipelines + completion trigger, Lesson 2) to separate the “build pipeline” from the “release pipeline.” Another reason: coverage results for a multi-stage pipeline are only visible after the entire run finishes (Module 7).

Common misconceptions① “ManualValidation can replace environment approval.” No: it is written in YAML, so deleting one line removes it; compliance approval must use resource checks. ② “Use stageDependencies in a stage condition.” No: stage conditions use dependencies.<stage>.outputs['job.step.var']; only job-level conditions use stageDependencies. ③ “Setting prod's condition to succeeded() means it deploys only from main.” No: PR builds also reach prod, so you must add a branch check (and add a Branch control check on the environment as a fallback).

Dependency graph: Build → Dev → (Smoke ∥ Security) → Prod

BuildOutput imageTag Deploy_devenv: myapp-dev Smokecurl /healthz SecuritydependsOn: Build ConfirmManualValidation Deploy_prodApproval + required template dependsOn: [Smoke, Security] condition: main branch Security and Deploy_dev run in parallel (fan-out); Confirm waits for both to finish (fan-in)
Figure 2-1: stage dependency graph: fan-out, fan-in, and the “gates” at each node

Sequence diagram: how output variables pass across stages

Stage Build / Job Build step name: setTag ##vso[task.setvariable variable=imageTag; isOutput=true]20261115.4 Written to the run's output dictionary Build.setTag.imageTag stage condition (Deploy_prod) dependencies.Build.outputs ['Build.setTag.imageTag'] key = job.step.var job variable (Deploy_prod) $[ stageDependencies.Build .Build.outputs['setTag.imageTag'] ] key = step.var (job is in the path)
Figure 2-2: the same output variable, written two ways in a stage condition and in a job variable

Interactive simulator: stage dependency graph and condition evaluation

Set the trigger branch, whether Security fails, and the ManualValidation outcome, then run. The simulator evaluates each stage using the real rules: dependencies finished? → condition → checks/approvals → run.

After selecting parameters, click “Run.”

Core syntax

SyntaxPurposeNotes
dependsOn: [A, B] / dependsOn: []Declare dependencies / cancel implicit dependenciesAvailable for both stages and jobs
condition:Run conditionA custom condition replaces the default succeeded(), so you usually need to write and(succeeded(), …)
pool: serveragentless jobManualValidation, InvokeRESTAPI, Delay, and other server tasks
lockBehavior: sequential | runLatestWorks with exclusive lock checksDefault runLatest: only the latest run gets the lock; older runs are canceled
az pipelines runs show --id NView run statusCombined with --open View the stage graph in the browser
az pipelines run --branch main --parameters …Manual triggerCan specify a branch to validate the prod condition

Full skeleton: Build → Dev → Confirm → Prod

trigger: [ main ]
pr: [ main ]

variables:
  acr: acrmyapp21877.azurecr.io

stages:
- stage: Build
  jobs:
  - job: Build
    pool: { vmImage: ubuntu-latest }
    steps:
    - bash: |
        TAG="$(Build.BuildNumber)"
        echo "##vso[task.setvariable variable=imageTag;isOutput=true]$TAG"
      name: setTag                          # must use name; output variables are addressed by it
    - task: AzureCLI@2
      inputs:
        azureSubscription: sc-azure-myapp
        scriptType: bash
        scriptLocation: inlineScript
        inlineScript: az acr build -r ${ACR%%.*} -t myapp:$(setTag.imageTag) .
      env: { ACR: $(acr) }

- stage: Deploy_dev
  dependsOn: Build
  variables:
    imageTag: $[ stageDependencies.Build.Build.outputs['setTag.imageTag'] ]
  jobs:
  - deployment: Deploy
    environment: myapp-dev
    pool: { vmImage: ubuntu-latest }
    strategy:
      runOnce:
        deploy:
          steps:
          - download: none
          - task: AzureCLI@2
            inputs:
              azureSubscription: sc-azure-myapp
              scriptType: bash
              scriptLocation: inlineScript
              inlineScript: az containerapp update -n myapp-dev -g rg-ado-lab --image $(acr)/myapp:$(imageTag)

- stage: Deploy_prod
  dependsOn: [ Build, Deploy_dev ]
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'), ne(variables['Build.Reason'], 'PullRequest'))
  lockBehavior: sequential
  variables:
    imageTag: $[ stageDependencies.Build.Build.outputs['setTag.imageTag'] ]
  jobs:
  - job: Confirm
    pool: server
    timeoutInMinutes: 1440
    steps:
    - task: ManualValidation@1
      timeoutInMinutes: 720
      inputs:
        notifyUsers: ''
        approvers: '[myapp-lab]\Release Managers'
        instructions: 'Check dev smoke results and change ticket, then resume'
        onTimeout: reject
  - deployment: Deploy
    dependsOn: Confirm
    environment: myapp-prod
    pool: { vmImage: ubuntu-latest }
    strategy:
      runOnce:
        deploy:
          steps:
          - download: none
          - task: AzureCLI@2
            inputs:
              azureSubscription: sc-azure-myapp
              scriptType: bash
              scriptLocation: inlineScript
              inlineScript: az containerapp update -n ca-myapp-prod -g rg-ado-lab --image $(acr)/myapp:$(imageTag)

Note: job-level timeoutInMinutes (default 1 hour) must be greater than the ManualValidation task's timeout, otherwise the job times out first. How to verify: In the run page's stage graph, the PR build should show Deploy_prod as “Skipped,” and the main build should stop at Confirm, waiting. In Deploy_prod, stageDependencies.Build Prerequisite for using it: Build must appear in Deploy_prod's dependsOn dependsOn list (a direct dependency), so here it is written as [ Build, Deploy_dev ].

Lab 2: dev → prod promotion (about 7 min)

Commit the skeleton above to myapp (the Module 1 extends version can be merged in the capstone lab; here, observe the behavior directly with the multi-stage YAML first). If you already added a Required template check to sc-azure-myapp in Module 1, this pipeline will be blocked. First click the disable option on the check Disable, then Enable it again after the lab.
git checkout -b lab/multistage
$EDITOR azure-pipelines.yml
git commit -am "ci: multi-stage dev->prod" && git push -u origin lab/multistage
az pipelines run --name myapp-ci --branch lab/multistage -o table

Run on a feature branch: Build and Deploy_dev succeed, and Deploy_prod shows Skipped (condition not met, so checks are not evaluated).

Merge to main and run again:
az repos pr create --source-branch lab/multistage --target-branch main --title "multi-stage" --auto-complete true
# After the PR completes, main triggers CI; check the pending checks and ManualValidation
az pipelines runs list --branch main --top 1 --query "[0].{id:id,status:status}" -o table
Build ✓  →  Deploy_dev ✓  →  Deploy_prod: Waiting
  1 approval needs your review before this run can continue to Deploy_prod   (myapp-prod · Approval)
  ── After approval ──
  Confirm (agentless)  ManualValidation: Waiting for review — Check dev smoke results and change ticket, then resume
  Deploy: Not started
Approve and release: first, on the stage, Review → Approve (environment approval), then on Confirm Review → Resume. Think about it: why does the environment approval appear before ManualValidation, even though the deployment job comes after Confirm? (Answer: checks operate at the stage level; if any job in the stage uses a protected resource, all checks run before the stage starts; ManualValidation, by contrast, is a job that runs after the stage starts.)
Verify image tag passing:
az containerapp show -n ca-myapp-prod -g rg-ado-lab --query "properties.template.containers[0].image" -o tsv
az containerapp show -n myapp-dev -g rg-ado-lab --query "properties.template.containers[0].image" -o tsv
acrmyapp21877.azurecr.io/myapp:20261115.4
acrmyapp21877.azurecr.io/myapp:20261115.4
Try the exclusive lock: on myapp-prod add a Exclusive lock check, push two commits in a row. Because lockBehavior: sequential, the second run's Deploy_prod shows waiting for the lock; after changing it to runLatest then older waiting runs are canceled.

Case 1: a PR build deploys unmerged code to production

Problem: The prod stage's condition only had succeeded(), so a PR validation run from a forked branch went through dev and then deployed to prod directly (the prod environment had no approvals at the time). Fix: Add branch and reason checks to the prod condition; add a Branch control check to the environment that allows only refs/heads/main, and require branch protection; add Required template to the production service connection. Limitation: The condition is only the “first gate”; resource checks are the real fallback.

Case 2: two commits deploy at the same time, and the older version overwrites the newer one

Problem: Two runs queued at the prod approval; the approver approved the newer run first, then the older run, so the old image went live last. Fix: Add an Exclusive lock check to the environment + lockBehavior: runLatest, older runs are canceled when the newer run acquires the lock. Limitation: runLatest cancels older queued runs; if every commit must be deployed (for example, when database migration order matters), use sequential instead.

Case 3: DBA confirmation needed after migration scripts run

Problem: Database migrations run before deployment; the DBA needs to check lock waits and execution plans before switching traffic. Fix: In the prod stage: migration job → agentless job (ManualValidation,approvers for the DBA group,onTimeout: reject) → deployment job. Limitation: ManualValidation is controlled by YAML and cannot serve as compliance approval evidence; compliance approval stays on the environment.

Common errors and fixes

Job Confirm: Step references task 'ManualValidation' at version '1' which is not valid for the given job target.

Cause: ManualValidation can only run in an agentless job, but you placed it in pool: vmImage an agent job.

Fix: Create a separate pool: server job, and have the deployment job dependsOn depend on it.

The variable $(imageTag) is an empty string in prod (the log shows the literal $(imageTag) or an empty value)

Cause:① The step that sets the variable does not have a name:; ② forgot to isOutput=true; ③ the referenced stage is not in dependsOn ; ④ used dependencies.Build.outputs[...] in a job variable (which is stage-condition syntax); ⑤ it comes from a deployment job but the job name was not repeated.

# Print all dependency outputs in the consumer to quickly check the key names
- bash: echo '$(System.JobName)'; env | sort | grep -i tag

Fix: Check against the “output variable syntax” table. After the producer step, add - bash: echo $(setTag.imageTag) a check to confirm the value is readable within the same job; in the consumer, first verify the path with the simplest job variable mapping, then add it to the condition.

Stage Deploy_prod was skipped (no approvals appeared)

Cause: Checks are not evaluated when the condition is false: the branch does not match, Build.Reason is PullRequest, or a dependent stage failed.

Fix: On the run page, expand the stage to see the evaluation details for “Condition evaluated to False.”

The job running on agent … ran longer than the maximum time of 1 hour

Cause: The default timeout for an agentless job is 1 hour, and ManualValidation waited longer than that.

Fix: On the job, set a larger timeoutInMinutes (e.g., 1440); the task timeout must be shorter than the job timeout.

Approval timed out / Checks timed out; stage shows Skipped

Cause: No one acted on the approval within the timeout configured on the check.

Fix: On the run page, you can use Retry stage (officially supported: retry the stage after an approval timeout); adjust the timeout and the notification recipients.

Command-line exercise
1. Write the condition for stage C: run it only when the step check in job A1 of stage A outputs go=true and A succeeds.
- stage: C
  dependsOn: A
  condition: and(succeeded(), eq(dependencies.A.outputs['A1.check.go'], 'true'))
2. Write an agentless job that waits for manual confirmation for 2 hours and automatically continues on timeout.
- job: Wait
  pool: server
  timeoutInMinutes: 180
  steps:
  - task: ManualValidation@1
    timeoutInMinutes: 120
    inputs:
      notifyUsers: ''
      onTimeout: resume
Scenario analysis
You want the Security stage to run in parallel with Deploy_dev, and to reach prod only if both succeed. However, Security occasionally fails due to scanner service timeouts, and the team wants to still deploy Smoke after dev “with risk” in that case. How would you design this?

Security dependsOn: Build, Deploy_dev dependsOn: Build (fan-out); Smoke depends only on Deploy_dev, so it is not affected by Security; prod dependsOn: [Smoke, Security], the default succeeded() requires both to succeed. The Security scan step can be set continueOnError: true to make the result SucceededWithIssues (succeeded() treats it as passing)—but this weakens the gate; a better approach is to retry on scanner service timeouts (retryCountOnTaskFailure), and keep real vulnerability findings failing.

Verified teaching videos

▶
Build Your First Multi-Stage YAML Pipeline in Azure DevOps — The Journey of DevOps
English · Introductory demo of multi-stage YAML
▶
(Simple?) Real World Azure Pipelines YAML Walkthrough — Julie Ng
English · Walkthrough of multi-stage, template, and condition usage in real projects

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–25s
Visual: five stage nodes, with arrows representing dependsOn; Security and Deploy_dev light up at the same time.
Narration: the dependency graph sets the order; stages with no dependency between them run in parallel.
Shot 2 · 25–50s
Visual: three gates in front of the Deploy_prod node: condition, resource checks, ManualValidation.
Narration: the YAML author writes the condition, the resource owner configures the checks, and manual confirmation pauses inside the stage.
Shot 3 · 50–90s
Visual: an envelope labeled imageTag flies from Build to prod; the path is labeled stageDependencies.Build.Build.outputs.
Narration: an output variable needs a step name, isOutput, and a direct dependency; all three are required.
or score ≥ 70% on the quiz

Module 3 · Deployment strategies: runOnce, rolling, canary

15:00 – 22:00 · A deployment job splits deployment into lifecycle hooks; the strategy decides how many times the hooks run and on which targets
7 minpreDeploy · deploy · routeTraffic · postRouteTraffic · onrolling supports VM resources only★★★★☆
Learning objectives
  • Explain the differences between a deployment job and a regular job: the deployment history is recorded to the environment, there is no automatic checkout, and it runs only within deploy its lifecycle hooks, which automatically inject artifact downloads and use $(Pipeline.Workspace).
  • Draw the hook execution order for the three strategies: runOnce executes each hook once; rolling executes per maxParallel batch on each VM; canary's preDeploy executes once,deploy/routeTraffic/postRouteTraffic per increments iteration, and finally goes to on.success or on.failure.
  • references output variable names under different strategies (deploy_10.step.var,Deploy_<resource>.step.var), and uses Container Apps revision weights to implement a real canary and automatic rollback.
Prerequisites: Lesson 3, Module 5 (deploying to Container Apps), and Module 2 of this lesson. Importance:★★★★☆

What: deployment job

- deployment: Name + environment: + strategy:. It can coexist with regular jobs in the same stage. Benefits: ①deployment history is recorded to the environment (even to specific resources such as a Kubernetes namespace or VM), making it auditable; ②deployment strategies standardize “init → deploy → shift traffic → observe → succeed or roll back.”

  • does not automatically check out source code (when needed, write - checkout: self).
  • deploy Hooks automatically inject download the current run's pipeline artifacts; when not needed, write - download: none.
  • Each hook resolves to an agent job or server job (depending on pool), and by default inherits the deployment job's pool. For example, postRouteTraffic can be set to pool: server Only waits and checks.

Lifecycle hooks

HookPurposemyapp example
preDeployInitialize resources before deploymentCheck that the image exists in ACR; database migration pre-check
deployDeploy the app (the only hook that automatically downloads artifacts)az containerapp update --revision-suffix Create a new revision
routeTrafficDirect traffic to the new versionaz containerapp ingress traffic set --revision-weight
postRouteTrafficObserve health after the traffic switchLoop requests /healthz, query error-rate alerts
on: failure / on: successRoll back, or clean up / notifyfailure: send 100% of traffic back to the old revision; success: deactivate the old revision

How: three strategies

runOncerollingcanary
Execution methodEach hook runs once, then on.success / on.failureGenerates a hook job for each VM in the environment; each batch contains maxParallel (number or percentage) of VMspreDeploy runs once; deploy → routeTraffic → postRouteTraffic run per increments iteration; then on.success / on.failure
Supported targetsAny environment (including an empty environment with no resources)VM resources onlyThe official example uses Kubernetes resources (the KubernetesManifest task uses $(strategy.action),$(strategy.increment) to automatically manage canary replicas); iterations still occur in environments without resources, and traffic switching is implemented by your script
Available variablesstrategy.namestrategy.namestrategy.name,strategy.action (deploy/promote/reject),strategy.increment (available only in deploy/routeTraffic/postRouteTraffic)
Output variable keys<job>.<step>.<var>; with resources, Deploy_<resource>.<step>.<var><hook>_<resource>.<step>.<var><hook>_<increment>.<step>.<var>, e.g., deploy_10.setvarStep.myOutputVar
Known limitations—Retrying a stage redeploys to all VMs, not just the failed targetsincrements is a list of “maximum batch sizes”; the official example [10, 20] describes it as 10% → 20% → promote to 100%

When: choosing a strategy

  • runOnce: PaaS (Container Apps/App Service/Functions) + the platform's own traffic features (revisions, deployment slots), or a simple “all-at-once” deployment. Most common.
  • rolling: the environment has VM resources registered (the Linux/Windows agent is installed on the target machines), and IIS/systemd services need to be updated in batches.
  • canary: Kubernetes resources (native to the KubernetesManifest task); or a platform where you can script the traffic ratio (this course uses Container Apps revision weights).
  • Blue-green: there is no separate strategy keyword; implement it with runOnce plus a deployment slot swap (App Service) or a 100% revision switch.

Comparison with similar techniques

Azure Pipelines deployment jobArgo Rollouts / FlaggerContainer Apps revisions
Control planePipeline (push-based)In-cluster controller (pull-based, GitOps)Platform API
Traffic splittingImplemented by calling tools in hooksNative, combined with Ingress/service meshNative weights (--revision-weight)
Automated analysispostRouteTraffic script / checks (Azure Monitor alerts)AnalysisTemplate (Prometheus, etc.)None (requires external judgment)
Common misconceptions① “The canary strategy switches traffic for me automatically”. This only applies to tasks such as KubernetesManifest that use strategy.* variables to do it; on other platforms you call the API yourself in routeTraffic. ② “on.failure always rolls back”. It only runs the steps you write when a failure occurs; rollback logic must be idempotent and rehearsed. ③ “rolling can be used with Kubernetes”. The official docs currently support only VM resources.

Hook timeline: canary increments: [10, 50]

preDeploy×1 Iteration 1: increment 10deploy → routeTraffic → postRouteTraffic Iteration 2: increment 50deploy → routeTraffic → postRouteTraffic Promote 100%strategy.action=promote on.success on.failure (any hook fails)Traffic 100% back to the stable revision · deactivate the new revision Output variable keys: deploy_10.step.var, routeTraffic_50.step.var …
Figure 3-1 canary: preDeploy runs once, the three hooks iterate per increment, ending in success or failure

myapp's Container Apps canary architecture

Userhttps://myapp.… Container Apps ingressrevisionMode: multipletraffic: stable 90 / new 10 myapp--r20261114-2 (stable)90% myapp--r20261115-4 (new)10% → 50% → 100% deployment jobaz containerapp …
Figure 3-2 The pipeline only calls the Container Apps API to adjust revision weights; traffic splitting is done by the platform

Interactive animation: canary hook execution timeline (failures can be injected)

Choose the stage where a failure is injected, then play. Each step shows the hook running,strategy.increment values, traffic weights, and the output variable key names.

stable 100%

Core syntax and commands

Syntax / commandPurposeDescription
environment: name.resourceSpecific resources deployed to the environmentRecorded in the resource-level deployment history; connection info for Kubernetes resources is inherited automatically
environment: { name, resourceType: VirtualMachine, tags }Target VMs for rollingFilter VMs by tag
workspace: { clean: all }Clean up the deployment workspace on a self-hosted agent—
az containerapp revision set-mode --mode multipleEnable multiple revisionsPrerequisite for canary
az containerapp update --image … --revision-suffix r$(Build.BuildId)Create a new revisionSuffix makes the revision name predictable
az containerapp ingress traffic set --revision-weight A=90 B=10Set traffic weightsAlso available latest=10
az containerapp revision deactivate --revision XDeactivate old revisionsClean up in on.success

runOnce (with resources and output variables)

- deployment: DeployWeb
  environment: myapp-dev
  pool: { vmImage: ubuntu-latest }
  strategy:
    runOnce:
      preDeploy:
        steps:
        - bash: echo "pre-check"
      deploy:
        steps:
        - download: none
        - bash: echo "##vso[task.setvariable variable=revision;isOutput=true]myapp-dev--r$(Build.BuildId)"
          name: setRev
      on:
        failure:
          steps:
          - bash: echo "notify on-call"
- job: Verify
  dependsOn: DeployWeb
  variables:
    rev: $[ dependencies.DeployWeb.outputs['DeployWeb.setRev.revision'] ]   # runOnce: job name repeated
  steps:
  - bash: echo $(rev)

rolling (VM resources)

- deployment: VMDeploy
  environment:
    name: myapp-vms
    resourceType: VirtualMachine
    tags: web
  strategy:
    rolling:
      maxParallel: 2          # or '50%'
      deploy:
        steps:
        - bash: sudo systemctl restart myapp
      postRouteTraffic:
        steps:
        - bash: curl -fsS http://localhost:8000/healthz
      on:
        failure:
          steps:
          - bash: echo "restore previous build"

canary (Kubernetes resources, official pattern)

- deployment: K8sCanary
  environment: shop-prod.shop          # Kubernetes namespace resource
  pool: { vmImage: ubuntu-latest }
  strategy:
    canary:
      increments: [10, 20]
      deploy:
        steps:
        - task: KubernetesManifest@1
          inputs:
            action: $(strategy.action)        # deploy / promote / reject
            strategy: $(strategy.name)        # canary
            percentage: $(strategy.increment)
            manifests: manifests/deployment.yml
      postRouteTraffic:
        pool: server
        steps:
        - task: Delay@1
          inputs: { delayForMinutes: '5' }
      on:
        failure:
          steps:
          - task: KubernetesManifest@1
            inputs: { action: reject, strategy: canary, manifests: manifests/deployment.yml }

Note: KubernetesManifest's canary is based on replica count ratio creating -canary and -baseline workloads, not exact traffic percentages; for precise traffic splitting, combine with SMI/service mesh. This lab uses Container Apps revision weights, so the platform enforces the traffic ratio exactly.

Lab 3: myapp on Container Apps 10% → 50% → 100% canary (about 8 minutes)

Conservative note The official docs do not clearly describe the full behavior of the canary strategy on environments without resources (all examples use Kubernetes resources). The traffic switching in this lab is done entirely by our az script; it depends only on the canary hook iterations and strategy.increment variables. If the increments iteration behavior in your organization differs from this description, go by the hook job names in the run log (such as deploy_10), or fall back to runOnce plus a step-by-step routeTraffic script.
Enable multiple revisions and record the current stable revision:
az containerapp revision set-mode -n ca-myapp-prod -g rg-ado-lab --mode multiple
az containerapp revision list -n ca-myapp-prod -g rg-ado-lab --query "[?properties.active].{name:name,weight:properties.trafficWeight,image:properties.template.containers[0].image}" -o table
Name                  Weight    Image
--------------------  --------  ------------------------------------------
myapp--r20261114-2    100       acrmyapp21877.azurecr.io/myapp:20261114.2
Write the canary stage template in the template repo:
parameters:
- name: app
  type: string
- name: environment
  type: string
- name: imageTag
  type: string
- name: increments
  type: object
  default: [10, 50]
- name: serviceConnection
  type: string
  default: sc-azure-myapp

stages:
- stage: Deploy_${{ replace(parameters.environment, '-', '_') }}
  jobs:
  - deployment: Canary
    environment: ${{ parameters.environment }}
    pool: { vmImage: ubuntu-latest }
    variables:
      rg: rg-ado-lab
      newRev: ${{ parameters.app }}--r$(Build.BuildId)
    strategy:
      canary:
        increments: ${{ parameters.increments }}
        preDeploy:
          steps:
          - task: AzureCLI@2
            name: stable
            inputs:
              azureSubscription: ${{ parameters.serviceConnection }}
              scriptType: bash
              scriptLocation: inlineScript
              inlineScript: |
                STABLE=$(az containerapp revision list -n ${{ parameters.app }} -g $(rg) \
                  --query "sort_by([?properties.trafficWeight>\`0\`], &properties.trafficWeight)[-1].name" -o tsv)
                echo "stable=$STABLE"
                echo "##vso[task.setvariable variable=stableRev]$STABLE"
        deploy:
          steps:
          - download: none
          - task: AzureCLI@2
            inputs:
              azureSubscription: ${{ parameters.serviceConnection }}
              scriptType: bash
              scriptLocation: inlineScript
              inlineScript: |
                if ! az containerapp revision show -n ${{ parameters.app }} -g $(rg) --revision $(newRev) >/dev/null 2>&1; then
                  az containerapp update -n ${{ parameters.app }} -g $(rg) \
                    --image acrmyapp21877.azurecr.io/myapp:${{ parameters.imageTag }} \
                    --revision-suffix r$(Build.BuildId)
                fi
        routeTraffic:
          steps:
          - task: AzureCLI@2
            inputs:
              azureSubscription: ${{ parameters.serviceConnection }}
              scriptType: bash
              scriptLocation: inlineScript
              inlineScript: |
                W=$(strategy.increment)
                STABLE=$(az containerapp revision list -n ${{ parameters.app }} -g $(rg) \
                  --query "[?name!='$(newRev)' && properties.trafficWeight>\`0\`].name | [0]" -o tsv)
                az containerapp ingress traffic set -n ${{ parameters.app }} -g $(rg) \
                  --revision-weight $(newRev)=$W $STABLE=$((100-W))
        postRouteTraffic:
          steps:
          - bash: |
              URL="https://${{ parameters.app }}.$(acaDomain)/healthz"
              FAIL=0
              for i in $(seq 1 30); do
                code=$(curl -s -o /dev/null -w '%{http_code}' -m 3 "$URL")
                [ "$code" = "200" ] || FAIL=$((FAIL+1))
                sleep 2
              done
              echo "failures=$FAIL/30 at $(strategy.increment)%"
              [ $FAIL -le 1 ]
            displayName: Health gate ($(strategy.increment)%)
        on:
          failure:
            steps:
            - task: AzureCLI@2
              inputs:
                azureSubscription: ${{ parameters.serviceConnection }}
                scriptType: bash
                scriptLocation: inlineScript
                inlineScript: |
                  STABLE=$(az containerapp revision list -n ${{ parameters.app }} -g $(rg) \
                    --query "[?name!='$(newRev)' && properties.active].name | [0]" -o tsv)
                  az containerapp ingress traffic set -n ${{ parameters.app }} -g $(rg) --revision-weight $STABLE=100
                  az containerapp revision deactivate -n ${{ parameters.app }} -g $(rg) --revision $(newRev) || true
                  echo "##vso[task.logissue type=error]canary rolled back to $STABLE"
          success:
            steps:
            - task: AzureCLI@2
              inputs:
                azureSubscription: ${{ parameters.serviceConnection }}
                scriptType: bash
                scriptLocation: inlineScript
                inlineScript: |
                  az containerapp ingress traffic set -n ${{ parameters.app }} -g $(rg) --revision-weight $(newRev)=100
                  for r in $(az containerapp revision list -n ${{ parameters.app }} -g $(rg) --query "[?name!='$(newRev)' && properties.active].name" -o tsv); do
                    az containerapp revision deactivate -n ${{ parameters.app }} -g $(rg) --revision $r
                  done

Key points: ①deploy Each increment runs the hook, so “create only if the revision does not exist” guarantees idempotency; ② the stable revision is re-queried in each hook, because different hooks are different jobs and normal variables do not cross jobs; ③$(acaDomain) is the default domain of the Container Apps environment (such as purplesea-1a2b3c4d.canadacentral.azurecontainerapps.io), defined in pipeline variables; ④ JMESPath numeric literals `0` When written inside bash double quotes, backticks must be escaped as \`, otherwise bash treats them as command substitution. Tagging v1.1.0.

Using it in myapp (replace the prod stage with the canary template):
variables:
  acaDomain: purplesea-1a2b3c4d.canadacentral.azurecontainerapps.io
stages:
# … Build / Deploy_dev same as Module 2 …
- template: templates/stages/deploy-aca-canary.yml@templates
  parameters:
    app: myapp
    environment: myapp-prod
    imageTag: $(Build.BuildNumber)
    increments: [10, 50]

imageTag The macro string passed here $(Build.BuildNumber), is expanded at runtime; it matches the Build stage's tag (the build number of the same run).

Run and observe: in another terminal, keep observing traffic:
watch -n 5 'az containerapp ingress traffic show -n ca-myapp-prod -g rg-ado-lab -o table'
RevisionName          Weight
--------------------  --------
myapp--r412           10
myapp--r20261114-2    90
…
myapp--r412           50
myapp--r20261114-2    50
…
myapp--r412           100
Rehearse failure rollback: Submit a change that makes /healthz return 500 (for example, in app.py make the health check read a nonexistent environment variable), then re-run. Expected: the first postRouteTraffic fails → on.failure runs → traffic returns 100% to the old revision and the new revision is deactivated. After the rehearsal, revert the commit.

Case 1: the canary rollback script itself fails

Problem: on.failure uses the pipeline variable $(stableRev) to roll back, but that variable was set as a normal variable in the preDeploy job, so it is empty in the on.failure job,--revision-weight =100 causing an error; traffic is stuck at 50/50. Fix: Hooks are separate jobs, so rollback logic must be self-sufficient (re-query the stable revision) or use output variables; the rollback path must be rehearsed for every iteration. Limitations: A failure in on.failure no longer triggers anything, so alerting is needed as a backstop.

Case 2: rolling deployment retry on VMs causes a full restart

Problem: 2 of 20 VMs failed; after retrying the stage, all 20 VMs were redeployed, causing a second disruption. Root cause: Known official limitation: rolling retry reruns on all VMs. Fix: The deployment script compares versions (skips the restart if the target version is already installed); maxParallel use a percentage to limit the proportion affected at the same time.

Case 3: AKS canary with Azure Monitor integration

Problem: Manually watching canary metrics is inefficient. Fix: Change postRouteTraffic to pool: server + Delay, and configure Query Azure Monitor alerts checks on the environment (query alerts before the next stage starts); reject the canary on failure. Limitation: Checks are only evaluated before the stage starts; analysis between hooks still needs scripts or tasks to finish.

Common errors and fixes

Job is pending... (deployment job does not start for a long time)

Cause: Official FAQ: a job name conflict within the same stage, or the job/stage name uses a reserved keyword (such as deployment). It may also be waiting on checks on the environment or an exclusive lock.

Fix: Make job names unique and avoid keywords; check the stage's Checks panel for pending locks or approvals.

##[error]Path does not exist: /home/vsts/work/1/drop (file not found in deploy hook)

Cause: The deployment job does not check out code; automatically downloaded artifacts are located in $(Pipeline.Workspace)/<artifact>, not $(System.DefaultWorkingDirectory); or artifacts are used in preDeploy (automatic download only happens in the deploy hook).

Fix: Use $(Pipeline.Workspace)/drop; in other hooks, explicitly - download: current.

ERROR: The containerapp 'ca-myapp-prod' is in single revision mode … traffic weight cannot be set

Cause: In single-revision mode, only one revision can be active.

az containerapp show -n ca-myapp-prod -g rg-ado-lab --query properties.configuration.activeRevisionsMode

Fix:az containerapp revision set-mode --mode multiple.

Rolling deployment: No resources found in environment 'myapp-vms' with resource type VirtualMachine

Cause: No VM resources are registered in the environment, or tags filter matches nothing.

Fix: In the environment, go to Add resource → Virtual machines, register the agent on the VMs using the page's script, and add tags.

Subsequent job reads the canary output variable as empty

Cause: canary keys include the hook name and the increment: dependencies.Canary.outputs['deploy_10.setRev.revision'].

Fix: Write it according to the output variable keys table; when unsure, check the hook job name in the run log.

Command-line exercise
1. Write the command that splits Container Apps traffic 20% to the new revision and 80% to the old revision.
az containerapp ingress traffic set -n ca-myapp-prod -g rg-ado-lab --revision-weight myapp--r412=20 myapp--r20261114-2=80
2. canary job Canary In the deploy hook of setRev step output revision, with increments [10]. Write the variable mapping that another job in the same stage uses to reference it.
variables:
  rev: $[ dependencies.Canary.outputs['deploy_10.setRev.revision'] ]
Scenario analysis question
A team changes an App Service deployment from “deploy to the production slot” to a canary strategy, but finds that all traffic switches to the new version instantly. What is the cause, and how should it be changed?

The canary strategy itself does not switch traffic; it only iterates the hooks. If the deploy hook deploys directly to the production slot, everything takes effect on the first iteration. Instead: deploy to the staging slot; in routeTraffic, use az webapp traffic-routing set --distribution staging=$(strategy.increment); postRouteTraffic health check; on.success performs the slot swap and clears routing; on.failure clears routing (traffic returns to the production slot).

Verified instructional videos

▶
Azure Pipelines Deployment Strategies Explained | Blue-Green, Canary | AZ-400 DevOps Engineer — Skilltech Club
English · Deployment strategy concepts (based on this course's hook and limitation notes)
▶
Canary Deployment in Azure DevOps | Azure DevOps Interview Questions | An IT Professional — An IT Professional
English · Canary explained from an interview perspective

Official docs

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: a timeline; after the preDeploy block are three deploy/route/post block groups, labeled below with 10%, 50%, 100%.
Narration: canary initializes once, then repeatedly deploys by increment, shifts traffic, and observes.
Shot 2 · 25–60s
Visual: the traffic bar grows from 0 to 10%, the health-check curve turns red, the traffic bar instantly returns to 0, and the on.failure block lights up.
Narration: if any hook fails, the flow enters on failure and runs the rollback you wrote.
Shot 3 · 60–90s
Visual: three-column comparison: runOnce once, rolling in batches by VM, canary by percentage.
Narration: PaaS mostly uses runOnce, VMs use rolling, and Kubernetes or platforms with controllable traffic use canary.
or score ≥ 70% in the quiz

Module 4 · Azure Artifacts: feeds, upstreams and retention

22:00 – 30:00 · one feed is at once a “private repository + public repository proxy cache + quality tiers (views)”
8 minutes@local · @prerelease · @release2 GiB free / organization★★★★☆
Learning objectives
  • Distinguish organization scope and project scope feeds, and the two build identities that must be granted permissions when pipelines publish.
  • Explain how upstream sources are resolved and the “save” mechanism: packages first installed from an upstream are saved to this feed, so they can still be restored even if the upstream removes them.
  • Express with views quality: can only be published to the base feed (goes into @local), and enters @prerelease/@release via “promote”; views are read-only and cannot be demoted; packages in views are exempt from retention policies.
  • Choose the correct authentication task for npm, NuGet, pip/twine, Maven, and Universal Packages, and publish myapp's Python packages to myapp-feed.
Prerequisites: Lesson 2 pipeline artifacts (the difference between Pipeline Artifacts and Azure Artifacts). Importance:★★★★☆

What: feeds

Azure Artifacts feeds are package repositories that support multiple protocols: NuGet, npm, Maven, Python (pip/twine), Cargo, Universal Packages (arbitrary files,az artifacts universal), and Gradle (uses the Maven protocol). Package versions are immutable: once published they cannot be modified; even if deleted, the version number is permanently reserved and cannot be reused.

Project-scoped feed (recommended default)Organization-scoped feed
VisibilityInherits project visibility and permissionsVisible within the organization, permissions managed separately
URLpkgs.dev.azure.com/<org>/<project>/_packaging/<feed>/…pkgs.dev.azure.com/<org>/_packaging/<feed>/…
Usage in tasksartifactFeed: myapp-lab/myapp-feedartifactFeed: myapp-feed
NotesThe official default when creating a feed is project scopeUse for sharing across projects (you can also let other projects use a project feed as an upstream)

Upstream sources

  • You can configure public sources such as npmjs, NuGet.org, PyPI, and Maven Central, as well as other Azure Artifacts feeds in the same organization or Microsoft Entra tenant, as upstreams.
  • Resolution order: check this feed first, then search upstreams in list order; On the first install of a version from an upstream, Azure Artifacts automatically saves it to this feed (goes into @local). Afterwards, even if the upstream is deleted or unreachable, restores still work. This is key to supply-chain stability.
  • For this feed to be used as an upstream by other feeds, its visibility must be set to “Organization members” or “Microsoft Entra ID members”.
  • Saving requires permission: users need Feed and Upstream Reader (Collaborator) or a higher role to trigger saving new versions from upstreams; with only Feed Reader, they can only read packages that are already saved.

Views

  • Each feed has three views by default: @local (the default view, containing directly published packages and packages saved from upstreams),@prerelease,@release (the latter two are suggested views that can be renamed or deleted).
  • Can only be published to the base feed; use Promote to add versions to other views. Views are read-only, and do not support demotion (once in a view, a package cannot go back to @local only).
  • To reference a view, append @view to the feed name, for example …/_packaging/myapp-feed@release/pypi/simple/. Consumers (downstream teams, or other feeds' upstreams) connect to @release the view to see only validated versions.
  • Semantics: the version number (SemVer) expresses the nature and risk of the change, while views express quality. Quality is known only after validation, so it should not be encoded in the version number.

Retention policy and storage

  • Feed settings → Feed details → Enable package retention: Maximum number of versions per package and Days to keep recently downloaded packages. Only when both conditions are met (the version count reaches the limit, and the version has not been downloaded within the specified number of days) is it deleted.
  • Packages in views are exempt from the retention policy. To keep a version long term, promote it to a view.
  • Deleted packages go to the recycle bin for 30 days, during which they still count toward storage. The cleanup job runs once a day.
  • Each organization gets 2 GiB of free storage. Beyond that, billing must be set up and the limit raised; otherwise, new packages cannot be published.

Quick reference for authentication tasks

EcosystemTaskMechanismPublish command
npmnpmAuthenticate@0Publish to the specified .npmrc Inject tokennpm publish
NuGet / dotnetNuGetAuthenticate@1Configure Azure Artifacts credential providerdotnet nuget push --source <feed-url> --api-key az
pip (install)PipAuthenticate@1Set PIP_EXTRA_INDEX_URL (or PIP_INDEX_URL)pip install
twine (publish)TwineAuthenticate@1Generate .pypirc, with the path in $(PYPIRC_PATH); running it multiple times appends rather than overwritestwine upload -r <feed> --config-file $(PYPIRC_PATH) dist/*
Maven / GradleMavenAuthenticate@0Write settings.xml 's server credentialsmvn deploy
Universal PackagesUniversalPackages@0Use the pipeline identity within the taskcommand: publish / download

Local development: Python uses artifacts-keyring, NuGet uses the Azure Artifacts Credential Provider, and npm uses vsts-npm-auth (Windows) or a PAT. Following the identity governance principles of Lesson 6, prefer Microsoft Entra tokens; set the PAT to minimal scope (Packaging: Read or Read & write) with a short validity period.

Comparison with similar technologies

Azure ArtifactsGitHub PackagesJFrog Artifactory
Public source proxyUpstream sources (auto-save)Limited (partially supported by npm, etc.)Remote repository
Quality tiersViews (promote)No built-in supportCross-feed promote / properties
PythonSupportedNot supportedSupported
Container imagesNot supported (use ACR)ghcr.ioSupported
Common misconceptions① “Pipeline Artifacts and Azure Artifacts are the same thing”. The former are build outputs passed within or between runs (retained with the run); the latter is a protocol-based package repository. ② “You can publish directly to @release”. No, you can only publish to the base feed and then promote. ③ “Deleting a package frees up the version number”. No, the version number is permanently reserved; when a fix is needed, publish a new version. ④ “With a retention policy enabled, old release versions get deleted”. Versions promoted to a view are exempt.

Package resolution and save flow

pip installflask==3.1.* myapp-feed (project scope) @localPublished packages + savedupstream packages @prerelease @release promote (one-way, no demotion) Upstream list (in order)1. platform-feed@release 2. PyPI platform-feed@releaseViews of other feeds in the same organization pypi.orgPublic registry ① ② ③ First install: automatically saved to @local (requires the Feed and Upstream Reader role or higher)
Figure 4-1 Check this feed first, then upstreams in order; a version first found in an upstream is saved to this feed

Lifecycle of myapp packages

CI builds wheel1.4.0.dev412 twine upload→ @local dev validation passespromote @prerelease prod deployment succeedspromote @release Retention policyExempt in views
Figure 4-2 The version number expresses “what changed”; views express “how far validation has gotten”

Interactive simulator: how a pip install resolves in a feed

Select a package, consumer role, and upstream status, then click “Install”. The simulator shows the real rules: hit in this feed → check upstreams in order → whether to save to @local → return or error.

After choosing the parameters, click “Install”.

Core commands and tasks

Command / taskPurposeNotes
TwineAuthenticate@1 + twine upload -r <feed> --config-file $(PYPIRC_PATH)Publish Python package-r The value is the feed name
PipAuthenticate@1 (artifactFeeds: myapp-lab/myapp-feed)Install from feedonlyAddExtraIndex: true as an extra index
pip install keyring artifacts-keyringLocal interactive authenticationOn first use, a browser / device code prompt appears
az artifacts universal publish/downloadUniversal Packages--organization --project --scope project --feed --name --version --path
REST: PATCH …/_apis/packaging/feeds/{feed}/pypi/packages/{pkg}/versions/{ver}Promote to viewbody {"views":{"op":"add","path":"/views/-","value":"Release"}}, host pkgs.dev.azure.com

Publish Python package (official steps + version number)

- task: UsePythonVersion@0
  inputs: { versionSpec: '3.12' }
- bash: |
    pip install build twine
    python -m build                      # generates dist/*.whl and *.tar.gz
  displayName: Build package
- task: TwineAuthenticate@1
  inputs:
    artifactFeed: myapp-lab/myapp-feed   # for an organization-scoped feed, write myapp-feed
- bash: python -m twine upload -r myapp-feed --config-file $(PYPIRC_PATH) dist/*
  displayName: Upload to feed

Install from feed (including upstreams)

- task: PipAuthenticate@1
  inputs:
    artifactFeeds: myapp-lab/myapp-feed
    onlyAddExtraIndex: false             # use the feed as the primary index; public packages are fetched via upstreams and saved
- bash: pip install -r requirements.txt

Promote to view (within the pipeline)

curl -sS -X PATCH \
  -H "Authorization: Bearer $(System.AccessToken)" -H "Content-Type: application/json" \
  "https://pkgs.dev.azure.com/<org>/myapp-lab/_apis/packaging/feeds/myapp-feed/pypi/packages/myapp-core/versions/1.4.0?api-version=7.1" \
  -d '{"views":{"op":"add","path":"/views/-","value":"Release"}}'
(HTTP 202, no response body)

Notes: In REST paths, the Python package name uses the normalized name (lowercase,_ and . converted to -). Using System.AccessToken requires the build identity to have at least Contributor on the feed; the view name does not include @. If your organization's API version differs, follow the REST docs “Python - Update Package Version”.

Other ecosystems (excerpt)

# npm
- task: npmAuthenticate@0
  inputs: { workingFile: .npmrc }
- script: npm publish
# NuGet
- task: NuGetAuthenticate@1
- script: dotnet nuget push "**/*.nupkg" --source "https://pkgs.dev.azure.com/<org>/myapp-lab/_packaging/myapp-feed/nuget/v3/index.json" --api-key az
# Maven
- task: MavenAuthenticate@0
  inputs: { artifactsFeeds: myapp-feed }
- script: mvn -B deploy
# Universal Packages
- task: UniversalPackages@0
  inputs:
    command: publish
    publishDirectory: $(Build.ArtifactStagingDirectory)
    vstsFeedPublish: myapp-lab/myapp-feed
    vstsFeedPackagePublish: myapp-bundle
    versionOption: custom
    versionPublish: $(Build.BuildNumber)

Lab 4: publish myapp's Python package and promote it to @release (about 8 minutes)

Package myapp's shared code: add a new file to the myapp repo pyproject.toml (package name myapp-core, the version is written by the pipeline).
[build-system]
requires = ["setuptools>=69", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "myapp-core"
version = "0.0.0"          # replaced with the computed version via sed in the pipeline
description = "Shared helpers of myapp (health checks, redis client)"
requires-python = ">=3.11"
dependencies = ["redis>=5"]

[tool.setuptools.packages.find]
include = ["app*"]
Configure upstream sources: Feed settings → Upstream sources → Add upstream → Public source → PyPI (new feeds usually include common public upstreams by default; just confirm).
Build and publish in the pipeline (appended to the Build stage; the version number uses the build ID for now, and Module 5 switches it to GitVersion):
- bash: |
    VER="1.4.0.dev$(Build.BuildId)"
    sed -i "s/^version = .*/version = \"$VER\"/" pyproject.toml
    pip install build twine && python -m build
    echo "##vso[task.setvariable variable=pkgVersion;isOutput=true]$VER"
  name: pkg
- task: TwineAuthenticate@1
  inputs: { artifactFeed: myapp-lab/myapp-feed }
- bash: python -m twine upload -r myapp-feed --config-file $(PYPIRC_PATH) dist/*
Uploading distributions to https://pkgs.dev.azure.com/<org>/myapp-lab/_packaging/myapp-feed/pypi/upload/
Uploading myapp_core-1.4.0.dev412-py3-none-any.whl
100% ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 6.1/6.1 kB
Uploading myapp_core-1.4.0.dev412.tar.gz
View at:
https://pkgs.dev.azure.com/<org>/myapp-lab/_packaging/myapp-feed/pypi/simple/myapp-core/
Install from the feed locally:
python -m venv .venv && . .venv/bin/activate
pip install keyring artifacts-keyring
pip install myapp-core==1.4.0.dev412 \
  --index-url https://pkgs.dev.azure.com/<org>/myapp-lab/_packaging/myapp-feed/pypi/simple/
pip install flask   # fetched via upstream PyPI and saved to myapp-feed

In the portal, go to Artifacts → myapp-feed and filter Source = PyPI to see the flask version that was just saved.

Auto-promote after a successful prod deployment: In the canary template's on.success , add the PATCH call from the previous section (the version number is passed via stageDependencies). Then verify the @release view:
pip index versions myapp-core --pre \
  --index-url https://pkgs.dev.azure.com/<org>/myapp-lab/_packaging/myapp-feed@release/pypi/simple/
myapp-core (1.4.0.dev412)
Available versions: 1.4.0.dev412
Enable retention policy: Feed details → Enable package retention: keep at most 20 versions per package; delete only if not downloaded within 30 days. Think about it: 1.4.0.dev412 already in @release, will it be deleted? (No, packages in views are exempt.)

Case 1: a public package is removed by its author, and all builds fail

Problem: An npm dependency was unpublished by its author, and CI cannot recover it. Fix: All projects connect only to the internal feed, with the public registry as an upstream; the first install saves a copy, so it can still be restored after being unpublished. Limitation: Saving happens only for versions that were actually installed; new versions still depend on the upstream being available.

Case 2: dependency confusion

Problem: An internal package name contoso-utils was squatted on public PyPI with a higher version; developer machines were configured with both PyPI and the internal feed, so pip picked the higher public version. Fix: Configure only one index (the internal feed, with PyPI as an upstream); add an organization prefix to internal package names; publish the internal package name to the feed first and rely on Azure Artifacts' “upstream behavior”. When the feed already has a local version of a package name, by default it does not bring in a same-named version from the public upstream (this can be relaxed per package). Limitation: For per-protocol details of upstream behavior, follow the official “Configure upstream behavior” docs; this course has not verified each protocol.

Case 3: storage exceeds 2 GiB, publishing is blocked

Problem: Each CI run publishes a Universal Package (200 MB), so publishing fails a month later. Fix: Enable retention policy (10 versions per package); promote release versions to @release for exemption; permanently delete unneeded versions from the recycle bin to free space immediately; consider switching to Pipeline Artifacts (which expire with the run's retention policy). Limitation: Storage usage statistics are updated at most every 24–48 hours.

Common errors and fixes

HTTPError: 401 Unauthorized from https://pkgs.dev.azure.com/…/pypi/upload/

Cause: TwineAuthenticate was not run; twine was not using --config-file $(PYPIRC_PATH); -r 's name does not match the feed name; the local PAT has expired or lacks the Packaging scope.

cat "$PYPIRC_PATH" | sed 's/password.*/password = ***/'

Fix: Complete the official steps; locally, switch to artifacts-keyring.

HTTPError: 403 Forbidden — User '…Build Service (org)' lacks permission to complete this action. You need to have 'AddPackage'.

Cause: The build identity is not the feed's Feed Publisher (Contributor). The official requirement is to add Project Collection Build Service and the project Build Service both as Contributors.

Fix: Add them under Feed settings → Permissions; if “Limit job authorization scope to current project” is enabled, cross-project feeds also need to grant the target project's identity access.

HTTPError: 409 Conflict — The feed already contains file 'myapp_core-1.4.0-py3-none-any.whl'

Cause: Package versions are immutable; republishing the same version (including a deleted version number) causes a conflict.

Fix: Generate a unique version for each build (Module 5); when re-running a pipeline, skip versions that are already published (twine upload --skip-existing).

ERROR: No matching distribution found for flask==3.1.1 (not in the feed, and not fetched from upstream)

Cause: The feed has no PyPI upstream configured; the consumer has only the Feed Reader role and cannot trigger saving; and it is connected to the @release view, which contains only promoted packages and does not go through upstreams.

Fix: Add the upstream; give the consumer the Feed and Upstream Reader role; when installing public packages, connect to the base feed rather than a view.

Storage limit reached / You have exceeded your free storage limit

Cause: The organization exceeded its 2 GiB free quota.

Fix: Enable retention policy, empty the recycle bin, and set up billing and raise the limit (Organization settings → Billing).

Command-line exercise
1. Write the pip command that uses only myapp-feed@release as the source to install myapp-core .
pip install myapp-core --index-url https://pkgs.dev.azure.com/<org>/myapp-lab/_packaging/myapp-feed@release/pypi/simple/
2. Use Universal Packages to download myapp-bundle 's version 1.4.0 to ./out.
az artifacts universal download --organization https://dev.azure.com/<org> --project myapp-lab --scope project \
  --feed myapp-feed --name myapp-bundle --version 1.4.0 --path ./out
Scenario analysis question
The platform team maintains a platform-feed, wanting 30 product teams to get only “platform-tested” shared packages, while each team can still use PyPI normally. How would you design this?

Each team has its own project feed, with upstreams configured in order: platform-feed@release (exposing only versions promoted to Release) and PyPI; the platform feed's visibility is set to organization members; the platform CI publishes to platform-feed, and after tests pass, the package is promoted to @release. Teams configure only their own feed as the single index, avoiding dependency confusion; retention policy is enabled on the platform feed, and release versions are exempt because they are in a view.

Verified instructional videos

▶
How to create, host, and share packages with Azure Artifacts | Azure Tips and Tricks — Microsoft Azure
English · Official short video: creating feeds and sharing packages
▶
Getting started with package management using Azure Artifacts — Microsoft Visual Studio
English · Official introductory walkthrough (recorded earlier; the UI may differ)

Official docs

Video storyboard (about 90 seconds)

Shot 1 · 0–30s
Visual: a pip request goes to myapp-feed first; on a miss, it goes to platform-feed and then PyPI in turn, and the package is copied back to @local.
Narration: upstream sources make the internal feed a cache of the public registry; the first install saves the package automatically.
Shot 2 · 30–60s
Visual: a version number gets a prerelease tag, then a release tag, applied in turn from @local.
Narration: the version number explains the change, the view explains the quality; promotion is one-way only.
Shot 3 · 60–90s
Visual: the retention policy scans; gray old versions move to the recycle bin; versions with a release tag are unaffected.
Narration: packages in views are never deleted by the retention policy; the recycle bin keeps them for thirty days.
or score ≥ 70% in the quiz

Module 5 · Version numbers, tags and release notes

30:00 – 36:00 · One run = one unique, traceable version: build number, package version, image tag, Git tag and release notes stay consistent
6 minutescounter()GitVersion 6.8 · GitTools task 4.7.0★★★★☆
Learning objectives
  • Use the top-level name: to define the build number format ($(Date:yyyyMMdd)$(Rev:.r) and other tokens), and override it at runtime with ##vso[build.updatebuildnumber] .
  • Use counter(prefix, seed) to generate a patch number that resets automatically when the major or minor version changes; know that it can only be used in variable definitions, counted per pipeline.
  • Use GitVersion (GitTools task gitversion-setup / gitversion-execute) to compute SemVer from Git history, and know that it requires a full clone (fetchDepth: 0).
  • After a successful prod deployment, automatically create the Git tag and generate release notes (based on merged PRs and linked work items).
Prerequisites: Lesson 2 variables and expressions; the tags from the Git course. Importance:★★★★☆

What: four kinds of “versions” need to be aligned

CarrierExampleDetermined by
Run build number Build.BuildNumber1.4.7 or 20261115.4YAML top level name: (default $(Date:yyyyMMdd)$(Rev:.r))
Package versionmyapp-core 1.4.7, prerelease 1.5.0.dev3Pipeline writes to pyproject / csproj / package.json
Image tagmyapp:1.4.7az acr build -t
Git tagv1.4.7Pushed by the pipeline after prod succeeds

How: build number format

  • Top level name: Supported tokens: $(Date:yyyyMMdd),$(Rev:r) (increments from 1 under the same build number prefix),$(Build.DefinitionName),$(SourceBranchName),$(Hours),$(Minutes) and custom variables (such as $(major).$(minor).$(patch)).
  • $(Rev:r) Can only be used in name:; if other parts of the build number change (such as the date),Rev restart from 1.
  • Overriding at runtime: echo "##vso[build.updatebuildnumber]1.4.7" (GitVersion's buildNumberFormat input does exactly this).

How: counter expression (official semantics)

  • $[counter(prefix, seed)]: increments by 1 each run; counts separately for each distinct prefix ; the first value is the seed.
  • Can only be used in expressions that define variables, not in the condition of a stage, job or step.
  • Counters are scoped per pipeline, with no project-level counters.
  • If the prefix is changed back to an old value, the count continues from where it last stopped (official example: major changed from 2 back to 1, minor continues from 102).
  • Common usage: patch: $[counter(format('{0}.{1}', variables['major'], variables['minor']), 0)]; daily reset: $[counter(format('{0:yyyyMMdd}', pipeline.startTime), 100)] (pipeline.startTime default is UTC, can be set to the organization's time zone).

How: GitVersion

  • GitVersion computes from branches, tags and commit messages (such as +semver: minor) and GitVersion.yml configuration, computing SemVer,FullSemVer,MajorMinorPatch, and PreReleaseTag , etc.
  • Using the Marketplace extension in Azure Pipelines GitTools two tasks: gitversion-setup@4 (install,versionSpec: '6.8.x') and gitversion-execute@4 (compute). Verified 2026-11: latest GitTools/actions v4.7.0 (2026-07-03), latest GitVersion 6.8.2 (2026-07-10). In older articles, the gitversion/setup@0 and @3 syntax belongs to older task versions.
  • Must do a full clone: checkout: self + fetchDepth: 0 (Lesson 2: pipelines created after 2022-09 may default to a shallow clone of depth 1), otherwise the execute task fails with a shallow clone error.
  • Output: within the same job, use $(GitVersion_SemVer), and across jobs use $(<stepName>.semVer) or …GitVersion_SemVer. GitVersion 6 removed NuGetVersionV2,LegacySemVer and other legacy variables.

Release notes automation

Approach: take the merge commits from the previous v* tag up to the current commit (Azure Repos PR merge commit messages read “Merged PR 123: title”), then use REST to read the work items linked to each PR, generate Markdown, and publish it as a pipeline artifact or write it to the Wiki (Lesson 1). The Marketplace also has ready-made extensions (such as “Generate Release Notes”); before using one, assess its maintenance status and permissions.

When: choose a versioning scheme

SchemeProsConsSuitable for
Date + RevZero configurationNo semanticsInternal apps, images
Hand-written major.minor + counterSimple, no external dependenciesChanging major/minor requires editing YAMLSmall team libraries
GitVersionDetermined by Git history; branches automatically get prerelease tagsRequires a full clone; configuration learning curveExternally published libraries, GitFlow / trunk-based mode
Common misconceptions① “A counter is globally unique”. It counts per pipeline; two pipelines using the same prefix do not affect each other; recreating the pipeline definition restarts from the seed. ② “The build number is the version number”. The build number is only the display name of a run; it can repeat across different pipelines, or within the same pipeline (with a custom format that does not include $(Rev:r) ), so the uniqueness of package versions must be guaranteed by you. ③ “Creating Git tags in PR builds”. Tags should only be created on main after prod succeeds; otherwise the tag points to a commit that was never released.

How the version flows through one run

Git historyv1.4.6 + 1 commit gitversion-executeSemVer = 1.4.7 Build number → 1.4.7 pyproject version = 1.4.7 myapp:1.4.7 (ACR) After prod succeedsgit tag v1.4.7 & pushrelease-notes-1.4.7.md The same value runs through the build number, package, image and tag: any of them can be traced back to the commit and the run
Figure 5-1 The version number is computed once from Git history and propagated to four carriers

counter count table

prefix = "1.4"Run 1 → 0 Run 2 → 1 Run 3 → 2 prefix = "1.5"(after changing minor) Run 4 → 0 Run 5 → 1 prefix = "1.4"(changed back to 1.4) Run 6 → 3 ← continues from where it last stopped, not from the seed
Figure 5-2 counter counts separately for each prefix

Interactive calculator: counter and build number

Change major/minor, then click “Simulate a run”. The calculator maintains the count for each prefix using the official semantics and displays name: the generated build number.

Core syntax

SyntaxPurposeNotes
name: $(major).$(minor).$(patch)Build number formatReference variable; $(Rev:r) can only be used in name
$[counter(prefix, seed)]auto-increment counterCan only be used in variable definitions
##vso[build.updatebuildnumber]XChange the build number at runtime—
##vso[build.addbuildtag]v1.4.7Tag run (not a Git tag)Makes it easy to filter runs
git tag -a v1.4.7 -m … && git push origin v1.4.7Push Git tagRequires persistCredentials: true and the build identity's Contribute / Create tag permissions
az repos pr list --status completedQuery completed PRsRelease notes data source

counter approach

variables:
  major: 1
  minor: 4
  patch: $[counter(format('{0}.{1}', variables['major'], variables['minor']), 0)]
  ${{ if eq(variables['Build.SourceBranchName'], 'main') }}:
    versionSuffix: ''
  ${{ else }}:
    versionSuffix: '-ci'

name: $(major).$(minor).$(patch)$(versionSuffix)

Note: name: variables are evaluated when the run starts, and the counter value is fixed at that point; conditional variables choose the suffix by branch at compile time.

GitVersion approach (GitTools 4.7.0)

steps:
- checkout: self
  fetchDepth: 0                     # GitVersion needs full history and tags
  fetchTags: true
- task: gitversion-setup@4
  displayName: Install GitVersion
  inputs:
    versionSpec: '6.8.x'
- task: gitversion-execute@4
  name: version                     # cross-job reference: $(version.semVer)
  displayName: Determine version
  inputs:
    buildNumberFormat: '${GitVersion_SemVer}'   # runtime build number becomes SemVer (GitTools docs example: v${GitVersion_MajorMinorPatch})
- bash: echo "SemVer=$(GitVersion_SemVer) FullSemVer=$(GitVersion_FullSemVer) Branch=$(GitVersion_BranchName)"
workflow: GitHubFlow/v1          # one of GitVersion 6's built-in workflow presets
branches:
  main:
    label: ''
  feature:
    label: '{BranchName}'
SemVer=1.4.7 FullSemVer=1.4.7 Branch=main
# On branch feature/login: SemVer=1.5.0-login.1

Conservative note:buildNumberFormat 's variable syntax follows the GitTools docs (the docs example is v${GitVersion_MajorMinorPatch}); GitVersion 6's workflow preset names should be checked against the current gitversion.net docs.

Tag and generate release notes after prod succeeds

- checkout: self
  fetchDepth: 0
  persistCredentials: true
- bash: |
    set -euo pipefail
    VER="$(semVer)"
    PREV=$(git describe --tags --abbrev=0 --match 'v*' 2>/dev/null || git rev-list --max-parents=0 HEAD)
    {
      echo "# myapp v$VER ($(date -u +%F))"
      echo
      echo "## Changes"
      git log "$PREV"..HEAD --merges --pretty='- %s' | sed 's/^- Merged PR /- PR !/'
    } > "$(Build.ArtifactStagingDirectory)/release-notes-$VER.md"
    git -c user.name="Azure Pipelines" -c user.email="pipelines@noreply" tag -a "v$VER" -m "release v$VER"
    git push origin "v$VER"
  displayName: Tag & release notes
- publish: $(Build.ArtifactStagingDirectory)
  artifact: release-notes

Lab 5: automatic versioning + tagging (about 6 minutes)

Install the GitTools extension: Organization settings → Extensions → Browse marketplace → search GitTools (publisher GitTools) → Get it free. If you do not have permission to install extensions, complete the lab with the counter approach above instead.
Grant the build identity tag permission: Project settings → Repositories → myapp → Security → myapp-lab Build Service (<org>): Contribute and Create tag set to Allow.
Build stage computes the version and outputs it: add the GitVersion step above to the Build job, and change the package version and image tag to $(GitVersion_SemVer); output variables for later stages to use:
- bash: echo "##vso[task.setvariable variable=semVer;isOutput=true]$(GitVersion_SemVer)"
  name: ver
Tag after the prod stage succeeds: In the canary template's on.success (or a separate job after prod), add the tagging and release-notes steps,semVer via stageDependencies.Build.Build.outputs['ver.semVer'] mapping.
Verify:
git fetch --tags && git tag -l 'v*' --sort=-v:refname | head -3
az pipelines runs list --pipeline-ids <id> --top 3 --query "[].buildNumber" -o tsv
v1.4.7
v1.4.6
v1.4.5
1.4.7
1.4.6
1.4.5

Case 1: a shallow clone makes the version drop back to 0.1.0

Problem: A newly created pipeline defaults to a shallow clone of depth 1; GitVersion cannot see the historical tags and calculates 0.1.0, which conflicts with an existing version in the feed on publish (409). Fix:fetchDepth: 0 + fetchTags: true; the GitTools task detects a shallow clone by default and fails (disableShallowCloneCheck — do not turn it on).

Case 2: rerunning a failed run generated a duplicate package version

Problem: Using $(Build.BuildId) as the patch number, rerunning a failed stage (same run) keeps BuildId unchanged, and Upload reports 409. Fix: Check whether the version exists before uploading, or use --skip-existing; package versions map one-to-one to runs, and a rerun only completes the unfinished steps.

Case 3: release notes are missing changes

Problem: The team uses squash merge, and the merge commit message is written by the author,--merges so the step cannot capture it. Fix: Switch to REST to query completed PRs and filter by closedDate , or unify the merge commit message format in the branch policy; work items are linked through PRs (Lesson 1, Boards and Repos integration).

Common errors and fixes

GitVersion: The repository is a shallow clone. Git repositories must contain the full history.

Cause: Shallow clone.

Fix:checkout: self Add fetchDepth: 0; the “Shallow fetch” setting in the UI is overridden by the YAML fetchDepth.

A task is missing. The pipeline references a task called 'gitversion-setup'.

Cause: The organization has not installed the GitTools extension, or the task major version is written incorrectly.

Fix: Install the extension; use gitversion-setup@4 / gitversion-execute@4 according to the extension's current docs.

Unrecognized value: 'counter'. / counter errors in a condition

Cause: counter can only be used in a runtime expression in a variable definition $[ ] .

Fix: Define the variable first, then reference the variable in the condition.

remote: TF401027: You need the Git 'GenericContribute' permission to perform this action. (tag push failed)

Cause: The build identity lacks Contribute/Create tag permission, or checkout was not persistCredentials: true.

Fix: Grant repository permissions; if needed, check whether a branch policy prevents the build identity from pushing.

Command-line exercise
1. Write a counter variable that starts from 1 each day daily.
variables:
  daily: $[counter(format('{0:yyyyMMdd}', pipeline.startTime), 1)]
2. In a script, change the run build number to 1.4.7+build.412.
echo "##vso[build.updatebuildnumber]1.4.7+build.412"
Scenario analysis question
The library team uses the counter approach. Someone accidentally changed minor from 4 to 5 and back to 4; after 1.4.3 was published, 1.4.4 appeared… Would this conflict? Why?

There is no conflict and no duplication: counter counts separately for each prefix, and the count for prefix “1.4” continues from the last stopped value after switching back (official behavior), so it does not return to the seed. However, the 1.5.x versions published in the meantime already exist; if you later truly upgrade to 1.5, the counter continues from 1.5's last value, so the version number jumps but does not conflict.

Verified instructional videos

▶
Auto Version Bumping and Deployments (SemVer, GitFlow, GitVersion, CI&CD) — Gavin Greenwood
English · SemVer and the GitVersion auto-versioning approach
▶
Az400 v8 - GitVERSION | Microsoft Certification AZ400 | git SEMANTIC Version | #AzureDevOps — Azure DevOps TV
English · Using GitVersion in Azure DevOps (task versions may be older; follow this course's v4 syntax)

Official docs

Video storyboard (about 75 seconds)

Shot 1 · 0–25s
Visual: a Git commit graph with the last tag v1.4.6, followed by a merge commit; the GitVersion icon computes 1.4.7.
Narration: the version number is computed once from Git history.
Shot 2 · 25–50s
Visual: 1.4.7 splits into four streams flowing to the build number, package, image and Git tag.
Narration: the same value runs through all carriers; any of them can be traced back to the commit.
Shot 3 · 50–75s
Visual: a counter table, with prefixes 1.4 and 1.5 each counting separately.
Narration: if you do not want to introduce a tool, counter can also reset the patch number automatically when major/minor changes.
or score ≥ 70% in the quiz

Module 6 · Migrating classic releases to YAML

36:00 – 43:00 · Classic releases still run, but new organizations are already blocked from creating them; migration is not an “export”, but mapping concepts one by one
7 minutesClassic releases do not support Export to YAMLSince Sprint 226, new organizations have classic creation disabled by default★★★★☆
Learning objectives
  • Map classic release concepts to YAML: release definition → multi-stage pipeline; stage → stage + deployment job; deployment group → VM resources in an environment; task group → template; release variables → variables / variable groups; pre-stage approvals / gates → environment checks.
  • Know the official migration limitations: Only classic build pipelines support Export to YAML; classic releases do not support export, so each task must be rewritten; YAML scheduled triggers default to UTC, while classic uses the organization time zone.
  • Clarify the current status of classic pipelines: the toggle “Disable creation of classic build and classic release pipelines” (organization level and project level); new organizations have it enabled by default since Sprint 226; existing classic pipelines can still be edited and run.
Prerequisites: Modules 1–3. Importance:★★★★☆ (required for existing projects)

What: Classic Release

Release definitions configured in the web designer: artifacts + stages (environments) + each stage's tasks, approvals, gates and deployment groups. The configuration lives in Azure DevOps, not in the repository.

Current status (verified 2026-11)

  • Organization settings → Pipelines → Settings has a toggle Disable creation of classic build pipelines / classic release pipelines, which, when enabled, prevents creating classic builds, classic releases, task groups and deployment groups; existing classic pipelines can still be edited and run.
  • Official security guide: from Sprint 226 onward,new organizations disable creation of classic builds and releases by default; it is not automatically enabled for existing organizations.
  • The official security recommendation is to prefer YAML (versioned, PR reviews, templates and extends, protected resource checks). As of the verification date, no official retirement date for classic releases has been published; this course does not speculate on a timeline, so please follow the release notes.

Concept mapping table

Classic releaseYAMLMigration notes
Release pipelineMulti-stage YAML (or a separate “release pipeline” + resources.pipelines)Keep two pipelines if build and release cadences differ
Artifacts (build, ACR, GitHub…) + continuous deployment triggerresources.pipelines / resources.containers / resources.repositories + triggerArtifacts are obtained via download to get them
Stage (environment)stage + deployment job + environmentDeployment history is recorded on the environment instead
Pre/Post-deployment approvalsApproval check on the environment (before the stage starts); after deployment, confirm availability with ManualValidation or the next stage's approval“Post-deployment approval” has no one-to-one equivalent
Gates (Azure Monitor, REST, Work item query…)Checks: Query Azure Monitor alerts, Invoke REST API, Invoke Azure Function, Business hoursWork item query gate must be changed to a REST check
Deployment groupVirtualMachine resources in the environment + rolling strategyRe-register the environment agent on the target machines
Agentless phasepool: server job—
Task groupsteps / jobs templatesParameters changed to typed template parameters
Release variables / variable groups / scoped variablesvariables (stage level) + variable groups (- group:)Stage-scoped variables changed to stage-level variables
$(Release.ReleaseName),$(Release.EnvironmentName)$(Build.BuildNumber),$(Environment.Name)Full-text search and replace predefined variables
Scheduled release trigger (organization time zone)schedules: cron (UTC)Watch the time zone conversion
Stage “redeploy” of an older versionRerun the stage of an old run (Rerun) or manually run a specified resource versionKeep old runs (retention policy)

How: migration path

  1. Inventory: use REST/CLI to list classic release definitions, stages, tasks, variables and approvals (commands are paginated).
  2. Build first: in the definition view of the classic build, choose ⋯ → Export to YAML Export (from the definition view, not from a specific run), then paste into a newly created starter pipeline and fix it up.
  3. Rewrite release tasks one by one: classic releases do not support export; open each task's “View YAML” in the classic editor, copy the snippet, and assemble it into a deployment job.
  4. Environments and checks: create an Environment for each stage; migrate approvals and gates to checks; add Required template to the production service connection.
  5. Run in parallel: deploy the new YAML to non-production first, and keep classic releases for a period as a fallback; after switching, disable the classic release triggers.
  6. Wrap-up: turn on the organization / project “Disable creation of classic pipelines” toggle; archive the classic definitions (keep history).

When: cases where migration should be postponed

  • Heavily dependent on deployment groups + many VMs with no one maintaining the agent registration scripts → migrate builds and non-production stages first.
  • Uses a Marketplace release task with no YAML equivalent → first evaluate alternatives or switch to a script.
Common misconceptions① “Export to YAML can export a release”. Officially, classic releases do not support export; only per-task export is possible. ② “Turning on the disable toggle stops existing classic pipelines”. No, it only prevents new creation. ③ “Post-deployment approval can be moved to YAML as is”. Environment checks all run before the stage starts; post-deployment confirmation must change to ManualValidation, an approval on the next stage, or a check in postRouteTraffic.

Structure comparison: classic release → YAML

Classic release (configured server-side) Artifacts+ CD trigger Dev stageTask group Prod stageDeployment group Pre-approval + gates Release variables (stage-scoped) Changes without PR or code reviewHistory in the “Releases” list YAML (in the repository) resources.pipelines+ trigger stage Devsteps template stage Prodenv VM + rolling Environment checks stage-level variables + variable groups PR review, template reuse, Required templateHistory in the environment's deployment records Item-by-item mapping
Figure 6-1 Migration is concept mapping, not format conversion

Interactive cards: classic element → YAML equivalent

Click a classic release element on the left to see its YAML equivalent, migration notes and common pitfalls. Going through all of them completes the “migration inventory”.

YAML equivalent
Migration notes

Inventory and migration commands

CommandPurposeNotes
az pipelines release definition list -o tableList classic release definitionsRequires the azure-devops extension
az pipelines release definition show --id NView definition JSON (stages, tasks, approvals)Good for scripted inventory
az pipelines release list --definition-id N --top 5Recent releasesConfirm whether still in use
REST GET vsrm.dev.azure.com/{org}/{project}/_apis/release/definitions?$expand=environmentsFull exportNote: the hostname is vsrm
REST PATCH …/_apis/build/generalsettingsProject-level “Disable creation of classic pipelines”Field disableClassicBuildPipelineCreation,disableClassicReleasePipelineCreation
# Inventory: number of stages and tasks per classic release definition
for id in $(az pipelines release definition list --query "[].id" -o tsv); do
  az pipelines release definition show --id $id \
    --query "{name:name, stages:environments[].{stage:name, tasks:length(deployPhases[0].workflowTasks), preApprovals:length(preDeployApprovals.approvals)}}" -o json
done
{
  "name": "myapp-release",
  "stages": [
    { "stage": "Dev",  "tasks": 3, "preApprovals": 1 },
    { "stage": "Prod", "tasks": 5, "preApprovals": 1 }
  ]
}

When there is no approval preApprovals is also 1. Classic releases use a single isAutomated: true placeholder approval to mean “automatic”; when taking inventory, check the isAutomated field.

# Enable “Disable creation of classic build and release pipelines” at project level (organization level is under Organization settings → Pipelines → Settings)
az devops invoke --area build --resource generalsettings --route-parameters project=myapp-lab \
  --http-method PATCH --api-version 7.1 \
  --in-file settings.json   # {"disableClassicBuildPipelineCreation":true,"disableClassicReleasePipelineCreation":true}

Conservative note:generalsettings 's field names follow the REST docs “General Settings - Update”; if unsure, make the change directly in the portal.

Lab 6: rewrite a classic release as YAML (about 7 minutes)

Prerequisites If your organization was created after Sprint 226, classic release creation is disabled by default. The lab can be completed on paper by mapping the provided classic definition JSON; those with an existing organization can temporarily turn off the toggle in a test project to create a classic release (restore it afterward).
Read the classic definition (example: two stages, Dev automatic, Prod pre-approval + Azure Monitor gate; the task group “Deploy-ACA” has two tasks):
{
  "name": "myapp-release",
  "artifacts": [{ "alias": "_myapp-ci", "type": "Build", "isPrimary": true }],
  "triggers": [{ "triggerType": "artifactSource", "artifactAlias": "_myapp-ci" }],
  "variables": { "rg": { "value": "rg-ado-lab" } },
  "environments": [
    { "name": "Dev",  "variables": { "app": { "value": "myapp-dev" } },
      "deployPhases": [{ "workflowTasks": [{ "name": "Task group: Deploy-ACA" }] }] },
    { "name": "Prod", "variables": { "app": { "value": "myapp" } },
      "preDeployApprovals": { "approvals": [{ "approver": { "displayName": "Release Managers" } }] },
      "preDeploymentGates": { "gates": [{ "tasks": [{ "name": "Query Azure Monitor alerts" }] }] },
      "deployPhases": [{ "workflowTasks": [{ "name": "Task group: Deploy-ACA" }] }] }
  ]
}
Task group → template:
parameters:
- name: app
  type: string
- name: image
  type: string
steps:
- task: AzureCLI@2
  inputs:
    azureSubscription: sc-azure-myapp
    scriptType: bash
    scriptLocation: inlineScript
    inlineScript: az containerapp update -n ${{ parameters.app }} -g $(rg) --image ${{ parameters.image }}
Release definition → release pipeline (separate from CI, triggered by a pipeline resource):
trigger: none
resources:
  pipelines:
  - pipeline: ci                 # corresponds to the classic artifact alias
    source: myapp-ci
    trigger: { branches: { include: [ main ] } }
  repositories:
  - repository: templates
    type: git
    name: myapp-lab/pipeline-templates
    ref: refs/tags/v1.1.0
variables:
  rg: rg-ado-lab
  image: acrmyapp21877.azurecr.io/myapp:$(resources.pipeline.ci.runName)
stages:
- stage: Dev
  variables: { app: myapp-dev }
  jobs:
  - deployment: Deploy
    environment: myapp-dev
    pool: { vmImage: ubuntu-latest }
    strategy:
      runOnce:
        deploy:
          steps:
          - download: none
          - template: templates/steps/deploy-aca.yml@templates
            parameters: { app: $(app), image: $(image) }
- stage: Prod
  variables: { app: myapp }
  jobs:
  - deployment: Deploy
    environment: myapp-prod      # approval and Azure Monitor alert checks are configured on this environment
    pool: { vmImage: ubuntu-latest }
    strategy:
      runOnce:
        deploy:
          steps:
          - download: none
          - template: templates/steps/deploy-aca.yml@templates
            parameters: { app: $(app), image: $(image) }

$(resources.pipeline.ci.runName) is the build number of the CI run that triggered it (i.e., the image tag), corresponding to the classic $(Release.Artifacts._myapp-ci.BuildNumber).

Approvals and gates → environment checks: on myapp-prod , confirm the Approval (Release Managers), and add a new Query Azure Monitor alerts check (choose the subscription, resource group and alert rule).
Parallel validation and switchover: after the new pipeline successfully deploys to dev, disable the classic release's continuous deployment trigger; after observing for two weeks, archive the classic definition and turn on the “disable creation” toggle in project settings.

Case 1: after migration, the scheduled deployment moved 5 hours earlier

Problem: The classic release deployed the test environment every night at 22:00 (organization time zone EST); after migrating to cron: '0 22 * * *' , it became 22:00 UTC. Fix: Official note: YAML schedules use UTC, while classic uses the organization time zone; convert to 0 3 * * * (watch for daylight saving time).

Case 2: the classic “post-deployment approval” was lost

Problem: The classic Prod stage had a post-deployment approval for business acceptance; after migration it was simply gone. Fix: Add a Signoff stage after the Prod stage, where one agentless job uses ManualValidation; when compliance evidence is required, have the Signoff stage use an environment used only for approval myapp-prod-signoff (the environment may have no resources) and configure an Approval on it.

Case 3: a task group referenced by 30 classic releases

Problem: Changing one task group immediately affects 30 releases (task groups have no version pinning). Fix: Migrate to templates in a template repository; consumers use ref to pin a fixed version and upgrade one by one. This itself is one of the benefits of migration.

Common errors and fixes

No “New release pipeline” / “Classic editor” entry visible in the portal

Cause: The organization or project has disabled creation of classic pipelines (new organizations have this on by default).

Fix: This is expected behavior; use YAML. If creation is temporarily required, a Project Collection Administrator must turn off the organization toggle.

No “Export to YAML” in the ⋯ menu

Cause: You are on a specific run page rather than the definition page; or this is a classic release (export is not supported); or the classic build was not created with the classic build designer.

Fix: Go to the build definition view; for releases, use “View YAML” task by task.

After migration, script error: Release.EnvironmentName: command not found / variable is empty

Cause: The YAML pipeline does not have Release.* predefined variables.

Fix: Replace with Environment.Name,Build.BuildNumber,resources.pipeline.<alias>.runName , etc.

Pipeline resource ci is not authorized / the release pipeline is not triggered when the CI pipeline completes

Cause:source It must be the CI pipeline's name (not the file name); first use requires authorization; a pipeline resource trigger in a YAML file only takes effect when it is defined in the version on the default branch.

Fix: Verify the name; merge release.yml into the default branch; authorize the resource on the run page.

Command-line exercise
1. Write the pipeline resource snippet that is triggered when the CI pipeline myapp-ci completes on main.
resources:
  pipelines:
  - pipeline: ci
    source: myapp-ci
    trigger:
      branches: { include: [ main ] }
2. Use the CLI to list the Prod stage task names of classic release definition 7.
az pipelines release definition show --id 7 --query "environments[?name=='Prod'].deployPhases[].workflowTasks[].name"
Scenario analysis question
An existing organization has 120 classic releases, heavily using deployment groups. Management requires “migrate everything this quarter”. What is your migration plan?

First take an inventory (export stages, tasks, approvals and deployment groups via CLI/REST) and group by risk; the first batch migrates only PaaS releases (runOnce + environment checks); build a template repository and rewrite commonly used task groups as templates; for deployment group scenarios, register environment resources on the target VMs and use the rolling strategy, rehearsing retry behavior in non-production first; run each application in parallel for a period before disabling the classic triggers; finally, turn on the organization-level disable-creation toggle. Deployment group scenarios that cannot be completed within one quarter should be scheduled separately.

Verified instructional videos

▶
Migrating Classic Azure DevOps Pipelines to YAML with Manual Approvals — Microsoft DevRadio
English · Classic-to-YAML migration and approvals
▶
Migrate Classic pipeline to YAML pipeline | Azure Pipeline | Azure Devops | An IT Professional — An IT Professional
English · Export to YAML demonstration

Official docs

Video storyboard (about 75 seconds)

Shot 1 · 0–25s
Visual: the classic release canvas (artifacts, two stages, a lightning approval icon), each flying to the matching spot in the YAML file on the right.
Narration: migration maps each concept to YAML, rather than a one-click export.
Shot 2 · 25–50s
Visual: in the ⋯ menu, Export to YAML appears only on the build definition; on the release definition it is grayed out.
Narration: classic builds can be exported; classic releases can only have their YAML viewed task by task.
Shot 3 · 50–75s
Visual: the organization settings toggle “Disable creation of classic pipelines” is on, and existing classic pipelines are still running.
Narration: new organizations block creation of classic pipelines by default; existing ones remain usable.
or score ≥ 70% in the quiz

Module 7 · Tests, code coverage and quality gates

43:00 – 52:00 · Test results go to the Tests tab, coverage goes to the Code Coverage tab; gates work at three layers: pipeline failure, PR status, branch policy
9 minutesPublishTestResults@2PublishCodeCoverageResults@2Default target for diff coverage is 70%★★★★★
Learning objectives
  • Use PublishTestResults@2 Publish JUnit/NUnit/xUnit/VSTest(TRX)/CTest results, and understand failTaskOnFailedTests,condition: succeededOrFailed() and flaky test rerun analysis.
  • Use PublishCodeCoverageResults@2 (inputs summaryFileLocation,pathToSources, and failIfCoverageEmpty) to publish Cobertura/JaCoCo coverage, and understand that it only supports build pipelines, as well as the differences between v1 and v2.
  • Configure azurepipelines-coverage.yml so that PRs show diff coverage status, and in branch policies set the status {pipeline-name}/codecoverage to required, which changes “suggest” into “block merge”.
  • Understand the role of Azure Test Plans (manual/exploratory testing, test plans and suites), and how it relates to automated test results.
Prerequisites: Lesson 1 (branch policies), Lesson 2 (PR triggers). Importance:★★★★★

What: three types of quality signals

SignalSource taskWhere to viewCan block merge?
Test resultsPublishTestResults@2 (or built-in publishing in VSTest/DotNetCoreCLI)Run page Tests tab, Test AnalyticsTest failure → task fails → build validation policy fails → blocks
CoveragePublishCodeCoverageResults@2Code Coverage tab (for multi-stage pipelines, wait until the entire run completes)Threshold failures must be implemented yourself in the test command (e.g., --cov-fail-under)
diff coverage statusThe platform calculates coverage for changed lines in the PR based on published coveragePR status area + optional file-level commentsSuggest only by default; blocks after adding a status policy in branch policies

How: PublishCodeCoverageResults@2 (verify)

  • Only three inputs: summaryFileLocation (required, supports minimatch; multiple files are merged into one report),pathToSources (specify the source root when the report has no absolute paths, e.g., JaCoCo or tests run inside a container),failIfCoverageEmpty (default false).
  • v2 generates cjson and HTML reports, supports many formats including .coverage, .covx, .covb, .cjson, .xml (Cobertura/JaCoCo, etc.), .lcov, and can generate diff coverage for multiple languages in the same pipeline; v1 only accepts a single Cobertura/JaCoCo summary file.
  • Official requirement: can only be used in build pipelines (YAML or classic build), not for classic release; the official note recommends running UseDotNet@2 first (v2 depends internally on .NET).
  • Maximum total size of coverage attachments per build 10 GB, beyond which they are not processed.

How: diff coverage and branch policies

  1. After the PR-triggered build validation pipeline publishes coverage, the platform calculates coverage for the changed executable lines of the PR and publishes a status to it (default target 70%).
  2. The repo root's azurepipelines-coverage.yml can change the target and whether to publish file-level comments (comments: on). It belongs to the repository rather than a specific pipeline.
  3. The status name follows the convention {pipeline name}/codecoverage; in Branch policies → Status checks in it, add it and set it to Required; PRs that don't meet the target cannot be completed.
  4. Limitations (official troubleshooting section): the coverage policy gets stuck when a PR has more than 100 files; only configure one coverage policy; you must use the V2 task to generate diff comments; only applies to Azure Repos.
Conservative note: inconsistency in the docs The same official page says in one place that v2 can “generate diff coverage for multiple languages,” while the FAQ elsewhere says “currently PR coverage can only be validated with the Visual Studio code coverage (.coverage) format.” Therefore, this lesson uses belt and suspenders for Python (Cobertura): in the test command, use pytest --cov-fail-under=80 to fail the build (reliably effective), while also configuring the diff coverage status (better if it works for Cobertura in your organization).

Introduction to Azure Test Plans

Test Plans is a management tool for manual and exploratory testing: test plan → test suites (static, requirement-based, query-based) → test cases (steps and expected results). Tests can be run and results recorded in the Web Test Runner, and defects can be filed. Results are traceable to requirement work items; automated tests can also be linked to test cases. Licensing: Full functionality requires Basic + Test Plans access level (paid). Basic users can run tests and use the Test & Feedback extension for exploratory testing. For specific permissions and pricing, refer to the official “Test Plans access levels” page.

When: layered gate design

LayerMechanismBest for
1 Within the buildtest failures,--cov-fail-underhard minimum, runs on all branches
2 PR statusdiff coverage, SonarQube and other external statusesfocus on quality of “new code”
3 Branch policybuild validation + required status + reviewersmake 1 and 2 prerequisites for merging
4 Before releaseEnvironment check (Invoke REST API to query the quality platform)final gate before deployment
Common misconceptions① “Publishing coverage will automatically block low coverage” — by default it only shows a suggestion status; you need a branch policy or a threshold in the test command. ② “Failed tests in PublishTestResults will make the task fail” — by default this is not true failTaskOnFailedTests: false, because failed tests usually already make the test command itself fail; only results-publishing scenarios need to enable it explicitly. ③ “You can see coverage once the Build stage of a multi-stage pipeline finishes” — official note: coverage is only visible after the entire run completes.

Quality signal flow

PR submittedBuild validation policy triggers build validation pipeline pytest --junitxml--cov-report=xml--cov-fail-under=80 PublishTestResults@2PublishCodeCoverageResults@2Result: Succeeded / Failed Tests tabFailures, reruns, trends Code Coverage tabFile/directory drill-down + HTML PR statusmyapp-ci/codecoverage Branch policy (main)Build validation: requiredStatus check: required→ can the PR be completed?
Figure 7-1: build results and coverage status only become a “gate” when enforced through branch policies

Interactive checker: can this PR be merged?

Adjust the number of test failures, overall coverage, PR changed-line coverage, and policy settings; the checker gives a verdict and reason based on three layers of rules.

Failing test count: 0
Overall line coverage: 84% (--cov-fail-under=80)
PR changed-line coverage (diff): 55%
diff target (azurepipelines-coverage.yml): 70%

Core tasks and configuration

Task / fileKey inputsNotes
PublishTestResults@2testResultsFormat (JUnit/NUnit/VSTest/XUnit/CTest),testResultsFiles,failTaskOnFailedTests,testRunTitleSet condition: succeededOrFailed(), so results are published even when tests fail
PublishCodeCoverageResults@2summaryFileLocation,pathToSources,failIfCoverageEmptybuild pipelines only
azurepipelines-coverage.ymlcoverage.status.comments,coverage.status.diff.targetrepo root; the file name must match exactly
az repos policy build createBuild validation policysee below
In the portal: Branch policies → Status checks (the CLI can use the generic az repos policy create --policy-configuration <json>)Required statusStatus name myapp-ci/codecoverage
steps:
- task: UsePythonVersion@0
  inputs: { versionSpec: '3.12' }
- bash: |
    pip install -r requirements.txt pytest pytest-cov
    pytest tests --junitxml=$(Build.ArtifactStagingDirectory)/test-results.xml \
      --cov=app --cov-report=xml:$(Build.ArtifactStagingDirectory)/coverage.xml \
      --cov-fail-under=80
  displayName: pytest + coverage
- task: PublishTestResults@2
  condition: succeededOrFailed()
  inputs:
    testResultsFormat: JUnit
    testResultsFiles: '$(Build.ArtifactStagingDirectory)/test-results.xml'
    testRunTitle: 'myapp unit tests (py3.12)'
- task: UseDotNet@2                       # Official note: install .NET before the v2 task
  condition: succeededOrFailed()
  inputs: { packageType: sdk, version: 8.x }
- task: PublishCodeCoverageResults@2
  condition: succeededOrFailed()
  inputs:
    summaryFileLocation: '$(Build.ArtifactStagingDirectory)/coverage.xml'
    pathToSources: '$(Build.SourcesDirectory)'
    failIfCoverageEmpty: true
coverage:
  status:
    comments: on        # publish a coverage comment for each changed file in the PR
    diff:
      target: 80%       # default 70%
REPO_ID=$(az repos show -r myapp --query id -o tsv)
PIPE_ID=$(az pipelines show --name myapp-ci --query id -o tsv)
# Build validation (required)
az repos policy build create --repository-id $REPO_ID --branch main --build-definition-id $PIPE_ID \
  --blocking true --enabled true --queue-on-source-update-only false --manual-queue-only false \
  --display-name "CI must pass" --valid-duration 720
az repos policy list --repository-id $REPO_ID --branch main --query "[].{type:type.displayName,blocking:isBlocking}" -o table
Type                     Blocking
-----------------------  ----------
Minimum number of reviewers  True
Build                    True

The most reliable way to add the status check policy is in the portal: Repos → Branches → main ⋯ → Branch policies → Status checks → + → select myapp-ci/codecoverage (it only appears in the list after a PR has published that status for the first time) → Required.

Lab 7: pytest + coverage gate (about 9 minutes)

Add tests to myapp:
from app import create_app

def test_healthz_ok(monkeypatch):
    app = create_app(testing=True)
    client = app.test_client()
    resp = client.get("/healthz")
    assert resp.status_code == 200
    assert resp.get_json()["status"] == "ok"

If the Lesson 2 myapp has no create_app factory function, use the Docker lesson's myapp, app.py importing it directly from app import app and using app.test_client(); in tests, replace the Redis dependency with monkeypatch or fakeredis a similar stub.

Put the test steps into a template: use Module 1's templates/steps/python-test.yml, plus two steps for PublishTestResults and PublishCodeCoverageResults, and tag it v1.2.0, and reference it in myapp's extends parameter.
Push and view the results:
git add tests azurepipelines-coverage.yml azure-pipelines.yml
git commit -m "test: add health tests and coverage gate" && git push
---------- coverage: platform linux, python 3.12.x -----------
Name              Stmts   Miss  Cover
-------------------------------------
app/__init__.py      18      2    89%
app/health.py        12      1    92%
-------------------------------------
TOTAL                30      3    90%
Coverage XML written to file /home/vsts/work/1/a/coverage.xml
Required test coverage of 80% reached. Total coverage: 90.00%
========================= 3 passed in 0.82s =========================
Configure branch policy and verify blocking: add the build validation policy (the CLI above), create a branch that adds one function without tests, open a PR, and observe the PR status myapp-ci/codecoverage; then set it as a required status. Push coverage below 80% (by adding a lot of untested code) and observe that the build fails and the PR cannot be completed.
(Optional) Test Plans: Test Plans → New Test Plan “myapp 1.4 acceptance” → add a requirement-based suite (select user stories from Boards) → create a test case “Accessing /healthz returns ok” → Run for web application to execute and record results.

Case 1: coverage gate blocks all PRs

Problem: After enabling the coverage status policy, the status of a large refactoring PR stays “Pending”. Root cause: Official troubleshooting: the coverage policy gets stuck when a PR has more than 100 files; additionally, if two coverage policies are configured, one of them will get stuck. Fix: Keep only one coverage policy; split large refactors into smaller PRs, or have an admin override the policy to complete the merge through the defined process.

Case 2: Code Coverage tab is always empty

Problem: After the Build stage of a multi-stage pipeline finishes, coverage is not visible, and the team assumes the task failed. Root cause: The official note says coverage for multi-stage pipelines only appears after the entire run completes, and the prod stage is waiting for approval. Fix: Split PR validation and deployment into two pipelines (PR validation has only a Build stage); or accept the delay.

Case 3: flaky tests cause frequent release failures

Problem: Integration tests time out with a 3% probability. Fix: Use Test Analytics to find unstable tests; enable Flaky test detection in project settings; add retries to network-related tests and isolate them to a nightly pipeline; do not use continueOnError to hide failures.

Common errors and fixes

##[warning]No test result files matching '**/TEST-*.xml' were found.

Cause:testResultsFiles The pattern does not match the actual path (the default pattern is **/TEST-*.xml), or the publish task does not run after a test step fails (missing condition: succeededOrFailed()).

Fix: Use absolute paths; add a condition.

No code coverage results were found to publish. / The code coverage tab shows no data

Cause: coverage.xml is empty or the path is wrong; not generated because tests failed; used in a classic release (not supported).

ls -l $(Build.ArtifactStagingDirectory); head -c 400 $(Build.ArtifactStagingDirectory)/coverage.xml

Fix: verify the path,failIfCoverageEmpty: true and make the problem visible.

File paths in the Coverage XML are relative, so when you open a file in the Code Coverage tab you cannot see the source code

Cause: The report does not contain absolute paths (common with JaCoCo and tests run inside containers).

Fix: Set pathToSources: $(Build.SourcesDirectory) (or the corresponding subdirectory).

Code coverage status check stays Pending / no diff comments appear

Cause: Using PublishCodeCoverage V1; PR has more than 100 files; multiple coverage policies configured; the name in the branch policy does not match the pipeline name; the changes contain only non-executable lines.

Fix: Switch to V2; verify the policy name {pipeline}/codecoverage; keep only one policy.

FAIL Required test coverage of 80% not reached. Total coverage: 72.41%

Cause: This is the pytest-cov threshold gate working as designed.

Fix: Add tests; do not lower the threshold on a whim, since lowering it should go through review.

Command-line exercises
1. Write the v2 task that publishes Cobertura coverage and fails the task if there are no results.
- task: PublishCodeCoverageResults@2
  inputs:
    summaryFileLocation: '$(System.DefaultWorkingDirectory)/**/coverage.xml'
    failIfCoverageEmpty: true
2. Write the configuration file that sets the PR diff coverage target to 85% and enables comments.
coverage:
  status:
    comments: on
    diff:
      target: 85%
Scenario analysis
A legacy project has only 35% overall coverage, and management requires an 80% coverage gate. What happens if you directly set --cov-fail-under=80 in pytest? What is a better approach?

All builds fail immediately, and the team will bypass the gate. A better approach is a “new code gate”: first set the overall threshold to the current value (35%) to prevent regression, and raise it each quarter; for PRs, use the diff coverage status (target 80%) and set it as required in branch policies, so that only changed lines must be covered. If the diff status does not work for Cobertura in your organization, use a tool such as diff-cover to compute changed-line coverage in the pipeline and fail the build.

Verified instructional videos

▶
Azure DevOps: Adding unit tests and code coverage to YAML pipelines — Bogdan Bujdea
English · .NET example, analogous to the Python flow (task versions follow v2 in this lesson)
▶
🧪 Add Unit Tests & Code Coverage to Azure Pipelines 🔥 | Full Guide — LazyDevCoder
English · complete demo of test and coverage publishing

Official documentation

Video storyboard script (about 75 seconds)

Shot 1 · 0–25s
Visual: the pytest output, JUnit XML, and coverage.xml files flow respectively into the Tests and Code Coverage tabs.
Narration: test results and coverage are two different publishing tasks.
Shot 2 · 25–50s
Visual: the PR page shows the codecoverage status, with green/red coverage indicators next to the changed lines.
Narration: diff coverage only looks at the lines you changed; the default target is seventy percent.
Shot 3 · 50–75s
Visual: the branch policy toggle is on, and the Complete button is grayed out.
Narration: only when set as required in branch policies does the status actually block the merge.
or score ≥ 70% on the “Quiz”

Module 8 · First five hours recap, self-check, and cleanup

52:00 – 60:00 · Tie the platform, repos, CI, cloud CD and production-grade pipelines into one diagram, then troubleshoot, self-check, and shut down billable resources
8 minutesInteractive troubleshooting treeBefore cleaning up rg-ado-lab, confirm whether Lesson 6 reuses it★★★★☆
Learning objectives
  • Use one diagram to recap the first five hours: organization/project/permissions (Lesson 1) → YAML and agents (Lesson 2) → service connections and Azure deployment (Lesson 3) → AWS deployment (Lesson 4) → templates, promotion, artifacts and quality (Lesson 5).
  • Use the troubleshooting tree to locate five common failure types: template not found, parameter type errors, cross-repo template permissions, Artifacts 401/403, and deployment job lock conflicts and waits.
  • Estimate this lesson's resource costs and clean up safely (keep the projects and template repos needed for Lesson 6).
Importance:★★★★☆

First five hours knowledge map

LessonCore skillsHow it is used in this lesson
Lesson 1: Platform and collaborationOrganizations, projects, security groups, Boards, Repos branch policies, CLI/RESTBranch policies carry the coverage gate; Build Service identity authorization
Lesson 2: Azure PipelinesYAML structure, triggers, agents, variables, artifacts, template basicsDeeper templates, counter, output variables
Lesson 3: Azure CDWIF service connections, Environments, Container Apps, IaCcanary deployment targets, Required template added to the service connection
Lesson 4: AWS CDOIDC, ECR, ECS, multi-account promotionThe same template/promotion pattern applies to AWS service connections
Lesson 5 (this lesson)extends, multi-stage, deployment strategies, Artifacts, versioning, migration, quality gates—

10-point checklist for production pipelines

  1. Pipelines extend platform templates; pin the template repo ref to a tag or SHA.
  2. Production service connections and production environments have Required template + Approval + Branch control.
  3. The prod stage condition is limited to main and non-PR.
  4. Build once, deploy many: images/packages are built only once; tags are passed via output variables.
  5. Deploy using deployment jobs (which keep deployment history); rollback logic lives in on.failure and has been rehearsed.
  6. Exclusive lock + lockBehavior prevents concurrent deployments.
  7. Dependencies come only from internal feeds, with public sources as upstream; release packages are promoted to @release.
  8. Version numbers are unique and carried through build number, packages, images and Git tags.
  9. Publish test results and coverage; thresholds fail within the build; PR status and build validation are required policies.
  10. Do not create new classic pipelines (the organization switch is turned on).

Lesson resource costs (canadacentral, illustrative)

ResourceBilling modelUsage and estimate for this lesson
Container Apps (myapp, myapp-dev)Billed per vCPU-second/GiB-second + requests, with a monthly free grantWith minimum replicas at 0, idle cost is nearly 0; a few cents during the lab
ACR BasicBilled per dayAbout US$0.17/day (Basic SKU; see the pricing page)
Azure Artifacts2 GiB free per organizationThis lesson's package is a few dozen KB, free
Microsoft-hosted agentFree-tier parallel jobs (requires a request) or purchaseThis lesson uses about 30–60 minutes of build time
Test PlansPer user access levelOptional; no cost if not purchased

Prices change over time and by region; refer to the Azure pricing calculator. Security risk: the service connection has Contributor permission on the resource group. If it is no longer needed after the lab, delete the service connection or delete the federated credential in Microsoft Entra ID; remove Build Service identities added to feed permissions as needed.

Five-hour overview: from commit to production

Repos + PRBranch policy (L1/L5) Compile YAMLextends template (L5) Build stageAgent (L2) · Version (L5) Quality gateTests + coverage (L5) ArtifactsACR · Artifacts feed Deploy_devWIF service connection (L3)Container Apps / ECS (L3/L4) Checks (before stage)Required template · approvalBranch control · exclusive lock Deploy_prod canary10% → 50% → 100%Tag · promote to @release L1–L5 = Lessons 1–5; Lesson 6 will extend “checks” to organization-level governance
Figure 8-1: where the first five hours of content fit in a single run

Interactive self-check: drag each failure symptom to the correct stage (click version)

Each question gives a real error or symptom; choose which stage of a run it occurs in. After answering all 8 questions, view your score and explanations.

Recap and cleanup commands

CommandPurpose
az pipelines runs list --top 10 -o tableReview this lesson's runs
az containerapp update -n ca-myapp-prod -g rg-ado-lab --min-replicas 0Keep the app, idle with no charge
az containerapp revision list -n ca-myapp-prod -g rg-ado-lab --query "[?properties.active].name"Check for leftover active revisions
az group delete -n rg-ado-lab --yes --no-waitFully delete Azure resources (once Lessons 6 and 7 no longer need them)
az devops service-endpoint delete --id <id> --yesDelete service connection
az repos policy list --repository-id <id>Review branch policies
# Option A: keep the environment for Lesson 6 (recommended); only reduce cost
for app in myapp myapp-dev; do
  az containerapp update -n $app -g rg-ado-lab --min-replicas 0 --max-replicas 1 -o none
  for r in $(az containerapp revision list -n $app -g rg-ado-lab --query "[?properties.active && properties.trafficWeight==\`0\`].name" -o tsv); do
    az containerapp revision deactivate -n $app -g rg-ado-lab --revision $r
  done
done

# Option B: fully clean up Azure resources (keep the Azure DevOps project, template repo and source; they incur no cost)
az group delete -n rg-ado-lab --yes --no-wait
az group list --query "[?name=='rg-ado-lab']" -o table
(empty output, meaning the resource group has been deleted)

After deleting the resource group, the Lesson 3 service connection still exists but its target resources are gone; the start of Lesson 6 gives the rebuild commands. Packages in the Artifacts feed and packages in the recycle bin both count toward the 2 GiB free quota; this lesson's size is negligible.

Lab 8: one end-to-end regression + cleanup (about 6 minutes)

Commit a small change (for example, in /healthz the return value, add a version field), and confirm: the PR build passes, the diff coverage status appears, and after merging, main runs to prod and waits for approval.
Approve and observe the canary: 10% → 50% → 100%; on.success deactivates the old revision, tags Git, and promotes the package to @release.
curl -s https://myapp.$ACA_DOMAIN/healthz
git fetch --tags && git describe --tags --abbrev=0
{"status":"ok","version":"1.4.8"}
v1.4.8
Walk through the troubleshooting tree on the Troubleshooting page of Module 8, completing at least the “template not found” and “Artifacts 401” paths.
Cleanup: run Option A or B; in sc-azure-myapp re-enable (Enable) the Required template check that was temporarily disabled in Module 2; delete the temporary pipelines and branches from the lab.

Case: retrospective on a platform team's rollout of a “golden pipeline”

Background: A team had 60 services in 3 languages, mixing classic releases and YAML; 40% of production incidents were related to “inconsistent deployment methods”. Approach:① Create a pipeline-templates repo providing build templates per language and deployment templates per platform, all extending one secure skeleton; ② add Required template to production service connections; ③ unify the internal Artifacts feed and upstream; ④ unify versioning with GitVersion; ⑤ add a diff coverage gate; ⑥ migrate classic releases in three batches, and finally turn on the switch that prohibits creating new ones. Result: Deployment methods were consolidated into 2 templates, and rollback drills covered all production services. Lessons learned: The template repo itself must have PRs, a test pipeline, and semantic version tags; changes to a Required template's ref must be rolled out before consumers are upgraded.

Common errors and fixes (summary)

File /templates/x.yml not found in repository … branch refs/heads/main

Template path or ref errors: see Module 1 troubleshooting. Note: if ref is omitted, the default is refs/heads/main, and if the template repo's default branch is named master, it will not be found.

The 'x' parameter is not a valid … / Expected a sequence

Parameter type or values validation failures: see Module 1.

HTTPError: 401/403 from pkgs.dev.azure.com

Missing authentication task or build identity lacks source permissions: see Module 4.

Waiting for exclusive lock on environment myapp-prod / Job is pending

Another run holds the exclusive lock, or a job name conflicts: see Modules 2 and 3.

Interactive troubleshooting decision tree: common production pipeline issues

Covers six symptom types: template not found, parameter type errors, cross-repo template permissions, Artifacts 401/403, deployment job lock conflicts and waits, and empty output variables. Select what you see and narrow it down step by step.

Command-line exercises
1. List all active revisions of myapp and their traffic weights.
az containerapp revision list -n ca-myapp-prod -g rg-ado-lab --query "[?properties.active].{name:name,weight:properties.trafficWeight}" -o table
2. Query all branch policies on the main branch and whether each one blocks merges.
az repos policy list --repository-id $(az repos show -r myapp --query id -o tsv) --branch main --query "[].{type:type.displayName,blocking:isBlocking}" -o table
Scenario analysis
On Friday afternoon, the prod stage is stuck on “Waiting” with no approval request, and the team is worried. What order do you troubleshoot in?

① Check the stage's Checks panel: is it waiting on an exclusive lock (held by another run), Business hours, or Invoke REST API retries; ② is the Required template static check still being evaluated or has it failed; ③ if the stage has started, check whether it is stuck on the agentless job's ManualValidation; ④ is the job “pending”: no agents available in the agent pool, parallel jobs exhausted, or a job name conflict; ⑤ is lockBehavior=sequential queuing it behind several runs. Act on the conclusion: wait for or cancel old runs, adjust checks, or add parallel jobs.

Verified instructional videos

▶
Building and Deploying your Code with Azure Pipelines — Microsoft Visual Studio
English · official channel, end-to-end review of build and deployment
▶
(Simple?) Real World Azure Pipelines YAML Walkthrough — Julie Ng
English · real-project walkthrough, suitable as a review of the first five hours

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–30s
Visual: the Figure 8-1 overview lights up block by block, labeled with the lesson number.
Narration: over five hours, we went from the organization and repos all the way to a production pipeline with templates, checks, canary, and quality gates.
Shot 2 · 30–60s
Visual: the resource group delete command runs and the cost curve drops to zero; the next lesson title “Security and Governance” appears.
Narration: clean up billable resources; the next lesson extends these checks to organization-wide governance.
or score ≥ 70% on the “Quiz”

Command cheat sheet

Templates · multi-stage · deployment strategies · Artifacts · versioning · migration · quality gates — every code block can be copied with one click
Post-lesson reference

Templates

resources:
  repositories:
  - repository: templates
    type: git                       # github requires endpoint
    name: myapp-lab/pipeline-templates
    ref: refs/tags/v1.2.0           # or a 40-character SHA; omitted = refs/heads/main
extends:
  template: templates/secure-pipeline.yml@templates
  parameters: { buildSteps: [ ... ] }
# Insert: - template: steps/x.yml@templates
# Parameter types: string number boolean object step stepList job jobList
#           deployment deploymentList stage stageList (stringList cannot be used for templates)
# Limits: 100 files / 100 levels of nesting / 20 MB parse memory
- ${{ each e in parameters.envs }}:
  - ${{ if eq(e.approval, true) }}:
    - job: Confirm_${{ e.name }}

Multi-stage and output variables

# Set
- bash: echo "##vso[task.setvariable variable=tag;isOutput=true]$TAG"
  name: setTag
# another job in the same stage
v: $[ dependencies.Build.outputs['setTag.tag'] ]
# job variable in the next stage
v: $[ stageDependencies.Build.Build.outputs['setTag.tag'] ]
# stage condition for the next stage
condition: eq(dependencies.Build.outputs['Build.setTag.tag'], 'x')
# runOnce deployment job: job name is duplicated
$[ stageDependencies.S.Dep.outputs['Dep.step.var'] ]
# canary: deploy_10.step.var    rolling: deploy_vm1.step.var
lockBehavior: sequential   # default runLatest; requires an exclusive lock check

ManualValidation and conditions

- job: Confirm
  pool: server
  timeoutInMinutes: 1440        # job timeout > task timeout
  steps:
  - task: ManualValidation@1
    timeoutInMinutes: 720       # maximum 30 days
    inputs:
      notifyUsers: ''
      approvers: '[proj]\Release Managers'
      onTimeout: reject         # or resume
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'), ne(variables['Build.Reason'], 'PullRequest'))
# Check order: static (Branch control/Required template/Evaluate artifact)
#  → pre-approval → dynamic (Approval/REST/Function/Business hours/Monitor) → post-approval → exclusive lock

Deployment strategies

strategy:
  runOnce:  { preDeploy, deploy, routeTraffic, postRouteTraffic, on: { failure, success } }
  rolling:  { maxParallel: 2 | '50%', ... }      # VM resources only
  canary:   { increments: [10, 50], ... }        # $(strategy.increment) / action / name
# the deploy hook automatically downloads the current run's artifacts; when not needed, use - download: none
# artifact path: $(Pipeline.Workspace)/<artifact>
az containerapp revision set-mode -n ca-myapp-prod -g rg-ado-lab --mode multiple
az containerapp update -n ca-myapp-prod -g rg-ado-lab --image ACR/myapp:TAG --revision-suffix r123
az containerapp ingress traffic set -n ca-myapp-prod -g rg-ado-lab --revision-weight myapp--r123=10 myapp--old=90
az containerapp ingress traffic show -n ca-myapp-prod -g rg-ado-lab -o table
az containerapp revision deactivate -n ca-myapp-prod -g rg-ado-lab --revision myapp--old

Azure Artifacts

- task: TwineAuthenticate@1
  inputs: { artifactFeed: myapp-lab/myapp-feed }   # organization feed: myapp-feed
- bash: python -m twine upload -r myapp-feed --config-file $(PYPIRC_PATH) dist/*
- task: PipAuthenticate@1
  inputs: { artifactFeeds: myapp-lab/myapp-feed }
- task: npmAuthenticate@0
  inputs: { workingFile: .npmrc }
- task: NuGetAuthenticate@1
- task: MavenAuthenticate@0
  inputs: { artifactsFeeds: myapp-feed }
# view URL: …/_packaging/myapp-feed@release/pypi/simple/
pip install keyring artifacts-keyring
az artifacts universal publish --organization https://dev.azure.com/ORG --project myapp-lab --scope project \
  --feed myapp-feed --name bundle --version 1.0.0 --path ./out
# retention policy: max versions + days since last download (both must be met to delete); packages in views are exempt; recycle bin 30 days; 2 GiB free

Versions and tags

variables:
  major: 1
  minor: 4
  patch: $[counter(format('{0}.{1}', variables['major'], variables['minor']), 0)]
name: $(major).$(minor).$(patch)
# default name: $(Date:yyyyMMdd)$(Rev:.r)
- checkout: self
  fetchDepth: 0
  persistCredentials: true
- task: gitversion-setup@4
  inputs: { versionSpec: '6.8.x' }
- task: gitversion-execute@4
  name: version                # $(GitVersion_SemVer) / $(version.semVer)
echo "##vso[build.updatebuildnumber]1.4.7"
echo "##vso[build.addbuildtag]release"
git tag -a v1.4.7 -m "release v1.4.7" && git push origin v1.4.7
git log "$(git describe --tags --abbrev=0)"..HEAD --merges --pretty='- %s'

Classic → YAML

az pipelines release definition list -o table
az pipelines release definition show --id 7 --query "environments[].name"
# classic build: Definition view ⋯ → Export to YAML (classic releases do not support export)
# YAML schedules are in UTC; classic uses the organization time zone
# Release.EnvironmentName → Environment.Name
# Release.Artifacts.<alias>.BuildNumber → resources.pipeline.<alias>.runName
# organization switch: Disable creation of classic build/release pipelines (on by default for new organizations since Sprint 226)

Tests and coverage

- bash: pytest --junitxml=$(Build.ArtifactStagingDirectory)/test-results.xml --cov=app --cov-report=xml:$(Build.ArtifactStagingDirectory)/coverage.xml --cov-fail-under=80
- task: PublishTestResults@2
  condition: succeededOrFailed()
  inputs: { testResultsFormat: JUnit, testResultsFiles: '$(Build.ArtifactStagingDirectory)/test-results.xml' }
- task: PublishCodeCoverageResults@2
  condition: succeededOrFailed()
  inputs:
    summaryFileLocation: '$(Build.ArtifactStagingDirectory)/coverage.xml'
    pathToSources: '$(Build.SourcesDirectory)'
    failIfCoverageEmpty: true
# azurepipelines-coverage.yml → coverage.status.diff.target: 80% (default 70%), comments: on
# status name: {pipeline}/codecoverage → set Status checks in branch policy to Required

Integrated lab + final quiz

Create a shared template repo for myapp (build/deploy templates + required extends), multi-stage dev→prod canary deployment, publish the Python package to Azure Artifacts, and a coverage gate
Post-lesson ≈ 45 minutesIntegrates all modules
Scenario Platform team requirement: myapp's pipeline must extend the platform template v2.0.0; production service connections and myapp-prod environments enforce Required template; each merge to main generates a unique SemVer, with images, packages, build numbers and Git tags consistent; PRs must pass tests and have overall coverage ≥ 80%; dev deploys automatically, and prod, after approval, is released as a 10% → 50% → 100% canary with automatic rollback on failure; after prod succeeds, myapp-core promote the package to @release and generate release notes.
Template repo structure (Modules 1, 3, 7)
pipeline-templates/
├── templates/
│   ├── secure-pipeline.yml          # extends skeleton: filter steps + call the build/deploy below
│   ├── jobs/build-python.yml        # GitVersion + pytest/coverage + package + image
│   └── stages/deploy-aca-canary.yml # Module 3 canary stage (includes rollback, promotion, tagging)
└── tests/template-smoke.yml         # template self-test pipeline (extends each template once)
parameters:
- name: app
  type: string
- name: devApp
  type: string
- name: coverageThreshold
  type: number
  default: 80
- name: increments
  type: object
  default: [10, 50]
- name: extraBuildSteps
  type: stepList
  default: []

stages:
- stage: Build
  jobs:
  - template: jobs/build-python.yml
    parameters:
      coverageThreshold: ${{ parameters.coverageThreshold }}
      extraSteps:
      - ${{ each step in parameters.extraBuildSteps }}:
        - ${{ each pair in step }}:
            ${{ if in(pair.key, 'script', 'powershell') }}:
              '${{ pair.key }} is not allowed by platform template': error
            ${{ else }}:
              ${{ pair.key }}: ${{ pair.value }}

- stage: Deploy_dev
  dependsOn: Build
  variables:
    semVer: $[ stageDependencies.Build.Build.outputs['ver.semVer'] ]
  jobs:
  - deployment: Deploy
    environment: myapp-dev
    pool: { vmImage: ubuntu-latest }
    strategy:
      runOnce:
        deploy:
          steps:
          - download: none
          - task: AzureCLI@2
            inputs:
              azureSubscription: sc-azure-myapp
              scriptType: bash
              scriptLocation: inlineScript
              inlineScript: az containerapp update -n ${{ parameters.devApp }} -g rg-ado-lab --image $(acr)/myapp:$(semVer)

- ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/main') }}:
  - template: stages/deploy-aca-canary.yml
    parameters:
      app: ${{ parameters.app }}
      environment: myapp-prod
      imageTag: $(semVer)
      increments: ${{ parameters.increments }}

${{ if eq(variables['Build.SourceBranch'], …) }} Trimmed at compile time: the final plan for PR and feature branches contains no prod stage at all. The canary template needs two small changes: add to the stage dependsOn: [Build, Deploy_dev] and define at the stage level semVer variable mapping (same as Deploy_dev),on.success and add the Module 4 promotion PATCH and Module 5 tagging steps in

Build job template (Modules 4, 5, 7)
parameters:
- name: coverageThreshold
  type: number
- name: extraSteps
  type: stepList
  default: []
jobs:
- job: Build
  pool: { vmImage: ubuntu-latest }
  steps:
  - checkout: self
    fetchDepth: 0
  - task: gitversion-setup@4
    inputs: { versionSpec: '6.8.x' }
  - task: gitversion-execute@4
    inputs: { buildNumberFormat: '${GitVersion_SemVer}' }
  - bash: echo "##vso[task.setvariable variable=semVer;isOutput=true]$(GitVersion_SemVer)"
    name: ver
  - task: UsePythonVersion@0
    inputs: { versionSpec: '3.12' }
  - task: PipAuthenticate@1
    inputs: { artifactFeeds: myapp-lab/myapp-feed }
  - bash: |
      pip install -r requirements.txt pytest pytest-cov build twine
      pytest tests --junitxml=$(Build.ArtifactStagingDirectory)/test-results.xml \
        --cov=app --cov-report=xml:$(Build.ArtifactStagingDirectory)/coverage.xml \
        --cov-fail-under=${{ parameters.coverageThreshold }}
    displayName: Test (coverage ≥ ${{ parameters.coverageThreshold }}%)
  - ${{ each s in parameters.extraSteps }}:
    - ${{ s }}
  - task: PublishTestResults@2
    condition: succeededOrFailed()
    inputs: { testResultsFormat: JUnit, testResultsFiles: '$(Build.ArtifactStagingDirectory)/test-results.xml' }
  - task: UseDotNet@2
    condition: succeededOrFailed()
    inputs: { packageType: sdk, version: 8.x }
  - task: PublishCodeCoverageResults@2
    condition: succeededOrFailed()
    inputs:
      summaryFileLocation: '$(Build.ArtifactStagingDirectory)/coverage.xml'
      pathToSources: '$(Build.SourcesDirectory)'
      failIfCoverageEmpty: true
  - bash: |
      sed -i "s/^version = .*/version = \"$(GitVersion_SemVer)\"/" pyproject.toml
      python -m build
    displayName: Build package
  - task: TwineAuthenticate@1
    inputs: { artifactFeed: myapp-lab/myapp-feed }
  - bash: python -m twine upload --skip-existing -r myapp-feed --config-file $(PYPIRC_PATH) dist/*
    condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))
  - task: AzureCLI@2
    condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))
    inputs:
      azureSubscription: sc-azure-myapp
      scriptType: bash
      scriptLocation: inlineScript
      inlineScript: az acr build -r ${ACR%%.*} -t myapp:$(GitVersion_SemVer) .
    env: { ACR: $(acr) }

Tagging v2.0.0: git tag v2.0.0 && git push origin v2.0.0. Note that Python package versions must comply with PEP 440: the version GitVersion generates on feature branches 1.5.0-login.1 gets normalized by setuptools to 1.5.0rc0… or causes an error — so uploads only happen on main (PRs and feature branches do not upload); if necessary, in GitVersion.yml set a compatible tag format for non-main branches.

myapp consumer YAML (Modules 1, 2)
trigger: [ main ]
pr: [ main ]
resources:
  repositories:
  - repository: templates
    type: git
    name: myapp-lab/pipeline-templates
    ref: refs/tags/v2.0.0
variables:
  acr: acrmyapp21877.azurecr.io
  acaDomain: purplesea-1a2b3c4d.canadacentral.azurecontainerapps.io
extends:
  template: templates/secure-pipeline.yml@templates
  parameters:
    app: myapp
    devApp: myapp-dev
    coverageThreshold: 80
    increments: [10, 50]
Server-side enforcement (Modules 1, 2, 7):
  • sc-azure-myapp and myapp-prod: Required template → pipeline-templates / refs/tags/v2.0.0 / templates/secure-pipeline.yml;
  • myapp-prod: Approval (Release Managers; cannot approve their own runs) + Branch control (refs/heads/main) + Exclusive lock;
  • main branch policy: build validation (required), status check myapp-ci/codecoverage (required), at least 1 reviewer; commit azurepipelines-coverage.yml to the repo root (target 80%).
End-to-end verification
# 1) open a PR: build + test + coverage; the final plan has no prod stage
az repos pr create --source-branch feature/version-endpoint --target-branch main --title "feat: version in healthz"
# 2) after merging: dev deploys automatically → prod waits for approval → canary 10/50/100
watch -n 5 'az containerapp ingress traffic show -n ca-myapp-prod -g rg-ado-lab -o table'
# 3) version consistency
V=$(git fetch --tags -q && git describe --tags --abbrev=0); echo $V
az containerapp show -n ca-myapp-prod -g rg-ado-lab --query "properties.template.containers[0].image" -o tsv
pip index versions myapp-core --index-url https://pkgs.dev.azure.com/<org>/myapp-lab/_packaging/myapp-feed@release/pypi/simple/
v1.5.0
acrmyapp21877.azurecr.io/myapp:1.5.0
myapp-core (1.5.0)
Available versions: 1.5.0, 1.4.8
Failure drills (Modules 1, 3): ① in myapp, delete extends and write the deployment job directly → prod is blocked by Required template; ② make /healthz return 500 → the canary rolls back at 10%, and traffic returns 100% to the old revision; ③ change a test to fail → the PR cannot be completed. Restore after each drill.
Cleanup: Use Module 8 Option A (kept for Lesson 6) or Option B; record this run's build number, tags, and package version as acceptance evidence.
Acceptance checklist

Open-ended self-check (answer on your own first, then expand the reference answer)

1. From commit to the prod stage, when do templates and checks each take effect?

At run start, the template repository is resolved (only once) → at compile time, templates are loaded and expanded (parameter validation, each/if, limit checks) → the final plan is generated (recording the extends source) → before each stage starts, checks run on the protected resources it uses (static checks including Required template → pre-approval → dynamic checks → post-approval → exclusive lock) → at runtime, expressions are evaluated and jobs execute.

2. Why can neither condition nor ManualValidation replace environment approval?

Both are written in YAML, so anyone who can edit the pipeline can delete them; environment approval is a check configured server-side by the resource owner, which YAML cannot modify or skip, and it has an audit trail.

3. In the canary strategy, why should the deploy hook be idempotent?

deploy, routeTraffic, and postRouteTraffic run on every iteration per increments; if deploy creates a new revision each time, it produces multiple new versions. It should check whether the target revision already exists, create it only the first time, and have later iterations only adjust the weights.

4. How do views and retention policies work together?

Large numbers of prerelease versions produced by CI stay in @local and are cleaned up automatically by the retention policy (max versions + days since last download; both must be met to delete); validated versions are promoted to @prerelease/@release, and packages in views are exempt from the retention policy; consumers connecting to the @release view see only release versions.

5. What are the three things most easily missed when migrating classic releases to YAML?

① Post-deployment approval (YAML checks all run before the stage, so you need ManualValidation or an extra stage); ② the scheduled trigger time zone (YAML uses UTC); ③ Release.* predefined variables and stage-scoped variables. Also, classic releases cannot be exported to YAML, so tasks must be rewritten one by one.

6. Design a coverage gate that is practical for a legacy project.

Set the overall threshold to the current value to prevent regression (within the build --cov-fail-under), use the diff coverage status for PRs (target 80%) and set it as required in branch policy; keep PR file counts within 100; keep only one coverage policy; use PublishCodeCoverageResults@2; raise the overall threshold each quarter.

Final quiz (12 questions, covering all modules)

Sources and version notes

Verification sources for all technical facts in this lesson (verified on 2026-11-15)
TopicVerified findingSource (accessed 2026-11-15)
Template types and limitsincludes vs extends; up to 100 YAML files, 100 levels of nesting, 20 MB parse memory (about 600 KB–2 MB of YAML on disk); when ref is omitted, the default is refs/heads/main; can be pinned to a 40-character SHA; repository resources are resolved only once at run start; scripts in the template repo cannot be used directly; @selfUse YAML templates (2026-06-17)
Parameter typesstring, stringList (cannot be used for templates), number, boolean, object, step, stepList, job, jobList, deployment, deploymentList, stage, stageList; templateContext can be used with jobList/deploymentList/stageList; default values must be literalsParameters and templateContext
Checks and approvalsChecks are not in YAML; the five-category order is: static (Branch control, Required template, Evaluate artifact) → pre-approval → dynamic → post-approval → exclusive lock; evaluation starts only after conditions are met; Required template fields (repository type, repository, Ref, path); lockBehavior runLatest (default)/sequential; a stage can be retried after an approval timeoutPipeline deployment approvals
ManualValidation@1Can only be used in YAML agentless jobs; inputs notifyUsers (required, can be an empty string), approvers, allowApproversToApproveTheirOwnRuns (default true for Services, false for Server), instructions, onTimeout (reject/resume, default reject); the timeout is the earlier of the task timeout and 30 days; job default timeout is 1 hourManualValidation@1 (2026-09-23)
Expressions and output variablescounter can only be used in variable definitions; it counts per pipeline, counts separately per prefix, and continues when switching back to an old prefix; pipeline.startTime default is UTC; syntax for dependencies and stageDependencies in each scenario; deployment job output variable keysExpressions (2026-01-09)
Deployment strategiesrunOnce/rolling/canary; hooks preDeploy, deploy, routeTraffic, postRouteTraffic, on.failure/success; deploy automatically downloads artifacts; rolling supports only VM resources, and retries redeploy all VMs; canary variables strategy.name/action/increment; output variable key format; “Job is pending” FAQDeployment jobs · canary schema
Azure Artifacts viewsDefault @local (default view), @prerelease, @release; can only publish to the base feed; views are read-only; to be used as an upstream by other feeds, it must be visible to the organization or Microsoft Entra ID; starting in 2027, public projects will automatically be converted to privateWhat are feed views? (2026-07-22)
Retention policies and storageBoth settings must be met before deletion; packages in views are exempt; downgrades are not supported; recycle bin 30 days; cleanup runs once daily; 2 GiB free per organization; version numbers are retained permanentlyDelete and recover packages (2026-07-09)
Publish Python packagesTwineAuthenticate@1 (artifactFeed: project/feed; for an organization feed, write only the feed),$(PYPIRC_PATH) repeated runs append; both build identities need Feed Publisher (Contributor)Publish Python packages
Classic pipelinesOnly classic builds can be exported to YAML; classic releases are not supported; YAML schedules use UTC; since Sprint 226, new organizations have creation of classic build/release pipelines disabled by default, which does not automatically apply to existing organizations; once enabled, you cannot create new classic builds, releases, task groups, or deployment groups, but existing ones can still be edited and runMigrate Classic to YAML (2026-02-06) · Pipeline security approach · DevOps Blog 2023-01-24
CoveragePublishCodeCoverageResults@2 inputs summaryFileLocation/pathToSources/failIfCoverageEmpty; build pipelines only; recommend running UseDotNet first; diff coverage default 70%; azurepipelines-coverage.yml; status name {pipeline}/codecoverage; shown only after a multi-stage pipeline completes; 10 GB attachment limit; PRs > 100 files get stuck; Azure Repos onlyPublishCodeCoverageResults@2 (2026-09-23) · Review code coverage (2026-08-20)
GitVersionGitTools/actions v4.7.0 (2026-07-03), task gitversion-setup/gitversion-execute; GitVersion 6.8.2 (2026-07-10); requires fetchDepth: 0; output $(GitVersion_SemVer) and $(<step>.semVer)GitTools/actions releases · Azure examples · GitVersion releases

Video verification notes

The following videos were checked on 2026-11-15 via the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json) to verify titles and channels: CoderDave “Templates in Azure Pipelines: What, Why, and How” (UQlRITs7veM); Houssem Dellai “Templates in Azure DevOps Yaml Pipelines” (US_e31hZiWk); The Journey of DevOps “Build Your First Multi-Stage YAML Pipeline in Azure DevOps” (qmjTLNp-p5c); Julie Ng “(Simple?) Real World Azure Pipelines YAML Walkthrough” (e0bF1LlclEs); Skilltech Club “Azure Pipelines Deployment Strategies Explained | Blue-Green, Canary | AZ-400 DevOps Engineer” (uzlr9HC0Fuo); An IT Professional “Canary Deployment in Azure DevOps | Azure DevOps Interview Questions” (HS_2DmysOW0) and “Migrate Classic pipeline to YAML pipeline” (mGVFJqWxtQ8); Microsoft Azure “How to create, host, and share packages with Azure Artifacts | Azure Tips and Tricks” (xHNXwqxV7Uc); Microsoft Visual Studio “Getting started with package management using Azure Artifacts” (b3BPkyikvNM) and “Building and Deploying your Code with Azure Pipelines” (NuYDAs3kNV8); Gavin Greenwood “Auto Version Bumping and Deployments (SemVer, GitFlow, GitVersion, CI&CD)” (92EJlmyA3_k); Azure DevOps TV “Az400 v8 - GitVERSION …” (zTAHJ_H9J_M); Microsoft DevRadio “Migrating Classic Azure DevOps Pipelines to YAML with Manual Approvals” (mddbdvcZkYw); Bogdan Bujdea “Azure DevOps: Adding unit tests and code coverage to YAML pipelines” (bGV7SWySK04); LazyDevCoder “Add Unit Tests & Code Coverage to Azure Pipelines | Full Guide” (hIsUeMwF1w4). oEmbed does not return duration or publish date, so durations are not shown on the cards; all videos are in English, and some were recorded earlier, so task versions and limits follow this lesson and the official docs.

Audio narration notes

The “Audio” page uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time, with English terms pronounced in en-US. Results depend on the voices installed on the operating system. The course generation environment cannot call a TTS service, so no MP3 is embedded; for offline audio, the narration script can be passed to a service such as Azure AI Speech to generate it.

Known limitations and conservative handling

  • The official docs do not explicitly describe the full behavior of the canary strategy on “no-resource environments” (examples are based on Kubernetes resources); this lesson's lab depends only on hook iteration and strategy.increment, with traffic controlled by the Container Apps API, and provides a fallback approach.
  • The official coverage page is inconsistent about “which formats PR diff coverage supports”, so this lesson uses an in-build threshold for Python (--cov-fail-under) as the reliably effective gate.
  • As of the verification date, no official date for classic releases being shut down was found, so this lesson only states that “creation is disabled by default for new organizations.”
  • az artifacts feed create Availability depends on the extension version; for creating environments and feeds, follow the portal. The REST promotion path and generalsettings field names should be checked against the REST documentation.
  • GitVersion 6's workflow preset names and buildNumberFormat syntax should follow the current versions of the gitversion.net and GitTools documentation.
  • Run IDs, revision names, domain names, version numbers, and timestamps in “expected output” are sample values; prices are illustrative, see the Azure pricing page; timing in the animations is a schematic of the mechanism.
  • Some defaults and feature availability differ in Azure DevOps Server (on-premises); this lesson follows Azure DevOps Services.