Azure DevOps Hour 5: Production-Grade Pipelines
- 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 aresources.repositories+refpinned 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 (dependenciesandstageDependenciestwo 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
| # | Time | Module | Core content | Animation / interaction | Lab (project myapp-lab) |
|---|---|---|---|---|---|
| 0 | Before class | Prep: shared template repo | Reuse the service connection and Container Apps from Lesson 3, and create a new pipeline-templates repo and Artifacts feed | Production readiness self-assessment | Two repos + one feed + two environments |
| 1 | 00–08 | Template deep dive | includes vs extends, parameter types and validation, cross-repo templates and ref pinning, each/if, template limits, Required template checks | Core animation: extends expansion and protected resource checks | Build template + required extends |
| 2 | 08–15 | Multi-stage and environment promotion | stage dependency graph, conditions, ManualValidation, cross-stage output variables, lockBehavior | Dependency graph and condition evaluation simulator | dev → prod promotion |
| 3 | 15–22 | Deployment strategies | deployment job, runOnce/rolling/canary, hook order, output variable naming | Canary hook timeline (failures can be injected) | Container Apps 10% → 50% → 100% |
| 4 | 22–30 | Azure Artifacts | Feeds and scopes, upstream sources, views, retention policies, 5 package types and authentication tasks, 2 GiB free storage | Package resolution: local → upstream → save | Publish the myapp Python package and promote it to @release |
| 5 | 30–36 | Version numbers, tags, and release notes | Build number format, counter, GitVersion 6, Git tags, release notes automation | Counter calculator | Automatic versioning + tagging |
| 6 | 36–43 | Migrating classic releases to YAML | Concept mapping, Export to YAML limitations, migration path, new organizations have classic pipelines disabled by default | Classic → YAML mapping card | Rewrite a classic release as YAML |
| 7 | 43–52 | Tests, code coverage, and quality gates | PublishTestResults@2, PublishCodeCoverageResults@2, diff coverage and PR status, branch policies, Test Plans | Quality gate evaluator | pytest + coverage gate |
| 8 | 52–60 | Recap, self-check, and cleanup | Knowledge map for the first five hours, troubleshooting tree, costs, and cleanup | Interactive troubleshooting tree | Clean up resources |
| — | After class | Cheat sheet · Capstone lab | Shared template repo + required extends + dev→prod canary + Python package + coverage gate | Final quiz, 12 questions | Capstone lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key syntax / commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Write reusable templates (parameters, each/if) | ✓ | ✓ | ✓ | · | · | ✓ | · | ✓ | template:,parameters:,${{ each }} | M1 lab |
| Enforce compliance with extends + Required template | ✓ | · | · | · | · | · | · | ✓ | extends:, Approvals and checks | Required template |
| Multi-stage promotion and manual approval | · | ✓ | ✓ | · | · | ✓ | · | · | dependsOn,ManualValidation@1 | dev→prod |
| Pass output variables across jobs / stages | · | ✓ | ✓ | · | ✓ | · | · | ✓ | isOutput=true,stageDependencies | Passing image tags |
| Deployment strategies and rollback hooks | · | · | ✓ | · | · | ✓ | · | · | strategy: canary,on.failure | Container Apps canary |
| Package management and upstream sources | · | · | · | ✓ | ✓ | · | · | ✓ | TwineAuthenticate@1,PipAuthenticate@1 | Python packages |
| Semantic versions and release notes | · | · | · | ✓ | ✓ | · | · | · | name:,counter(), GitVersion | automatic tagging |
| Classic → YAML migration | · | ✓ | · | · | · | ✓ | · | · | Export to YAML, environments | Rewrite a classic release |
| Tests, coverage, and quality gates | · | · | · | · | · | · | ✓ | ✓ | PublishTestResults@2,azurepipelines-coverage.yml | coverage gate |
Topics not covered in this lesson (and where to learn them)
| Topic | Why it is not in this lesson | Where to learn it |
|---|---|---|
| YAML basics, triggers, variables, pipeline artifacts | Covered in Lesson 2; used directly in this lesson | Hour 2 |
| Workload identity federation service connections, Environments approvals, deploying to Container Apps/AKS | Built in Lesson 3; reused in this lesson | Hour 3 |
| Enforcing templates at organization scale, protected resource governance, Key Vault variable groups, GHAzDO | Belongs to the security and governance topic; this lesson only covers Required template on a single service connection | Hour 6 |
| Agent performance, caching deep dive, Managed DevOps Pools | Belongs to the performance and troubleshooting topic | Hour 7 |
| Packaging and OCI publishing of Helm charts | Covered in the Helm course | Helm 8-hour course |
How to use this courseware
Theory · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · narration · video. Start with “Theory” and the Module 1 core animation, then do the “Lab.”
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).
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.
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)
- CompletedLesson 2(the myapp repo has a working
azure-pipelines.yml) andLesson 3(resource grouprg-ado-lab, regioncanadacentral, ACR, Container Apps environment and appca-myapp-dev/ca-myapp-prod, ARM service connectionsc-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-poolinstead; in the YAML below, make the matching change at thepoollocation(s) accordingly). - Local machine: Azure CLI 2.6x+ and the
azure-devopsextension, 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).
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" ]
az 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.
Module 1 · Template deep dive: includes, extends, and parameters
- 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), usevalues:for enum validation, and understand that scalars without a declared type are treated as strings. - Put templates in a separate repo, use
resources.repositoriesto reference them, and useref: refs/tags/vX.Y.Zor a 40-character SHA to pin the version; know that when no ref is given, the default isrefs/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.
What: two kinds of templates
- Includes template (insertion):
- template: steps/build.ymlWritten in thesteps/jobs/stages/variableslist; template content is inserted as-is at the point of reference, similar to a programming language's#includeinclude. 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 rejectsCmdLine@2andscript).
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)
- Resolve repository resources: resolved only once at the start of the run
resources.repositories, after which the entire run uses the same commit. - Compile-time expansion: read the entry-point YAML and
template:andextends:recursively load files, substituteparameters, and evaluate all${{ }}(compile-time expressions, which can see parameters and static variables but not runtime variables), and expandeach, and pruneif. - 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).
- 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).
- 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.
- 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)
| Type | Description | Typical use |
|---|---|---|
string / number / boolean | number Usable values: Restricted values; boolean can only be true/false | Image names, replica counts, switches |
object | Any YAML structure | Environment lists, key-value maps; in templates, replaces stringList |
step / stepList | a single step / step sequence | Lets consumers insert custom build steps |
job / jobList,deployment / deploymentList,stage / stageList | Structured type, validated against the YAML schema; jobList/deploymentList/stageList can take templateContext | an extends template receives the consumer's job/stage and wraps pre- and post-steps |
stringList | Multi-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
| Scenario | Recommendation | Reason |
|---|---|---|
| Reusing a few steps (installing dependencies, running tests) | includes (steps template) | Simple, non-intrusive |
| Standardizing multi-environment deployment stages | includes (stage template + parameters) | Instantiating dev/test/prod from the same template |
| Must guarantee scanning, signing, and use of only approved tasks | extends + Required template checks | The template controls the structure, checks run server-side, and YAML edits cannot override them |
| Centralizing variable definitions | variables template | A variables template can contain only variables |
Comparison with similar technologies
| Azure Pipelines template | GitHub Actions | GitLab CI | |
|---|---|---|---|
| Reuse steps | steps template | composite action | include: + !reference |
| Reuse an entire pipeline | extends template | reusable workflow (workflow_call) | include: + extends: |
| Server-side enforcement | Required template checks (resource-level) | Organization rulesets with required workflows | Compliance pipelines (paid) |
| Version pinning | ref: Tag / branch / SHA | @v1 / SHA | ref: |
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
Flowchart: structural differences between includes and extends
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.
Core syntax and commands
| Syntax / command | Purpose | Notes |
|---|---|---|
- template: path.yml + parameters: | Insert steps/jobs/stages/variables template | A 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 skeleton | A pipeline has only one extends |
resources.repositories[].ref | Pin the template version | refs/tags/v1.2.0,refs/heads/release or a 40-character SHA; if omitted, it defaults to refs/heads/main |
@self | Reference the consumer repo's files in an extends template | e.g. - template: BuildJobs.yml@self |
${{ each x in parameters.list }} | Compile-time loop | Iterates over object, stepList, and jobList; can also iterate over parameters itself (key-value pairs) |
${{ if }} / ${{ elseif }} / ${{ else }} | Compile-time conditional insertion | Can only be used at mapping or sequence key positions |
az pipelines run --parameters k=v | Start with runtime parameters | Type-validate parameter values |
| Run page ⋯ → Download full YAML | View the expanded final YAML | The 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)
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.
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.
- 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.
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.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.
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.
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 SHA2. 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 }}"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
Official documentation
- Use YAML templates for reusable and secure pipelines
- Parameters and templateContext
- Template expressions
- Use templates for security
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.
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.
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.
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.
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.
Module 2 · Multi-stage pipelines and environment promotion
- Use
dependsOnto build a stage dependency graph (fan-out/fan-in), knowing that by default each stage depends on the previous stage, anddependsOn: []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) andstageDependencies.<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.
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
- Dependencies satisfied:
dependsOnthe stages in it have all finished. If it is not written,dependsOnthe stage depends on the previous stage in the YAML. - Condition is true: the default is
condition: succeeded()—all dependencies succeeded or partially succeeded. It can be changed toand(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))which deploys prod only on main. - 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.
- Jobs queued: jobs within a stage are controlled by job-level
dependsOnsettings and run in parallel by default.
Comparison of the three gates
condition | Approval check on the environment | ManualValidation@1 | |
|---|---|---|---|
| Who defines it | YAML author | Resource administrator (portal) | YAML author |
| Can it be bypassed by editing YAML? | Yes | No | Yes |
| Pause location | No pause, skip directly | Before the stage starts | Agentless 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 timeout | Task timeoutInMinutes or 30 days, whichever is earlier,onTimeout: reject|resume |
| Use case | Branch/parameter filtering | Production compliance approval | Manual check of configuration before deployment, confirmation after migration scripts run |
Output variable syntax (most error-prone)
| Reference location | Syntax |
|---|---|
| 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 conditions | eq(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).
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
Sequence diagram: how output variables pass across stages
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.
Core syntax
| Syntax | Purpose | Notes |
|---|---|---|
dependsOn: [A, B] / dependsOn: [] | Declare dependencies / cancel implicit dependencies | Available for both stages and jobs |
condition: | Run condition | A custom condition replaces the default succeeded(), so you usually need to write and(succeeded(), …) |
pool: server | agentless job | ManualValidation, InvokeRESTAPI, Delay, and other server tasks |
lockBehavior: sequential | runLatest | Works with exclusive lock checks | Default runLatest: only the latest run gets the lock; older runs are canceled |
az pipelines runs show --id N | View run status | Combined with --open View the stage graph in the browser |
az pipelines run --branch main --parameters … | Manual trigger | Can 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)
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).
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
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
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.
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: resumeYou 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
Official documentation
- Add stages, dependencies, and conditions
- Pipeline deployment approvals (check categories and order)
- ManualValidation@1
- Expressions: dependencies
Video storyboard script (about 90 seconds)
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.
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.
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.
Module 3 · Deployment strategies: runOnce, rolling, canary
- 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
deployits 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
maxParallelbatch on each VM; canary'spreDeployexecutes once,deploy/routeTraffic/postRouteTrafficperincrementsiteration, and finally goes toon.successoron.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.
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). deployHooks automatically injectdownloadthe 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,postRouteTrafficcan be set topool: serverOnly waits and checks.
Lifecycle hooks
| Hook | Purpose | myapp example |
|---|---|---|
preDeploy | Initialize resources before deployment | Check that the image exists in ACR; database migration pre-check |
deploy | Deploy the app (the only hook that automatically downloads artifacts) | az containerapp update --revision-suffix Create a new revision |
routeTraffic | Direct traffic to the new version | az containerapp ingress traffic set --revision-weight |
postRouteTraffic | Observe health after the traffic switch | Loop requests /healthz, query error-rate alerts |
on: failure / on: success | Roll back, or clean up / notify | failure: send 100% of traffic back to the old revision; success: deactivate the old revision |
How: three strategies
| runOnce | rolling | canary | |
|---|---|---|---|
| Execution method | Each hook runs once, then on.success / on.failure | Generates a hook job for each VM in the environment; each batch contains maxParallel (number or percentage) of VMs | preDeploy runs once; deploy → routeTraffic → postRouteTraffic run per increments iteration; then on.success / on.failure |
| Supported targets | Any environment (including an empty environment with no resources) | VM resources only | The 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 variables | strategy.name | strategy.name | strategy.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 targets | increments 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 job | Argo Rollouts / Flagger | Container Apps revisions | |
|---|---|---|---|
| Control plane | Pipeline (push-based) | In-cluster controller (pull-based, GitOps) | Platform API |
| Traffic splitting | Implemented by calling tools in hooks | Native, combined with Ingress/service mesh | Native weights (--revision-weight) |
| Automated analysis | postRouteTraffic script / checks (Azure Monitor alerts) | AnalysisTemplate (Prometheus, etc.) | None (requires external judgment) |
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]
myapp's Container Apps canary architecture
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.
Core syntax and commands
| Syntax / command | Purpose | Description |
|---|---|---|
environment: name.resource | Specific resources deployed to the environment | Recorded in the resource-level deployment history; connection info for Kubernetes resources is inherited automatically |
environment: { name, resourceType: VirtualMachine, tags } | Target VMs for rolling | Filter VMs by tag |
workspace: { clean: all } | Clean up the deployment workspace on a self-hosted agent | — |
az containerapp revision set-mode --mode multiple | Enable multiple revisions | Prerequisite for canary |
az containerapp update --image … --revision-suffix r$(Build.BuildId) | Create a new revision | Suffix makes the revision name predictable |
az containerapp ingress traffic set --revision-weight A=90 B=10 | Set traffic weights | Also available latest=10 |
az containerapp revision deactivate --revision X | Deactivate old revisions | Clean 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)
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.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
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.
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).
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
/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.
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'] ]
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
Official docs
Video storyboard (about 90 seconds)
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.
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.
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.
Module 4 · Azure Artifacts: feeds, upstreams and retention
- 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/@releasevia “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.
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 | |
|---|---|---|
| Visibility | Inherits project visibility and permissions | Visible within the organization, permissions managed separately |
| URL | pkgs.dev.azure.com/<org>/<project>/_packaging/<feed>/… | pkgs.dev.azure.com/<org>/_packaging/<feed>/… |
| Usage in tasks | artifactFeed: myapp-lab/myapp-feed | artifactFeed: myapp-feed |
| Notes | The official default when creating a feed is project scope | Use 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
@viewto the feed name, for example…/_packaging/myapp-feed@release/pypi/simple/. Consumers (downstream teams, or other feeds' upstreams) connect to@releasethe 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
| Ecosystem | Task | Mechanism | Publish command |
|---|---|---|---|
| npm | npmAuthenticate@0 | Publish to the specified .npmrc Inject token | npm publish |
| NuGet / dotnet | NuGetAuthenticate@1 | Configure Azure Artifacts credential provider | dotnet nuget push --source <feed-url> --api-key az |
| pip (install) | PipAuthenticate@1 | Set PIP_EXTRA_INDEX_URL (or PIP_INDEX_URL) | pip install |
| twine (publish) | TwineAuthenticate@1 | Generate .pypirc, with the path in $(PYPIRC_PATH); running it multiple times appends rather than overwrites | twine upload -r <feed> --config-file $(PYPIRC_PATH) dist/* |
| Maven / Gradle | MavenAuthenticate@0 | Write settings.xml 's server credentials | mvn deploy |
| Universal Packages | UniversalPackages@0 | Use the pipeline identity within the task | command: 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 Artifacts | GitHub Packages | JFrog Artifactory | |
|---|---|---|---|
| Public source proxy | Upstream sources (auto-save) | Limited (partially supported by npm, etc.) | Remote repository |
| Quality tiers | Views (promote) | No built-in support | Cross-feed promote / properties |
| Python | Supported | Not supported | Supported |
| Container images | Not supported (use ACR) | ghcr.io | Supported |
Package resolution and save flow
Lifecycle of myapp packages
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.
Core commands and tasks
| Command / task | Purpose | Notes |
|---|---|---|
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 feed | onlyAddExtraIndex: true as an extra index |
pip install keyring artifacts-keyring | Local interactive authentication | On first use, a browser / device code prompt appears |
az artifacts universal publish/download | Universal Packages | --organization --project --scope project --feed --name --version --path |
REST: PATCH …/_apis/packaging/feeds/{feed}/pypi/packages/{pkg}/versions/{ver} | Promote to view | body {"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)
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*"]
- 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/
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.
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
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).
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
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
Official docs
- What are feed views?
- Upstream sources
- Delete and recover packages (retention policy)
- Publish Python packages with Azure Pipelines
Video storyboard (about 90 seconds)
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.
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.
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.
Module 5 · Version numbers, tags and release notes
- 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).
What: four kinds of “versions” need to be aligned
| Carrier | Example | Determined by |
|---|---|---|
Run build number Build.BuildNumber | 1.4.7 or 20261115.4 | YAML top level name: (default $(Date:yyyyMMdd)$(Rev:.r)) |
| Package version | myapp-core 1.4.7, prerelease 1.5.0.dev3 | Pipeline writes to pyproject / csproj / package.json |
| Image tag | myapp:1.4.7 | az acr build -t |
| Git tag | v1.4.7 | Pushed 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 inname:; if other parts of the build number change (such as the date),Revrestart from 1.- Overriding at runtime:
echo "##vso[build.updatebuildnumber]1.4.7"(GitVersion'sbuildNumberFormatinput 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.startTimedefault 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) andGitVersion.ymlconfiguration, computingSemVer,FullSemVer,MajorMinorPatch, andPreReleaseTag, etc. - Using the Marketplace extension in Azure Pipelines GitTools two tasks:
gitversion-setup@4(install,versionSpec: '6.8.x') andgitversion-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, thegitversion/setup@0and@3syntax 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 removedNuGetVersionV2,LegacySemVerand 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
| Scheme | Pros | Cons | Suitable for |
|---|---|---|---|
| Date + Rev | Zero configuration | No semantics | Internal apps, images |
| Hand-written major.minor + counter | Simple, no external dependencies | Changing major/minor requires editing YAML | Small team libraries |
| GitVersion | Determined by Git history; branches automatically get prerelease tags | Requires a full clone; configuration learning curve | Externally published libraries, GitFlow / trunk-based mode |
$(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
counter count table
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
| Syntax | Purpose | Notes |
|---|---|---|
name: $(major).$(minor).$(patch) | Build number format | Reference variable; $(Rev:r) can only be used in name |
$[counter(prefix, seed)] | auto-increment counter | Can only be used in variable definitions |
##vso[build.updatebuildnumber]X | Change the build number at runtime | — |
##vso[build.addbuildtag]v1.4.7 | Tag run (not a Git tag) | Makes it easy to filter runs |
git tag -a v1.4.7 -m … && git push origin v1.4.7 | Push Git tag | Requires persistCredentials: true and the build identity's Contribute / Create tag permissions |
az repos pr list --status completed | Query completed PRs | Release 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)
myapp-lab Build Service (<org>): Contribute and Create tag set to Allow.$(GitVersion_SemVer); output variables for later stages to use:
- bash: echo "##vso[task.setvariable variable=semVer;isOutput=true]$(GitVersion_SemVer)" name: ver
on.success (or a separate job after prod), add the tagging and release-notes steps,semVer via stageDependencies.Build.Build.outputs['ver.semVer'] mapping.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.
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"
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
Official docs
- Configure run or build numbers
- Expressions: counter
- GitTools: Azure Pipelines usage example
- Logging commands
Video storyboard (about 75 seconds)
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.
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.
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.
Module 6 · Migrating classic releases to YAML
- 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.
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 release | YAML | Migration notes |
|---|---|---|
| Release pipeline | Multi-stage YAML (or a separate “release pipeline” + resources.pipelines) | Keep two pipelines if build and release cadences differ |
| Artifacts (build, ACR, GitHub…) + continuous deployment trigger | resources.pipelines / resources.containers / resources.repositories + trigger | Artifacts are obtained via download to get them |
| Stage (environment) | stage + deployment job + environment | Deployment history is recorded on the environment instead |
| Pre/Post-deployment approvals | Approval 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 hours | Work item query gate must be changed to a REST check |
| Deployment group | VirtualMachine resources in the environment + rolling strategy | Re-register the environment agent on the target machines |
| Agentless phase | pool: server job | — |
| Task group | steps / jobs templates | Parameters changed to typed template parameters |
| Release variables / variable groups / scoped variables | variables (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 version | Rerun the stage of an old run (Rerun) or manually run a specified resource version | Keep old runs (retention policy) |
How: migration path
- Inventory: use REST/CLI to list classic release definitions, stages, tasks, variables and approvals (commands are paginated).
- 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.
- 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.
- Environments and checks: create an Environment for each stage; migrate approvals and gates to checks; add Required template to the production service connection.
- 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.
- 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.
Structure comparison: classic release → YAML
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”.
Inventory and migration commands
| Command | Purpose | Notes |
|---|---|---|
az pipelines release definition list -o table | List classic release definitions | Requires the azure-devops extension |
az pipelines release definition show --id N | View definition JSON (stages, tasks, approvals) | Good for scripted inventory |
az pipelines release list --definition-id N --top 5 | Recent releases | Confirm whether still in use |
REST GET vsrm.dev.azure.com/{org}/{project}/_apis/release/definitions?$expand=environments | Full export | Note: the hostname is vsrm |
REST PATCH …/_apis/build/generalsettings | Project-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)
{
"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" }] }] }
]
}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 }}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).
myapp-prod , confirm the Approval (Release Managers), and add a new Query Azure Monitor alerts check (choose the subscription, resource group and alert rule).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.
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"
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
Official docs
- Migrate your Classic pipeline to YAML
- Pipeline security approach (creation of classic pipelines disabled by default since Sprint 226)
- Resources in YAML pipelines
Video storyboard (about 75 seconds)
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.
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.
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.
Module 7 · Tests, code coverage and quality gates
- Use
PublishTestResults@2Publish JUnit/NUnit/xUnit/VSTest(TRX)/CTest results, and understandfailTaskOnFailedTests,condition: succeededOrFailed()and flaky test rerun analysis. - Use
PublishCodeCoverageResults@2(inputssummaryFileLocation,pathToSources, andfailIfCoverageEmpty) 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.ymlso that PRs show diff coverage status, and in branch policies set the status{pipeline-name}/codecoverageto 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.
What: three types of quality signals
| Signal | Source task | Where to view | Can block merge? |
|---|---|---|---|
| Test results | PublishTestResults@2 (or built-in publishing in VSTest/DotNetCoreCLI) | Run page Tests tab, Test Analytics | Test failure → task fails → build validation policy fails → blocks |
| Coverage | PublishCodeCoverageResults@2 | Code 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 status | The platform calculates coverage for changed lines in the PR based on published coverage | PR status area + optional file-level comments | Suggest 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@2first (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
- 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%).
- The repo root's
azurepipelines-coverage.ymlcan change the target and whether to publish file-level comments (comments: on). It belongs to the repository rather than a specific pipeline. - 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. - 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.
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
| Layer | Mechanism | Best for |
|---|---|---|
| 1 Within the build | test failures,--cov-fail-under | hard minimum, runs on all branches |
| 2 PR status | diff coverage, SonarQube and other external statuses | focus on quality of “new code” |
| 3 Branch policy | build validation + required status + reviewers | make 1 and 2 prerequisites for merging |
| 4 Before release | Environment check (Invoke REST API to query the quality platform) | final gate before deployment |
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
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.
--cov-fail-under=80)Core tasks and configuration
| Task / file | Key inputs | Notes |
|---|---|---|
PublishTestResults@2 | testResultsFormat (JUnit/NUnit/VSTest/XUnit/CTest),testResultsFiles,failTaskOnFailedTests,testRunTitle | Set condition: succeededOrFailed(), so results are published even when tests fail |
PublishCodeCoverageResults@2 | summaryFileLocation,pathToSources,failIfCoverageEmpty | build pipelines only |
azurepipelines-coverage.yml | coverage.status.comments,coverage.status.diff.target | repo root; the file name must match exactly |
az repos policy build create | Build validation policy | see below |
In the portal: Branch policies → Status checks (the CLI can use the generic az repos policy create --policy-configuration <json>) | Required status | Status 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)
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.
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.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 =========================
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.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.
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: true2. Write the configuration file that sets the PR diff coverage target to 85% and enables comments.
coverage:
status:
comments: on
diff:
target: 85%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
Official documentation
- PublishCodeCoverageResults@2
- Review and configure code coverage results (diff coverage, policies)
- PublishTestResults@2
- What is Azure Test Plans?
Video storyboard script (about 75 seconds)
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.
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.
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.
Module 8 · First five hours recap, self-check, and cleanup
- 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).
First five hours knowledge map
| Lesson | Core skills | How it is used in this lesson |
|---|---|---|
| Lesson 1: Platform and collaboration | Organizations, projects, security groups, Boards, Repos branch policies, CLI/REST | Branch policies carry the coverage gate; Build Service identity authorization |
| Lesson 2: Azure Pipelines | YAML structure, triggers, agents, variables, artifacts, template basics | Deeper templates, counter, output variables |
| Lesson 3: Azure CD | WIF service connections, Environments, Container Apps, IaC | canary deployment targets, Required template added to the service connection |
| Lesson 4: AWS CD | OIDC, ECR, ECS, multi-account promotion | The 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
- Pipelines extend platform templates; pin the template repo ref to a tag or SHA.
- Production service connections and production environments have Required template + Approval + Branch control.
- The prod stage condition is limited to main and non-PR.
- Build once, deploy many: images/packages are built only once; tags are passed via output variables.
- Deploy using deployment jobs (which keep deployment history); rollback logic lives in on.failure and has been rehearsed.
- Exclusive lock + lockBehavior prevents concurrent deployments.
- Dependencies come only from internal feeds, with public sources as upstream; release packages are promoted to @release.
- Version numbers are unique and carried through build number, packages, images and Git tags.
- Publish test results and coverage; thresholds fail within the build; PR status and build validation are required policies.
- Do not create new classic pipelines (the organization switch is turned on).
Lesson resource costs (canadacentral, illustrative)
| Resource | Billing model | Usage and estimate for this lesson |
|---|---|---|
| Container Apps (myapp, myapp-dev) | Billed per vCPU-second/GiB-second + requests, with a monthly free grant | With minimum replicas at 0, idle cost is nearly 0; a few cents during the lab |
| ACR Basic | Billed per day | About US$0.17/day (Basic SKU; see the pricing page) |
| Azure Artifacts | 2 GiB free per organization | This lesson's package is a few dozen KB, free |
| Microsoft-hosted agent | Free-tier parallel jobs (requires a request) or purchase | This lesson uses about 30–60 minutes of build time |
| Test Plans | Per user access level | Optional; 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
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
| Command | Purpose |
|---|---|
az pipelines runs list --top 10 -o table | Review this lesson's runs |
az containerapp update -n ca-myapp-prod -g rg-ado-lab --min-replicas 0 | Keep 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-wait | Fully delete Azure resources (once Lessons 6 and 7 no longer need them) |
az devops service-endpoint delete --id <id> --yes | Delete 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)
/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.curl -s https://myapp.$ACA_DOMAIN/healthz git fetch --tags && git describe --tags --abbrev=0
{"status":"ok","version":"1.4.8"}
v1.4.8sc-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.
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 table2. 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 tableOn 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
Official documentation
Video storyboard script (about 60 seconds)
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.
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.
Command cheat sheet
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 lockDeployment 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 RequiredIntegrated lab + final quiz
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.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
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.
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]sc-azure-myappandmyapp-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; commitazurepipelines-coverage.ymlto the repo root (target 80%).
# 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
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.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
| Topic | Verified finding | Source (accessed 2026-11-15) |
|---|---|---|
| Template types and limits | includes 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; @self | Use YAML templates (2026-06-17) |
| Parameter types | string, 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 literals | Parameters and templateContext |
| Checks and approvals | Checks 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 timeout | Pipeline deployment approvals |
| ManualValidation@1 | Can 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 hour | ManualValidation@1 (2026-09-23) |
| Expressions and output variables | counter 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 keys | Expressions (2026-01-09) |
| Deployment strategies | runOnce/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” FAQ | Deployment jobs · canary schema |
| Azure Artifacts views | Default @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 private | What are feed views? (2026-07-22) |
| Retention policies and storage | Both 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 permanently | Delete and recover packages (2026-07-09) |
| Publish Python packages | TwineAuthenticate@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 pipelines | Only 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 run | Migrate Classic to YAML (2026-02-06) · Pipeline security approach · DevOps Blog 2023-01-24 |
| Coverage | PublishCodeCoverageResults@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 only | PublishCodeCoverageResults@2 (2026-09-23) · Review code coverage (2026-08-20) |
| GitVersion | GitTools/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 createAvailability depends on the extension version; for creating environments and feeds, follow the portal. The REST promotion path andgeneralsettingsfield names should be checked against the REST documentation.- GitVersion 6's
workflowpreset names andbuildNumberFormatsyntax 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.