Azure DevOps Hour 2: Azure Pipelines Core

From “click Run” to “understanding every step of a run”: YAML structure, triggers, agents, variables, artifacts and caching, templates, and finally a CI pipeline for myapp that can block bad PRs
Azure Pipelines YAMLubuntu-latest = Ubuntu 24.04Cache@2 · PublishPipelineArtifact@1Verified against learn.microsoft.com · 2026-11-15
Overall learning objectives
  • Explain the full lifecycle of a pipeline run: Trigger → expand templates and evaluate template expressions (compile time) → authorize resources → jobs queue for parallel jobs → agent picks up the job → download tasks and run steps one by one → upload logs/artifacts → write status back to the PR, and use that to work out “where it is stuck.”
  • Read and write multi-stage YAML: stages/jobs/steps,dependsOn and condition,task and script,checkout default shallow-clone depth (in some organizations, new pipelines set fetchDepth to 1).
  • Configure the four trigger types correctly: CI trigger (branch/path/tag filters), PR (Azure Repos uses branch policy build validation, GitHub uses pr:),schedules (cron,UTC),resources.pipelines pipeline completion triggers.
  • Choose the right agent for a job: Microsoft-hosted image labels (ubuntu-latest/ubuntu-24.04/ubuntu-26.04/windows-latest/macOS-latest), free-tier quota,demands and capabilities, and when to use self-hosted agents.
  • Master the three variable syntaxes $(var) / ${{ }} / $[ ] and their evaluation timing; use variable groups, secret variables, output variables across jobs and stages, and predefined variables.
  • Use pipeline artifacts to pass outputs between jobs, and use Cache@2 to speed up dependency installs, and design cache keys that neither never hit nor never update.
  • Write step and job templates and declare typed parameters; understand the version rules for Marketplace tasks; finally complete a CI readiness review and use the troubleshooting tree to locate 10 common failure types.

1-hour time plan

#TimeModuleCore contentAnimation / interactionLab (project myapp-lab)
0Before classBridge and warm-upCommit myapp code to the repo, enable the free parallel job, first YAML (lint + pytest + docker build)Pipeline readiness self-checkFirst green run
100–07Architecture and how it worksYAML vs classic, compile/expand phase vs runtime phase, agent jobs / agentless jobs / deployment jobs, parallel jobs, timeouts and heartbeatsCore animation: the lifecycle of a run (3 failure types can be injected)Reading run logs and “downloading the expanded YAML”
207–15YAML structurestages/jobs/steps, dependsOn, condition, task vs script, checkout options, timeoutsDependency and condition simulatorRefactor into three stages: Lint/Test/Build
315–22TriggersCI trigger, implicit triggers, path filters, PR (build validation vs pr:), schedules (UTC), pipeline resources“Will this push trigger a run?” checkerPath filters + nightly build + downstream pipeline
422–29Agents and agent poolsHosted image labels and hardware, free tier, demands/capabilities, self-hosted agents, container jobsAgent matching and queueing simulatorMulti-OS jobs + self-hosted agent (optional)
529–37Variables and expressionsMacro / template / runtime expressions, variable groups, secrets, output variables across jobs and stages, predefined variables, runtime parametersTimeline of the three syntaxes' evaluationImage tag variable + passing values across stages
637–44Artifacts and cachingPublishPipelineArtifact/DownloadPipelineArtifact, publish/download shorthand, Cache@2 key and scopeCache key hit simulatorpip cache + image artifact passing
744–51Template basics and tasksstep/job/variable templates, parameter types, each/if, template repositories, Marketplace tasks and versionsTemplate expanderExtract the python-ci template
851–60CI readiness review and common failuresReview checklist, 10 common failure types and diagnosisFailure replay + interactive troubleshooting treeDeliberately trigger 4 failures and fix them
—After classCheat sheet · Capstone labFull CI: multi-stage + matrix + Redis service container + caching + artifacts + PR build validationFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / keywordsLab
Explain the run lifecycle and why jobs queue✓··✓···✓az pipelines runs showM1 lab
Write multi-stage YAML, dependencies and conditions·✓··✓·✓·dependsOn,conditionthree-stage CI
Control checkout (shallow clone, tags, multiple repos)·✓·····✓checkout: self,fetchDepthM2 lab
Configure CI / PR / schedule / resource triggers··✓····✓trigger,pr,schedules,resourcesnightly build
Choose agents; understand parallel jobs and costs✓··✓···✓pool.vmImage,demandsmulti-OS jobs
Variables, secrets, output variables····✓·✓✓##vso[task.setvariable]passing values across stages
Artifact passing and dependency caching·····✓·✓publish,download,Cache@2pip cache
Template reuse and task versions······✓·template:,parameters,Task@Npython-ci template
PR quality gate (build validation)✓·✓····✓az repos policy build createCapstone lab

What this hour does not cover (and where to learn it)

TopicWhy it is not in this hourWhere to learn it
Service connections, workload identity federation, deploying to Azure, Environments approvals and checksThese belong to CD and cloud-platform topics; this hour covers CI only, with no image push and no cloud connectionLesson 3: Moving to the cloud platform (Azure)
Enforced extends templates, protected resource checks, deployment strategies (runOnce/rolling/canary), Azure Artifacts feedsRequires first mastering this hour's templates and deployment job basicsLesson 5: Production-grade pipelines
Managed DevOps Pools, VMSS agent scaling, agent performance tuningBelongs to platform operationsLesson 7
Git details in Azure Repos (clone authentication, Git-side behavior of branch policies)covered in the Git courseGit 8-hour course Lesson 3
GitHub Actions comparisonThis hour compares only where necessaryGitHub 8-hour course
Writing Dockerfiles and image optimizationThis hour reuses the myapp from the Docker course directlyDocker 8-hour course

How to use this courseware

10 pages per module
Theory · diagrams · animation · commands · lab · production case · troubleshooting · quiz · audio · video. Start with “Theory” and “Animation”, then do the “Lab”.
Progress
Progress counts once the quiz score is ≥ 70% or you click “Mark module complete”. It is saved in this browser (if local storage is blocked, it is cleared on refresh).
Chinese audio
The “Audio” page reads the script aloud with the browser's built-in Web Speech API (en-US); if no Chinese voice pack is installed, the script can still be read or passed to a TTS tool.
Version notes Azure DevOps Services is a continuously released SaaS with no “version number”. All behavior in this hour was checked against learn.microsoft.com on 2026-11-15: ubuntu-latest points to Ubuntu 24.04,ubuntu-26.04 reached GA on 2026-09-29,ubuntu-22.04 is deprecated and scheduled for removal on 2027-04-17; windows-latest is currently Windows Server 2025 + VS 2022; Microsoft has announced that “in the coming weeks” it will point to windows-2025-vs2026; macOS-latest is macOS 15. Free tier: 1 Microsoft-hosted parallel job for private projects (up to 1 hour per run, 1,800 minutes per month),takes effect automatically only after the organization is linked to a valid Azure subscription (set up billing); public projects have been retired (converted to private in 2027). Azure DevOps Server (on-premises) does not provide Microsoft-hosted agents.

Module 0 · Bridge and warm-up: create the first YAML pipeline for myapp

Push the Docker course's myapp into the myapp-lab project created in Lesson 1, and get lint + pytest + docker build running
Before class ≈ 12 minA free organization is enough
Prerequisites
  • CompletedLesson 1: organization https://dev.azure.com/<org>, project myapp-lab, and you are a member of Project Administrators; Azure CLI and the azure-devops extension are installed, and you have run az devops configure --defaults.
  • Your local machine or lab VM (Ubuntu 24.04) has Git, Python 3.13 and Docker Engine (from the Docker course environment).
  • parallel jobs: private projects need a Microsoft-hosted agent, so first open Organization settings → Billing and link an Azure subscription; the free tier (1 parallel job) takes effect automatically after that. Linking a subscription without buying extra parallel jobs costs nothing. Without an Azure subscription, useModule 4 's self-hosted agents (the free self-hosted tier of 1 parallel job is granted automatically).

Step 1: Confirm the environment from the previous lesson

az devops configure --list
az devops project show --project myapp-lab --query "{name:name, visibility:visibility, state:state}" -o table
az repos list --project myapp-lab --query "[].{name:name, defaultBranch:defaultBranch}" -o table
[defaults]
organization = https://dev.azure.com/contoso-lab
project = myapp-lab

Name       Visibility    State
---------  ------------  ----------
myapp-lab  private       wellFormed

Name       DefaultBranch
---------  ---------------
myapp-lab  refs/heads/main

Step 2: Create the myapp repo and add the code

myapp matches the Docker course: Flask + gunicorn + a Redis counter, listening on port 5000,/healthz and returns ok. This lesson only adds test and lint configuration.

az repos create --name myapp --project myapp-lab --query remoteUrl -o tsv
mkdir -p ~/adolab && cd ~/adolab
git clone https://dev.azure.com/<org>/myapp-lab/_git/myapp && cd myapp
mkdir -p tests

cat > app.py <<'EOF'
import os, socket
from flask import Flask
import redis

app = Flask(__name__)
r = redis.Redis(host=os.getenv("REDIS_HOST", "localhost"),
                port=int(os.getenv("REDIS_PORT", "6379")),
                socket_connect_timeout=2)

@app.get("/")
def index():
    try:
        hits = r.incr("hits")
    except redis.exceptions.ConnectionError:
        hits = "N/A (redis not connected)"
    return f"Hello from {socket.gethostname()}, hits={hits}\n"

@app.get("/healthz")
def healthz():
    return "ok"
EOF

cat > requirements.txt <<'EOF'
flask==3.1.*
redis==5.*
gunicorn==23.*
EOF

cat > requirements-dev.txt <<'EOF'
-r requirements.txt
pytest==8.*
ruff==0.*
EOF

cat > tests/test_app.py <<'EOF'
import os, pytest
from app import app

@pytest.fixture
def client():
    app.config["TESTING"] = True
    return app.test_client()

def test_healthz(client):
    resp = client.get("/healthz")
    assert resp.status_code == 200 and resp.data == b"ok"

@pytest.mark.skipif(not os.getenv("REDIS_HOST"), reason="Requires Redis (provided by the service container in CI)")
def test_hits_increment(client):
    a = client.get("/").data.decode()
    b = client.get("/").data.decode()
    assert "hits=" in a and a != b
EOF

cat > Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
RUN useradd -m appuser
USER appuser
EXPOSE 5000
CMD ["gunicorn", "-b", "0.0.0.0:5000", "app:app"]
EOF
printf '[pytest]\npythonpath = .\n' > pytest.ini      # lets tests/ import app.py from the root directory
printf '__pycache__\n.git\n.venv\ntests\n' > .dockerignore
printf '__pycache__/\n.venv/\n.pytest_cache/\ntest-results.xml\n' > .gitignore

Run it locally first:python3 -m venv .venv && . .venv/bin/activate && pip install -r requirements-dev.txt && ruff check . && pytest -q. Without Redis locally, the second test is skipped; this is expected.

Step 3: The first YAML pipeline

# myapp first CI: lint + pytest + docker build (single-job version; Module 2 splits it into stages)
trigger:
  branches:
    include: [ main ]

pool:
  vmImage: ubuntu-latest        # currently points to Ubuntu 24.04

steps:
- task: UsePythonVersion@0
  inputs:
    versionSpec: '3.13'
  displayName: Use Python 3.13

- script: |
    python -m pip install --upgrade pip
    pip install -r requirements-dev.txt
  displayName: Install dependencies

- script: ruff check .
  displayName: Lint (ruff)

- script: pytest -q --junitxml=test-results.xml
  displayName: Unit tests (pytest)

- task: PublishTestResults@2
  condition: succeededOrFailed()     # upload results even if tests fail
  inputs:
    testResultsFormat: JUnit
    testResultsFiles: test-results.xml
    testRunTitle: myapp-unit

- script: docker build -t myapp:$(Build.BuildId) .
  displayName: Build image (no push; pushing is in Lesson 3)
git add . && git commit -m "myapp + first pipeline" && git push -u origin main

az pipelines create --name myapp-ci --repository myapp --repository-type tfsgit \
  --branch main --yml-path azure-pipelines.yml --project myapp-lab
# This command immediately queues the first run; afterwards you can run it manually at any time:
az pipelines run --name myapp-ci --branch main --project myapp-lab --query "{id:id, status:status}" -o table
Id    Status
----  ----------
12    notStarted

# after about 1–2 minutes
$ az pipelines runs show --id 12 --query "{result:result, reason:reason, branch:sourceBranch}" -o table
Result     Reason    Branch
---------  --------  ---------------
succeeded  manual    refs/heads/main
First run stuck in the queue? If the run log shows No hosted parallelism has been purchased or granted (historically this message also included a request form link), the organization has no Microsoft-hosted free tier. Per current official documentation,the free tier takes effect automatically once an Azure subscription is linked (set up billing); until then, you can register a self-hosted agent and change pool to name: Default (Module 4). Seethe Module 8 troubleshooting tree.

Warm-up: answer from memory (30 seconds)

In Lesson 1, where did you configure the “branch policy”? How does it relate to this lesson?

Repos → Branches → target branch → Branch policies. In Module 3 of this lesson, you will add a main to it Build validation: PR triggers in Azure Repos work through this, and the YAML pr: has no effect on Azure Repos.

What is the project's “Build Service” identity?

Each project has one <Project name> Build Service (<org>) identity; the job access token used at pipeline runtime System.AccessToken represents it. A 403 or TF401027 error caused by insufficient permissions usually means this identity needs to be granted access (Module 8).

Pipeline readiness self-check (10 items)

Tick what myapp's CI has already achieved in this project (saved in this browser). Come back after finishing this lesson and the capstone lab and tick again.

Environment self-check checklist

Module 1 · Azure Pipelines architecture and how it works

00:00 – 07:00 · The server decides “what to run”, and agents do “the actual running”; a parallel job gate sits in between
7 minYAML firstClassic release: new features focus on YAML★★★★★
Learning objectives
  • Explain the difference between YAML pipelines and classic pipelines, and why new projects should choose YAML.
  • Restate a run in the official order: expand templates + evaluate template expressions → select stages → authorize resources → select jobs (expand matrices, evaluate conditions) → request agents → agent prepares and executes step by step → report results.
  • Distinguish agent jobs (agent job),agentless jobs (server/agentless job) and deployment jobs (deployment job), and know which ones consume parallel jobs.
Prerequisites: Lesson 1's organization, project and permissions, and the Docker course's image builds. Importance:★★★★★ (understand this module and every later troubleshooting step has a map)

What: what Azure Pipelines is made of

  • Pipeline: a definition; a YAML pipeline's definition is the azure-pipelines.yml in the repo (any file name).
  • Run: one execution of a pipeline. A run contains one or more stages, a stage contains jobs, a job contains steps; a step is either a script/bash/pwsh or a task.
  • Agent: the program that actually runs jobs (open source,microsoft/azure-pipelines-agent), running on Microsoft-hosted VMs, your own machines, VMSS or Managed DevOps Pools. An agent runs only one job at a time.
  • Parallel job: the organization-level “number of lanes”. With 1 parallel job, only one agent job can run across the whole organization at a time; the rest queue.

Why: why choose YAML rather than the classic editor

YAML pipelinesClassic build / release
Where definitions liveIn the same repo as the code, goes through PR review, has Git historyStored on the server, edited in the UI, history only on the server
Branch differencesEach branch can have its own YAML version (a run uses the YAML of the branch it runs on)All branches share one definition
Reuse and governanceTemplates (includes/extends), required template checksTask groups
CD capabilitiesMulti-stage + Environments + approvals and checks (Lessons 3 and 5)Classic release pipelines
New featuresMicrosoft's new features mainly land in YAML (e.g. cache scope, template expressions, protected resources)Maintenance only; some organizations can block creating classic pipelines in settings

How: the two main phases of a run

The official documentation (Pipeline runs) splits a run into server-side processing and agent execution parts:

PhaseWho does itWhat it doesWhat can be used at this point
Compile / expand (compile time)Azure Pipelines serviceTakes the YAML on the triggering branch,expands templates and evaluates template expressions ${{ }} to get a “final YAML”; then selects the first stage to run based on stage dependenciesOnly YAML text, parameters and a few predefined variables (such as Build.SourceBranch,Build.Reason). Runtime variables do not exist yet
Resource authorizationServiceBefore each stage starts, checks whether all resources used by that stage's jobs (service connections, agent pools, variable groups, secure files, environments, other repos) are authorized for this pipelineTherefore stage/job variables cannot be used to decide service connection or environment names
Job schedulingServiceSelects runnable jobs based on job dependencies; expands strategy: matrix/parallel into multiple runtime jobs; evaluates condition; requests an agent for each eligible job (after passing the parallel job gate)runtime expressions $[ ],dependencies
runtime (runtime)agentDownloads the tasks the job needs and caches them, creates the working directory,each step as its own process runs them in order; streams logs in real time, uploads the full log when each step ends, and uploads test results and artifactsMacros $(var) (replaced before the task runs), environment variables, logging commands ##vso[...]

Three job types

TypeYAMLWhere it runsUses a parallel job?Typical use
Agent job- job: + poolAgent (on a VM or in a container job)YesBuild, test, package
Agentless job (server job)- job: + pool: serverAzure Pipelines serverNoA few server-side tasks such as Delay, ManualValidation, InvokeRESTAPI, and calling an Azure Function
Deployment job- deployment: + environment + strategyAgentYesDeploys artifacts to an Environment, with deployment history and approval checks (Lessons 3 and 5); does not check out code automatically, but automatically downloads this run's pipeline artifacts

When: which information decides “how this run will go”

  • Which branch's YAML: a CI run uses the YAML on the pushed branch; PR build validation uses the YAML in the merge commit.
  • Parallel jobs and agent capacity: decides how long jobs queue. Free tier for private projects: 1 Microsoft-hosted parallel job, up to 1 hour per run and 1,800 minutes per month; with paid parallel jobs, a single job can run up to 31 hours with no monthly limit. Self-hosted: 1 free (plus 1 for each Visual Studio Enterprise subscriber in the organization), with no time limit.
  • Timeouts and heartbeats: each job has a timeout (timeoutInMinutes) and a cancellation grace period (cancelTimeoutInMinutes); the agent sends a heartbeat every minute, and the server goes 5 minutes in a row without one, and then marks the job as failed (common with self-hosted machines that lose power or network).

Comparison with similar technologies

Azure PipelinesGitHub ActionsGitLab CI
Definitionazure-pipelines.yml, stages/jobs/steps.github/workflows/*.yml, jobs/steps.gitlab-ci.yml, stages/jobs
ExecutorAgent (hosted / self-hosted / VMSS / Managed DevOps Pools)RunnerRunner
Compile-time expressions${{ }} Template expressionsNo separate compile time (${{ }} evaluated at runtime)include/rules
Concurrency billingBy parallel jobsBy minutes (private repos)By compute minutes
Common misconceptions① “${{ variables.x }} can read a variable set by the previous step's script”—no; template expressions are fully evaluated at compile time. ② “Jobs share one machine”—Microsoft-hosted agents use a brand-new VM for each job, destroyed when the job ends; pass files between jobs using artifacts (Module 6). ③ “Waiting for approval also occupies a parallel job”—no; a run waiting for approval uses no parallel job, and neither do agentless jobs.

Architecture diagram: division of labor between server and agents

Event sources git push (CI)PR build validation / pr:schedules (UTC)Upstream pipeline completion / manual Azure Pipelines service (dev.azure.com) ① Compile/expandTemplates + ${{ }} → final YAMLFailure = YAML error, 0 jobs ② Resource authorizationService connections / pools / variable groups / reposChecked before each stage starts ③ Job schedulingmatrix expansion, conditiondependsOn topology ④ Parallel job gateRunning jobs < parallel jobs?No → queue Agent pool Azure Pipelines (hosted)Picks a fresh VM by vmImageDestroyed when the job ends Self-hosted / VMSS / MDPMatched by demands ↔ capabilitiesAgent long-polls the server to pick up jobs Job on the agent: download tasks → create working directory → one separate process per step (checkout, script, task…) Streams log lines in real time; uploads the full log when a step ends; uploads test results and artifacts; logging commands ##vso[...] set variables / upload files Heartbeat once per minute; 5 minutes without a heartbeat → job fails Result / status
Figure 1-1: the server handles compilation, authorization, scheduling and the parallel job gate; agents only execute the jobs assigned to them

Hierarchy: Run → Stage → Job → Step

Run #20261115.3 (Build.Reason = IndividualCI) Stage: Lint Job: ruff (agent job)step: checkout: selfstep: UsePythonVersion@0step: script: ruff check . Stage: Test (dependsOn: Lint) Job: py312matrix expansionservice container redis Job: py313matrix expansionparallel (needs 2 parallel jobs) Stage: Build Job: docker (agent job) Job: wait (pool: server)
Figure 1-2: stages run serially by default (each depends on the previous one); jobs within the same stage run in parallel by default (when agents and parallel jobs are free)

Core animation: the lifecycle of a run

Choose a scenario, then click “Play” or “Next”. Each step corresponds to the official documentation Pipeline runs describes the real processing stages; the terminal shows what you would see in the run log or CLI. After injecting a fault, watch where the run “gets stuck”, which is the most important judgment when troubleshooting.

Core commands (az pipelines)

CommandPurposeKey parameters / notes
az pipelines createCreate a pipeline from a YAML file in the repo--repository-type tfsgit|github,--yml-path,--skip-first-run
az pipelines runManually queue a run--branch,--variables k=v (override when queuing is allowed),--parameters k=v
az pipelines runs list / showView run status and results--status,--result,--top,--open
az pipelines runs artifact list/downloadList and download pipeline artifacts--run-id,--artifact-name,--path
az pipelines build cancelCancel a run--id
az devops invokeCall any REST API (e.g. to get logs)--area build --resource logs
az pipelines runs list --pipeline-ids $(az pipelines show --name myapp-ci --query id -o tsv) \
  --top 5 --query "[].{id:id, reason:reason, result:result, branch:sourceBranch, queued:queueTime}" -o table
Id    Reason       Result     Branch           Queued
----  -----------  ---------  ---------------  --------------------------------
15    pullRequest  failed     refs/pull/3/merge 2026-11-15T09:42:10.123456+00:00
14    individualCI succeeded  refs/heads/main  2026-11-15T09:30:02.551234+00:00
12    manual       succeeded  refs/heads/main  2026-11-15T09:12:44.009812+00:00

Get the log list for a run and a specific log

RUN=14
az devops invoke --area build --resource logs --route-parameters project=myapp-lab buildId=$RUN \
  --api-version 7.1 --query "value[].{id:id, lines:lineCount}" -o table
az devops invoke --area build --resource logs --route-parameters project=myapp-lab buildId=$RUN logId=1 \
  --api-version 7.1 --http-method GET --out-file run14-log1.txt; head -20 run14-log1.txt

How to verify: logId 1 is usually the “Initialize job” log, which shows the agent name, version and image version (such as Image: ubuntu-24.04,Version: 20261102.1). Common errors:--api-version If omitted, the CLI uses the default version, and some resources will report that the version is not supported. Production use: Pull logs back locally for grep and archive them for audits.

In the UI, view the “expanded final YAML”

Top right of the run page ⋮ → Download logs, the file in the downloaded archive is azure-pipelines-expanded.yaml (some views can also show it via ⋮ → View/Download full YAML ), which is the result of compile step ①: templates inlined,${{ }} expressions evaluated. Check it first when troubleshooting “template not applied” or “why a condition evaluates this way”.

Lab 1: do a “post-mortem” on a run (about 6 min)

Create a representative run: in azure-pipelines.yml append a context-printing step at the end and push.
- script: |
    echo "Reason=$(Build.Reason) Branch=$(Build.SourceBranch) Commit=$(Build.SourceVersion)"
    echo "Agent=$(Agent.Name) OS=$(Agent.OS) ImageOS=$ImageOS ImageVersion=$ImageVersion"
    echo "Workspace=$(Pipeline.Workspace)"; df -h $(Pipeline.Workspace) | tail -1
    nproc; free -g | head -2
  displayName: Run context
git commit -am "print run context" && git push
Reason=IndividualCI Branch=refs/heads/main Commit=3f9c2e1…
Agent=Azure Pipelines 3 OS=Linux ImageOS=ubuntu24 ImageVersion=20261102.1
Workspace=/home/vsts/work/1
/dev/root        72G   55G   17G  77% /
2
               total        used        free      shared  buff/cache   available
Mem:               7           1           5           0           0           6

2 cores and about 7 GB of RAM, matching the official hosted agent specs; the total disk is large, but the official docs only guarantee at least 10 GB free. ImageOS/ImageVersion are environment variables injected by the hosted image; use the actual values.

Read the log against the lifecycle: open the run → Job → check in turn Initialize job(agent version, downloaded tasks and their versions),Checkout(git fetch --depth=1 appears or not), each step,Finalize Job. In Initialize job find something like:
Agent name: 'Azure Pipelines 3'
Agent machine name: 'fv-az123-456'
Current agent version: '4.264.2'
Operating System
Ubuntu 24.04.3 LTS
Runner Image
Image: ubuntu-24.04
Version: 20261102.1
Downloading task: UsePythonVersion (0.257.0)
Downloading task: PublishTestResults (2.262.0)
Job preparation parameters …

Version numbers are examples. Key point: tasks are referenced by major version (e.g. @0,@2) and the agent downloads the latest minor version within that major version.

Download the expanded YAML: run page ⋮ → Download logs; unzip and view azure-pipelines-expanded.yaml. You will notice that even if you only write steps:, the server expands it into stages → stage: __default → jobs → job: Job full structure.
Experience “queuing”: manually queue two runs in a row az pipelines run --name myapp-ci; az pipelines run --name myapp-ci, then in Organization settings → Pipelines → Parallel jobs → View in-progress jobs and watch the second job stay queued until the first one finishes.
Cleanup: keeping the “Run context” step helps later troubleshooting; delete it and push if you do not want it. This lab creates no billable resources.

Case 1: “The pipeline keeps getting slower” is really queuing

Problem: A 30-person team has only 1 Microsoft-hosted parallel job. Developers complain CI takes 25 minutes, but a single run's log shows only 6 minutes. What was done: The agent pool's Analytics → Pool consumption report view showed running jobs pinned at the concurrency limit for long periods, with a persistent queue. Following the official rule of thumb “1 parallel job per 4–5 users”, they bought 6 and split lint and unit tests into separate parallel jobs. Limitation: Parallel jobs cannot be split by project or agent pool, so heavy runs in one project crowd out other projects.

Case 2: inventory before migrating classic releases

Problem: The company has 120 classic build and release pipelines and plans to migrate them. What was done: First export classic builds to YAML (classic editor ⋮ → Export to YAML) and compare the steps in the expanded YAML. Release pipelines cannot be exported in one click, so map them as “stage = stage, deployment group = deployment job + environment” (Lesson 5). Configuration: During the migration, enable “block creation of classic build/release pipelines” in organization settings. Limitation: Task groups must be rewritten as step templates.

Case 3: self-hosted agent “random failures”

Problem: Nightly builds intermittently fail with We stopped hearing from agent …. What was done: They checked the timestamps and found they matched the host's automatic update reboots: 5 minutes without a heartbeat is enough to fail a job. Fix: Configure a maintenance window on the agent host, or switch to a VMSS agent pool or Managed DevOps Pools (Lesson 7).

Common errors and fixes

##[error]No hosted parallelism has been purchased or granted.

Cause: The organization has no Microsoft-hosted parallel job. Per current official documentation, the private-project free tier requires the organization to be linked to a valid Azure subscription (set up billing), after which it takes effect automatically. Earlier error messages also included a manual request-form link; follow the current official documentation.

# Check in the browser (most reliable):
#   https://dev.azure.com/<org>/_admin/_buildQueue?_a=resourceLimits   (Organization settings → Parallel jobs)
#   If the Microsoft-hosted row shows "Free tier / 0", there are no Microsoft-hosted parallel jobs
az pipelines runs show --id <RUN_ID> --query "{status:status, result:result}" -o table

Fix: Organization settings → Billing → Set up billing to link a subscription; or register a self-hosted agent and change pool: { name: Default }.

/azure-pipelines.yml (Line: 12, Col: 5): Unexpected value 'step'

Cause: YAML structure error at compile time (misspelled keyword, misaligned indentation). The run fails immediately, creates no jobs and consumes no parallel jobs.

Fix: Use Validate in the pipeline editor; or install the Azure Pipelines extension in VS Code for schema validation. Use the “line:column” in the error location; it is often an indentation problem on the previous line.

There was a resource authorization issue: "The pipeline is not valid. Job X: Step Y input azureSubscription references service connection Z which could not be found..."

Cause: Resource authorization happens before a stage starts: the service connection does not exist, its name is misspelled, or it has not been authorized for this pipeline.

Fix: On the first run, click Authorize resources/Permit on the run page; or add the pipeline under Security → Pipeline permissions for the service connection. A service connection name cannot come from a runtime variable (covered in detail in Lesson 3).

We stopped hearing from agent Agent-01. Verify the agent machine is running and has a healthy network connection.

Cause: No agent heartbeat for 5 minutes in a row: the machine rebooted, lost network, or ran out of memory so the OOM killer terminated the agent process. On hosted agents this is usually a job that exhausted memory or disk.

journalctl -u 'vsts.agent.*' --since "1 hour ago" | tail -50     # self-hosted Linux (systemd service)
dmesg -T | grep -i -E "oom|killed process" | tail

Fix: Self-hosted: investigate the host and network. Hosted: reduce the number of concurrent processes and clean up the disk (the official docs guarantee at least 10 GB free).

The job running on agent Azure Pipelines 2 ran longer than the maximum time of 1 hour.

Cause: The free-tier hosted job is limited to 1 hour per run, or the YAML timeoutInMinutes is set too low.

Fix: Split the job and add caching (Module 6); with purchased parallel jobs a single job can run up to 31 hours; set a sensible timeoutInMinutes.

Command-line tasks
1. Using one command, list the ID, trigger reason and branch of the last 3 failed runs of myapp-ci.
az pipelines runs list --pipeline-ids $(az pipelines show --name myapp-ci --query id -o tsv) \
  --result failed --top 3 --query "[].{id:id, reason:reason, branch:sourceBranch}" -o table
2. Manually queue a run of myapp-ci on the feature/login branch and open it in the browser.
az pipelines run --name myapp-ci --branch feature/login --open
Scenario analysis
A PR build validation shows as failed in the UI, but the Jobs list is empty, it took 2 seconds, and it consumed no parallel job minutes. Which step most likely failed? How do you check?

It failed in the compile/expand phase (or the resource authorization phase): jobs were not created yet, so nothing queued and no parallel jobs were consumed. Check the error at the top of the run summary page (such as Unexpected value, a template file not found, a parameter type mismatch, or a resource authorization error). Investigate with the pipeline editor's Validate or by downloading the expanded YAML; if the PR introduced the template change, fix it on the PR branch.

Verified teaching videos

▶
Azure DevOps Tutorial for Beginners | CI/CD with Azure Pipelines — TechWorld with Nana
English · full walkthrough from organization/project to the first YAML CI/CD; suitable for reviewing the overall concepts of this module and Module 0 (the UI follows the current product)
▶
Building and Deploying your Code with Azure Pipelines — Microsoft Visual Studio
English · Azure Pipelines introduction from Microsoft's official channel; recorded earlier, so details such as hosted image labels follow this lesson

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot generate video or MP3 directly; the storyboard and narration script are provided so they can be passed to a video tool.

Shot 1 · 0–15s
Visual: a developer runs git push; a beam of light flies from the repo to a cloud labeled Azure Pipelines.
Narration: one push is the start of a run. The server first reads the YAML on that branch.
Shot 2 · 15–35s
Visual: several template files merge like puzzle pieces into one complete YAML; ${{ }} is replaced with concrete values.
Narration: the first step is compilation: expand templates and evaluate template expressions. If this step fails, the run fails immediately and no jobs are created.
Shot 3 · 35–60s
Visual: job cards line up in front of a gate labeled “Parallel jobs 1/1”; the gate opens when the previous job leaves.
Narration: a job must first get a parallel job slot, then be picked up by an agent. Each job on a Microsoft-hosted agent runs on a brand-new virtual machine.
Shot 4 · 60–90s
Visual: the agent lights up steps one by one, logs scroll, and finally a green check mark appears on the PR page.
Narration: the agent runs steps, streams logs back, uploads artifacts, and finally writes the result back to the PR. Once you understand this chain, you know where a failure is stuck.
or score ≥ 70% on the quiz

Module 2 · YAML structure: stage, job, step

07:00 – 15:00 · Three layers + dependencies + conditions can express most CI workflows; checkout's defaults decide whether your git commands end up with “missing history”
8 mindependsOn · conditionShallow clone default depth 1 (some organizations)★★★★★
Learning objectives
  • Write a complete stages → jobs → steps structure, and understand how the shorthand (writing only steps or jobs) is filled in on the server.
  • Use dependsOn to organize serial, fan-out and fan-in flows, and use condition to control failure notifications, cleanup, and “build only on main”.
  • Distinguish task and script/bash/pwsh, and know checkout 's options: fetchDepth,fetchTags,clean,path, and multi-repo checkout.
Prerequisites: The run lifecycle from Module 1. Importance:★★★★★

What: the three-layer structure and common keywords

LevelKeywordCommon propertiesDefault behavior
Pipelinetrigger pr schedules resources parameters variables pool stages/jobs/stepsname (run number format, e.g. $(Date:yyyyMMdd)$(Rev:.r))Writing only steps makes the server fill in 1 stage + 1 job
Stage- stage: NamedisplayName dependsOn condition variables pool jobsDepends on the previous stage by default (serial); dependsOn: [] means no dependencies, runs in parallel
Job- job: / - deployment: / - template:pool dependsOn condition strategy timeoutInMinutes (default 60) cancelTimeoutInMinutes continueOnError workspace.clean container servicesJobs within the same stage are independent and run in parallel by default
Step- script - bash - pwsh - powershell - task - checkout - download - publish - templatedisplayName name (for output variables) condition env continueOnError timeoutInMinutes retryCountOnTaskFailure workingDirectoryRun in order; after a step fails, later steps are skipped by default (default condition succeeded())

Why: why split into multiple stages/jobs

  • Fail fast: errors that lint catches in 30 seconds should not wait for 5 minutes of tests and image builds.
  • Parallel speedup: multiple jobs in the same stage can run at the same time (provided there are enough parallel jobs).
  • Clear visualization and retries: a failed stage can be Rerun failed jobson its own, without rerunning everything.
  • Cost: every job is a new VM that must check out code and install dependencies again; pass files between jobs using artifacts. Do not split more finely than needed just to make it “look nice”.

How: dependencies and conditions

  • dependsOn: A or dependsOn: [A, B] (fan-in); multiple jobs depending on dependsOn: A is fan-out.
  • Status functions: succeeded() (default: all dependencies succeeded or partially succeeded),failed() (any dependency failed),succeededOrFailed() (regardless of success or failure, but not cancelled),always() (runs even if cancelled),canceled().
  • A custom condition replaces the default condition: writing condition: eq(variables['Build.SourceBranch'], 'refs/heads/main') means it runs even if upstream fails! The correct form is and(succeeded(), eq(...)).
  • In a step,condition checks the status “so far in this job”; on a job or stage, it checks the status of its dependencies.

task vs script

script/bash/pwshtask: Name@Major
Natureis a shorthand for the CmdLine/Bash/PowerShell tasksa packaged Node.js/PowerShell program with input validation and a UI form
Best forfamiliar command lines: pip, pytest, dockerneed platform integration: publishing test results, using service connections, caching, artifacts
Cross-platformscript cmd on Windows, bash on Linux; bash/pwsh specify the interpreteris determined by the task itself
Version—references the major version and automatically gets the latest minor version (Module 7)

checkout: checkout options and defaults

PropertyMeaningDefault / notes
checkout: self | none | <repo alias>checks out the current repo / no checkout / checks out a repo declared in resourcesAutomatic when a regular job does not write checkout checkout: self; deployment jobs do not check out automatically
fetchDepthShallow clone depthAfter 2022-09 (sprint 209) new pipelines in some organizations have shallow clone enabled with depth 1 by default; an explicit YAML setting takes precedence over the UI; fetchDepth: 0 Fetch full history
fetchTagsWhether to sync tagsAn explicit YAML setting takes precedence over the UI's Sync tags; new pipelines do not sync tags by default (set git describe to true when needed)
cleanWhether to clean the working directory before checkoutmatters for self-hosted agents (hosted agents always use a new VM)
pathChecks out to $(Agent.BuildDirectory) subdirectoryDefault for a single repo s; with multiple repos, each repo is checked out to s/<repo name>
persistCredentialsKeep the access token for later git commands (e.g. pushing after tagging)Default false
submodules / lfsSubmodules (true/recursive) / Git LFSNot handled by default
fetchFilter / sparseCheckoutDirectories / sparseCheckoutPatternsPartial clone (e.g. blob:none) / sparse checkoutrequires a newer agent (v3.253.0 / v4.253.0 or later); speeds up large repos

When: what granularity to choose

  • Small projects: 1 stage and 2–3 parallel jobs is enough.
  • For “build once, deploy many times” or approvals: multi-stage (Build → Dev → Prod), covered in Lessons 3 and 5.
  • Needs full Git history (version calculation, SonarQube blame,git describe): explicitly set fetchDepth: 0.
Common misconceptions① “Jobs in a stage run in the order they are written”—no; without dependsOn they may run in parallel, and order is not guaranteed. ② “continueOnError: true can turn a failed job into a success”—it only changes the result to SucceededWithIssues(partially succeeded), and downstream dependencies still treat it as “succeeded”. ③ “An environment variable exported in one step is still there in the next”—no; each step is a separate process, so use ##vso[task.setvariable] (Module 5).

Dependency diagram: fan-out, fan-in and conditional jobs

Lint UnitTestdependsOn: Lint SecurityScandependsOn: Lint Build (fan-in)dependsOn: [UnitTest, SecurityScan] NotifyFailurecondition: failed() Cleanupcondition: always()
Figure 2-1: UnitTest and SecurityScan run in parallel (fan-out), and Build waits for both to succeed (fan-in); failure notifications and cleanup rely on condition functions

Directory diagram: working directory on the agent (Linux hosted agent)

$(Agent.BuildDirectory) = $(Pipeline.Workspace) = /home/vsts/work/1 s/Build.SourcesDirectory= System.DefaultWorkingDirectorycheckout: self checks out here a/Build.ArtifactStagingDirectoryholds artifacts to publish b/Build.BinariesDirectoryintermediate build outputs TestResults/ · <artifact name>/Common.TestResultsDirectorydownload lands by default in$(Pipeline.Workspace)/<artifact name>
Figure 2-2: do not hard-code paths; always use predefined variables (the official docs explicitly warn that the directory layout of hosted agents may change)

Interactive simulator: which jobs will run given the dependencies and conditions?

Set the run scenario and click “Calculate”. The simulator evaluates jobs following the official condition semantics (default succeeded(); a custom condition replaces the default condition). Jobs are evaluated one by one. You can switch Build's condition syntax to see what happens when succeeded() is left out.

Build.SourceBranch:
Build job's condition:
Choose a scenario, then click “Calculate”.

Key YAML snippet

# build the image only on main, notify on failure, always clean up
stages:
- stage: Lint
  jobs:
  - job: ruff
    pool: { vmImage: ubuntu-latest }
    steps:
    - checkout: self
      fetchDepth: 1          # set explicitly to avoid relying on the UI setting
    - script: pipx run ruff check .
- stage: Test
  dependsOn: Lint
  jobs:
  - job: pytest
    timeoutInMinutes: 15
    pool: { vmImage: ubuntu-latest }
    steps:
    - script: |
        pip install -r requirements-dev.txt
        pytest -q
- stage: Build
  dependsOn: Test
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
  jobs:
  - job: docker
    pool: { vmImage: ubuntu-latest }
    steps:
    - script: docker build -t myapp:$(Build.BuildId) .
- stage: Notify
  dependsOn: [Lint, Test, Build]
  condition: failed()
  jobs:
  - job: notify
    pool: server              # agentless job: does not use a parallel job
    steps:
    - task: Delay@1
      inputs: { delayForMinutes: '0' }

How to verify: The Validate button at the top right of the pipeline editor Validate (or Validate and save) only performs a compile check and does not run anything. Common errors: Writing steps directly under a stage (you must first have jobs); pool writing pool: ubuntu-latest (this refers to a self-hosted pool named ubuntu-latest; you should write vmImage).

Multi-repo checkout and full history

resources:
  repositories:
  - repository: tools                # alias
    type: git                        # Azure Repos
    name: myapp-lab/build-tools      # project/repo
    ref: refs/heads/main
steps:
- checkout: self
  fetchDepth: 0                      # full history, overrides the UI's Shallow fetch
  fetchTags: true                    # needed for git describe
  persistCredentials: true           # later steps need to git push tags
- checkout: tools                    # checks out to $(Build.SourcesDirectory)/build-tools
- script: git -C $(Build.SourcesDirectory)/myapp describe --tags --always
v0.3.0-4-g3f9c2e1

With multi-repo checkout, the self repo is also placed in s/<repo name> subdirectory — this changes the script's working directory and is a common cause of “I only added one checkout and now the build can't find files”. When enabling Protect access to repositories in YAML pipelines(on by default for organizations and projects created after 2020-05), other repos must be declared and checked out explicitly like this, otherwise the git clone in your script is rejected.

Lab 2: refactor the myapp CI into three stages: Lint → Test → Build (about 7 min)

Replace azure-pipelines.yml
trigger:
  branches: { include: [ main ] }

variables:
  pythonVersion: '3.13'

stages:
- stage: Lint
  jobs:
  - job: ruff
    pool: { vmImage: ubuntu-latest }
    steps:
    - checkout: self
      fetchDepth: 1
    - task: UsePythonVersion@0
      inputs: { versionSpec: $(pythonVersion) }
    - script: pip install "ruff==0.*" && ruff check .
      displayName: ruff

- stage: Test
  dependsOn: Lint
  jobs:
  - job: pytest
    pool: { vmImage: ubuntu-latest }
    timeoutInMinutes: 15
    steps:
    - task: UsePythonVersion@0
      inputs: { versionSpec: $(pythonVersion) }
    - script: pip install -r requirements-dev.txt
      displayName: Install dependencies
    - script: pytest -q --junitxml=$(Common.TestResultsDirectory)/test-results.xml
      displayName: pytest
    - task: PublishTestResults@2
      condition: succeededOrFailed()
      inputs:
        testResultsFiles: $(Common.TestResultsDirectory)/test-results.xml
        testRunTitle: myapp-unit

- stage: Build
  dependsOn: Test
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
  jobs:
  - job: docker
    pool: { vmImage: ubuntu-latest }
    steps:
    - script: docker build -t myapp:$(Build.BuildId) .
      displayName: docker build
    - script: docker image ls myapp
      displayName: Inspect image
git checkout -b feature/stages
git commit -am "split into Lint/Test/Build stages" && git push -u origin feature/stages
az pipelines run --name myapp-ci --branch feature/stages
Lint  ✓  Succeeded
Test  ✓  Succeeded
Build ⊘  Skipped   (condition not met: Build.SourceBranch = refs/heads/feature/stages)
Verify failure short-circuit: in app.py add an unused import (such as import sys), push to feature/stages and run it. Lint fails (ruff F401), and Test and Build show Skipped. Revert the change, then push again.
Observe the shallow clone: in the Lint checkout log, search for --depth, and you will see git … fetch … --depth=1. Change fetchDepth to 0 and run again; the log no longer shows --depth, and add a step before ruff git log --oneline | wc -l to compare the number of commits.
Merge to main: create a PR in Repos and complete the merge (the Lesson 1 process). All three stages run in the CI run on main, and Build produces the image.
az repos pr create --source-branch feature/stages --target-branch main --title "Split CI stages" --auto-complete true

Case 1: version number calculation gives 0.0.0 everywhere

Problem: The team uses GitVersion/git describe to calculate versions; after migrating to the new pipeline, every build version became 0.0.1-alpha. Cause: The new pipeline defaults to a shallow clone with depth 1 and does not sync tags. Fix: Explicitly set fetchDepth: 0 and fetchTags: true. Lesson learned: For any tool that depends on history or tags, declare checkout parameters explicitly in YAML and do not rely on UI settings.

Case 2: omitting succeeded() led to “publishing even after tests failed”

Problem: The publish stage condition was written as eq(variables['Build.SourceBranch'], 'refs/heads/main'), and the image was still pushed after a test failure. Fix: Change it to and(succeeded(), …), and add “custom conditions must explicitly include a status function” to the team's YAML review checklist.

Case 3: checking out a large monorepo takes 6 minutes

Problem: A 20 GB monorepo; every job's checkout is slow. What was done: CI jobs use fetchDepth: 1 + fetchFilter: blob:none + sparseCheckoutDirectories: services/api (agent 4.253.0+), and checkout drops to 40 seconds. Limitation: After a sparse checkout, files outside the included paths are absent; fetch them on demand with git sparse-checkout add.

Common errors and fixes

/azure-pipelines.yml (Line: 8, Col: 3): Unexpected value 'steps'

Cause: steps was written directly under a stage, or jobs and steps were written at the same level.

Fix: stage → jobs → job → steps; you cannot skip levels.

Stage Build was skipped / Job docker was skipped (but you expected it to run)

Cause: The condition is false or a dependency did not succeed. Hover over the skipped stage on the run page to see the condition evaluation result, for example Evaluating: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main')) Result: False.

Fix: Check Build.SourceBranch 's actual value (for a PR it is refs/pull/N/merge).

fatal: No names found, cannot describe anything.

Cause: Shallow clone / tags not synced.

Fix:fetchDepth: 0 + fetchTags: true.

remote: TF401019: The Git repository with name or identifier build-tools does not exist or you do not have permissions for the operation you are attempting.

Cause: The script directly git clone accesses another repo, but Protect access to repositories in YAML pipelinesis enabled, or the repo is in another project where Limit job authorization scope to current projectis turned on.

Fix: Declare it under resources.repositories and check it out with checkout; for cross-project access, grant the target repo's Read permission to this project's Build Service identity.

##[error]The job running on agent … ran longer than the maximum time of 15 minutes.

Cause: The job's own timeoutInMinutes limit was reached.

Fix: First find the slow step (check how long each step takes), add caching or split the job; do not blindly increase the limit.

Command-line tasks
1. Write a stage that runs in parallel with the Lint stage (it depends on no other stage).
- stage: Docs
  dependsOn: []
  jobs:
  - job: build_docs
    steps:
    - script: echo "build docs"
2. Write a step that must run whether earlier steps succeed, fail or are cancelled, using docker system prune -f.
- script: docker system prune -f
  displayName: Clean up
  condition: always()
Scenario analysis
A colleague added a second checkout (checking out the shared test-data repo) to the Test stage, and afterwards pytest fails with ERROR: file or directory not found: tests. Why?

With multi-repo checkout, each repo is checked out to $(Build.SourcesDirectory)/<repo name>, so self is no longer located at s/ the root, while the default working directory is still s/. Fix: set workingDirectory: $(Build.SourcesDirectory)/myapp on the pytest step, or give the self checkout path, and use variables instead of relative paths in scripts.

Verified teaching videos

▶
Azure DevOps Tutorial for Beginners | CI/CD with Azure Pipelines — TechWorld with Nana
English · the multi-stage YAML demo section of the video can supplement this module

No verified dedicated videos on “dependencies and conditions” or “checkout options” were found; the storyboard script is provided below.

Official documentation

Video storyboard script (about 80 seconds)

Shot 1 · 0–20s
Visual: three nested layers: a Stage box holds Job boxes, and each Job holds a string of Step beads.
Narration: stages hold jobs, and jobs hold steps. Stages run serially by default; jobs in the same stage run in parallel by default.
Shot 2 · 20–45s
Visual: in the dependency graph, Lint turns red, later nodes turn gray and are marked Skipped, and only Cleanup still runs.
Narration: the default condition is succeeded. If upstream fails, downstream is skipped; a cleanup step with always still runs.
Shot 3 · 45–80s
Visual: in the checkout log, --depth=1 is highlighted; next to it git describe fails; after changing to fetchDepth 0 it works.
Narration: new pipelines in many organizations default to a shallow clone of depth one. For tools that need history and tags, explicitly write fetchDepth 0 in the YAML.
or score ≥ 70% on the quiz

Module 3 · Triggers: CI, PR, schedules and pipeline resources

15:00 – 22:00 · When it runs, which branch it runs on, and which YAML it uses — half of all “pipeline didn't trigger” problems come from here
7 minPR in Azure Repos = branch policycron time zone is UTC★★★★★
Learning objectives
  • Know the implicit CI trigger (fires for all branches when no trigger is written, unless “Disable implied YAML CI trigger” is enabled), and can write branch/path/tag filters and batch.
  • Distinguish the two PR trigger types: Azure Repos uses build validation in the branch policy (the pr: in YAML is ignored),GitHub/Bitbucket uses pr:.
  • Write the correct schedules (five-field cron,UTC, no daylight saving time), understand always and its relationship to branch versions; know how to use resources.pipelines so downstream pipelines run automatically after upstream completes.
Prerequisites: The branch policies from Lesson 1. Importance:★★★★★

What: the four trigger types

TriggerYAMLBuild.ReasonWhich branch's YAML is used
CI (push)trigger:IndividualCI / BatchedCIThe pushed branch
PRAzure Repos: branch policy Build validation; GitHub: pr:PullRequestPR's merge commit (refs/pull/N/merge)
Scheduledschedules:ScheduleFor each branch, the schedule in the YAML on that branch and its branch filters decide
Pipeline completionresources.pipelines[].triggerResourceTriggersee below
Manual / API—ManualThe branch you choose

CI trigger rules (Azure Repos Git, verified)

  • Implicit trigger: when YAML has no trigger section, it fires by default for all branches pushes; since sprint 227 it can be enabled in organization/project settings Disable implied YAML CI trigger, after which YAML without a trigger section won't fire (off by default).
  • Writing a trigger replaces the implicit trigger: only explicitly included branches fire. Evaluate include first, then exclude. trigger: none Turn off CI.
  • Path filters: supports *,**,? wildcards; Git paths are case-sensitive; if only exclude is specified, it is equivalent to including everything.
  • Tags: when no tags filter is specified, pushing a tag does not trigger a run.
  • batch: true: if new pushes arrive while a run is in progress, the pipeline waits; after the run ends, the accumulated commits are combined into a single run (use with care for multi-stage pipelines with approvals, since the previous run must reach a terminal state).
  • Skip CI: the commit message or description contains [skip ci],[ci skip],skip-checks: true,[skip azurepipelines],[skip azpipelines],[skip azp],***NO_CI*** one of these, this push does not trigger CI (PR build validation is not affected).
  • Limitations: variables cannot be used in triggers; triggers must be defined in the main YAML file; defining them in a template has no effect; trigger settings in the UI (“Override the YAML continuous integration trigger” on the Triggers page) override the YAML.

PR triggers: two platforms, two approaches

Azure Repos GitGitHub / GitHub Enterprise / Bitbucket Cloud
Where it is configuredTarget branch's Branch policies → Build validation (the YAML pr: is ignored)Set in YAML pr: (branch/path filters,autoCancel,drafts)
DefaultNone; must be added manuallyYAML pipelines have CI and PR triggers enabled by default
Status reportingpolicy checks on the PR page (can be set to Required to block merging), validity period (Build expiration)GitHub Checks (via the Azure Pipelines GitHub App); combine with branch protection rules to block merging
Draft PRsdo not triggerdrafts: false can be excluded
Fork—Secrets are not exposed to fork PRs by default; this can be adjusted in UI settings (risky)

Scheduled triggers

  • cron has five fields: minute hour day month weekday,the time zone is always UTC, and daylight saving time is not handled. 2 AM Eastern Standard Time in Canada (EST, UTC−5) = 0 7 * * *; during daylight saving time (EDT, UTC−4) it becomes 3 AM.
  • always: false (default): since the last successful scheduled run, do not run if there are no code changes; always: true run unconditionally. batch: true: do not start a new scheduled run while the previous one is still in progress.
  • A schedule is re-evaluated for a branch after these events: pipeline creation, an update to that branch's YAML, and creation of a new branch. A schedule only takes effect for a branch if the branch filter in that branch's YAML includes it.
  • Schedules defined in the UI will override the YAML schedules; YAML schedules must be in the main file and cannot use variables. Limits are roughly 1,000 runs per pipeline per week and 10 runs per 15 minutes.
  • Build.CronSchedule.DisplayName Conditions can distinguish between “nightly builds” and “weekly builds.”

Pipeline resource triggers

Declared in the downstream pipeline resources.pipelines: when an upstream (source) run completes successfully, the downstream pipeline runs automatically, and it can read upstream information through variables such as resources.pipeline.<alias>.runID , etc., and use download: <alias> to download upstream artifacts. Typical use: a CI pipeline produces images or packages, and a CD pipeline (Lesson 3) deploys after it completes. Official note: for pipeline completion triggers, branch filters are evaluated using the YAML on the default branch of the triggered pipeline (the branch used for manual and scheduled builds).

When: recommended combinations

  • Trunk-based development: trigger include only main and releases/*, use build validation for PRs, and run a full test nightly (always: true as needed).
  • Documentation changes do not run CI: paths.exclude: [docs/*, '*.md'], but the build validation policy must also set the same path filters; otherwise PRs will wait forever for a required check.
Common misconceptions① “Having written pr: [main] in Azure Repos YAML, a PR should trigger”—no, Azure Repos only honors branch policies. ② “cron uses my local time”—it is always UTC. ③ “Adding a schedule for a release branch in main's YAML is enough”—the release branch's own YAML must also include it. ④ “Putting triggers in a template for central management”—triggers in templates have no effect.

Decision flow: does an event trigger CI?

git push to branch B Does the UI override the YAML trigger?Yes → follow the UI setting Does branch B's YAML have a trigger?No → implicit: all branches* B matches include and is not in excludeNo → does not trigger Do the changed paths match the paths filter?case-sensitive Does the commit contain [skip ci] or similar?Yes → does not trigger Is the pipeline disabled or paused?Paused → queued but not run Create run ✓ * When the organization or project has “Disable implied YAML CI trigger” enabled, no trigger section = does not trigger PR (Azure Repos): does not follow this path; the Build validation policy on the target branch queues a run when the PR is created or updated, running refs/pull/N/merge Schedules: the scheduler decides based on UTC time and the schedules in each branch's own YAML; with always: false, it also checks whether there have been changes since the last successful scheduled run Pipeline resources: upstream run completes successfully → check the trigger branch filter in the downstream resources.pipelines → create a run with Build.Reason = ResourceTrigger
Figure 3-1 Decision order for CI triggers (simplified)

Sequence diagram: Azure Repos PR build validation

DeveloperAzure ReposAzure PipelinesAgent Create/update PR Policy: queue build (refs/pull/N/merge) Job assignment Result Update PR status (succeeded/failed) Required policy not passed → merge cannot be completed
Figure 3-2 Build validation runs against the “merged code,” so it can catch problems where each change passes on its own but the combination fails

Interactive checker: will this event trigger a run?

The YAML below stays fixed. Select the repository type and event, click “Check,” and the simulator gives a verdict and reasoning based on the official rules.

trigger:
  batch: true
  branches:
    include: [ main, releases/* ]
    exclude: [ releases/old* ]
  paths:
    exclude: [ docs/*, '*.md' ]
  tags:
    include: [ v* ]
pr:
  branches: { include: [ main ] }
schedules:
- cron: '0 7 * * Mon-Fri'
  displayName: nightly
  branches: { include: [ main ] }
Repository type:
Event:
Branch / tag name:
Changed files (comma-separated):
Select the conditions, then click “Check.”

Trigger-related YAML and CLI

# Downstream pipeline: myapp-nightly-scan.yml
trigger: none          # does not trigger on push
pr: none               # (GitHub) does not trigger on PRs
schedules:
- cron: '0 7 * * Mon-Fri'          # UTC 07:00 = Toronto EST 02:00 (03:00 during daylight saving time)
  displayName: nightly
  branches: { include: [ main ] }
  always: true
resources:
  pipelines:
  - pipeline: ci                    # alias
    source: myapp-ci                # upstream pipeline name
    trigger:
      branches: { include: [ main ] }
steps:
- download: ci                      # download this run's artifacts from upstream (Module 6)
- script: |
    echo "Reason=$(Build.Reason)"
    echo "Upstream run=$(resources.pipeline.ci.runName) id=$(resources.pipeline.ci.runID) branch=$(resources.pipeline.ci.sourceBranch)"
    echo "Schedule=$(Build.CronSchedule.DisplayName)"

Add a build validation policy with the CLI (Azure Repos “PR trigger”)

REPO_ID=$(az repos show --repository myapp --query id -o tsv)
PIPE_ID=$(az pipelines show --name myapp-ci --query id -o tsv)
az repos policy build create --repository-id $REPO_ID --branch main \
  --build-definition-id $PIPE_ID --display-name "myapp-ci PR validation" \
  --blocking true --enabled true --manual-queue-only false \
  --queue-on-source-update-only true --valid-duration 720 \
  --path-filter "!/docs/*;!*.md"
az repos policy list --repository-id $REPO_ID --branch main \
  --query "[].{type:type.displayName, blocking:isBlocking, enabled:isEnabled}" -o table
Type                            Blocking    Enabled
------------------------------  ----------  ---------
Minimum number of reviewers     True        True
Build                           True        True

Parameter notes:--blocking true = Required; --valid-duration 720 = build result remains valid for 12 hours after the target branch is updated (0 = never expires); --queue-on-source-update-only true = only queue when the source branch is updated; --path-filter Use ; to separate,! to indicate exclusions; paths start with / (for wildcard syntax, follow the official Branch policies documentation); they should match the YAML path filters. Common errors: Using the wrong pipeline ID or --branch writing refs/heads/main (other formats are wrong; the CLI accepts both main).

Viewing schedules and trigger settings

Pipeline page ⋮ → Scheduled runs shows only schedules within the next 7 days (displayed in the browser's local time zone); ⋮ → Triggers to check for UI overrides.

Lab 3: path filters + PR build validation + nightly build + downstream pipeline (about 8 minutes)

Add path filters to myapp-ci: replace the azure-pipelines.yml top section with the content below and merge into main.
trigger:
  branches: { include: [ main ] }
  paths:
    exclude: [ docs/*, '*.md' ]
Verify the path filter: push a change to only README.md to main and confirm that no new run starts; then change app.py, push, and confirm it triggers.
echo "# myapp" > README.md && git add README.md && git commit -m "docs" && git push
az pipelines runs list --pipeline-ids $PIPE_ID --top 1 --query "[].{id:id,reason:reason,commit:sourceVersion}" -o table
The latest run's commit is still the previous code commit — the README change did not trigger a run
Enable PR build validation: run the command from the “Commands” tab: az repos policy build create. Create a new branch and change tests/test_app.py so that an assertion fails, create a PR, and observe that the PR page shows myapp-ci PR validation a failing check and the “Complete” button is unavailable. After fixing and pushing, confirm the check is re-queued automatically and turns green.
Create the downstream pipeline: put the myapp-nightly-scan.yml file from the Commands tab in the repository root, merge into main, then register it:
az pipelines create --name myapp-nightly-scan --repository myapp --repository-type tfsgit \
  --branch main --yml-path myapp-nightly-scan.yml --skip-first-run true
After any successful myapp-ci run on main, myapp-nightly-scan runs automatically and the log shows Reason=ResourceTrigger. On the first run, you may need to click Permit to grant access to the upstream pipeline resource.
Check the schedule: myapp-nightly-scan → ⋮ → Scheduled runs; confirm the weekday schedule time is displayed (converted to local time). After the lab, you can delete schedules in the YAML to avoid using up free minutes.

Case 1: PR stuck at “Required check pending”

Problem: The YAML excludes docs/*, but the build validation policy has no path filter; in addition, the policy is set to trigger only for specific paths — as a result, the required check for documentation-only PRs never runs. Fix: Make the policy's Path filter path filter match the YAML, or make the check optional for documentation-only PRs. Lesson: PR checks are configured in two places — the policy and the pipeline — so review them together.

Case 2: daylight saving time pushed nightly builds into working hours

Problem: The European team's 0 22 * * * builds moved up by one hour when daylight saving time began, eating into the evening deployment window. Fix: Document in the team wiki that “all cron times are UTC,” and choose times that don't conflict year-round; tasks that need strict local time should be handed to an external scheduler that calls the REST API to queue runs.

Case 3: decoupling CI from CD

Problem: A single pipeline both builds and deploys, so even build fixes must wait for approval. Approach: Split into app-ci (producing artifacts) and app-cd (resources.pipelines triggered, downloads artifacts, deploys). Configuration: The CD trigger includes only main, and an Environment approval is added in Lesson 3. Limitation: The downstream pipeline must have access to the upstream pipeline resource (authorization); across projects, it is also limited by the job authorization scope.

Common errors and fixes

Code was pushed, but the pipeline has no new runs

Troubleshooting order:① whether “Override the YAML continuous integration trigger from here” is checked on the Triggers page; ② whether the YAML on that branch has a trigger and whether it includes that branch; ③ path filters and case; ④ whether the commit message contains [skip ci]; ⑤ whether the organization has enabled Disable implied YAML CI trigger; ⑥ whether the pipeline is disabled or paused (Settings); ⑦ whether the trigger is written in a template or uses variables.

pr: is written but PRs in Azure Repos do not trigger

Cause: Azure Repos does not support YAML pr: for PR triggers.

Fix: Target branch → Branch policies → Build validation → add this pipeline.

The schedule in the YAML does not run, and it does not appear under Scheduled runs either

Cause: A schedule trigger exists in the UI (overriding the YAML); the branch filter in that branch's YAML does not include it; cron syntax error; the pipeline is disabled; the frequency limit is exceeded.

Fix: Delete the UI schedule, then push again to have the YAML schedule re-evaluated; verify with the Scheduled runs view.

The code has not changed, but scheduled runs still run every day

Cause:always: true; or there has never been a fully successful scheduled run (partial success doesn't count), so the system cannot find a baseline for comparison; or the pipeline settings or service connection were modified.

Downstream pipeline (resources.pipelines) was not triggered

Cause:source the name does not match the upstream pipeline name (when a folder path is needed, write \folder\name); the upstream run did not succeed; the branch filter does not match; the branch filter reads the YAML on the default branch of the triggered pipeline; first-time authorization is required.

Fix: Check the name and the YAML on the default branch; authorize the resource on the run page.

Command-line questions
1. Write the schedules for “2 AM Toronto time (EST) on weekdays, main only, running even when there are no changes.”
schedules:
- cron: '0 7 * * Mon-Fri'   # EST = UTC-5; during daylight saving time it is actually 03:00 local time
  displayName: nightly-main
  branches: { include: [ main ] }
  always: true
2. Turn off CI and (GitHub) PR triggers for a pipeline so that it can only be run manually.
trigger: none
pr: none
Scenario analysis
A team moved both trigger and schedules into a shared template ci-template.yml, leaving only extends. Afterwards, pushes do not trigger and the nightly build has also stopped. Why? How should it be changed?

Officially: triggers and schedules must be defined in the main YAML file; triggers in templates are not supported. Keep the trigger/pr/schedules/resources trigger section in the main file; templates should contain only stages/jobs/steps. After the change, push once and the schedule will be re-evaluated.

Verified instructional videos

▶
FREE Azure DevOps Full Course for Beginners | DevOps Tutorial Zero to Hero Series (Day 0) — Tech Tutorials with Piyush
English · an introduction to the series; later episodes cover pipelines and triggers. For PR triggers in Azure Repos, follow “Build validation” under branch policies in this lesson.

No verified video specifically on triggers was found; a storyboard script is provided below.

Official documentation

Video storyboard script (about 80 seconds)

Shot 1 · 0–20s
Visual: a push event passes through four gates in turn: “UI override,” “branch filter,” “path filter,” and “skip ci.”
Narration: a push must pass four gates before it becomes a run. Paths are case-sensitive, and tags do not trigger by default.
Shot 2 · 20–45s
Visual: under the Azure Repos icon, the pr keyword in the YAML is crossed out, and an arrow points to Build validation in Branch policies.
Narration: in Azure Repos, PR triggers rely on build validation in branch policies; only GitHub uses pr in YAML.
Shot 3 · 45–80s
Visual: a world clock stops at UTC 07:00, next to a Toronto clock showing 02:00, which becomes 03:00 after the DST switch; then the upstream pipeline finishes and the downstream one starts automatically.
Narration: cron is always UTC and does not handle daylight saving time. Pipeline resource triggers start the downstream pipeline automatically after CI completes.
or score ≥ 70% on the quiz

Module 4 · Agents and agent pools

22:00 – 29:00 · Microsoft-hosted agents are hassle-free but have fixed specs; self-hosted agents are flexible but you are responsible for security and maintenance; demands determine which machine a job can run on
7 minutesubuntu-latest → 24.04ubuntu-22.04 is deprecated (removal on 2027-04-17)★★★★☆
Learning objectives
  • Remember the current Microsoft-hosted image labels and specs, and know that *-latest will “drift,” and when to pin versions in production.
  • Understand the relationship between agent pools (organization level) and projects,demands and the matching rules against capabilities, and the difference between “waiting in queue” and “failing outright.”
  • Be able to register a self-hosted agent on Linux and run it as a service; understand its security boundaries; know how to use container jobs.
Prerequisites: parallel jobs from Module 1. Importance:★★★★☆

What: types of agent sources

TypeMaintained byCharacteristicsBest for
Microsoft-hosted (pool Azure Pipelines)MicrosoftA fresh VM for each job, destroyed when the job ends; images are updated roughly weekly; no remote login, cannot join corporate networks, cannot increase specsCI for most open-source and small/medium projects; safer for running untrusted code (such as fork PRs)
Self-hostedYouany machine, spec, or network; caches and Docker layers can be kept, so it may be faster; you must handle patching, cleanup, and isolationNeeds internal network access, special hardware (GPU), large disks, or fixed software versions
VMSS agent poolYou (Azure scaling)Azure Virtual Machine Scale Sets scale on demand and can be rebuilt after each jobElastic self-hosted needs
Managed DevOps PoolsMicrosoft-managed infrastructure + your configurationchoice of specs, images, VNet injection, standby agentsEnterprise managed pools (Lesson 7)

Microsoft-hosted images (verified 2026-11-15)

YAML vmImageActual imageStatus / notes
ubuntu-latest or ubuntu-24.04Ubuntu 24.04Used when YAML specifies no pool or image: default image
ubuntu-26.04Ubuntu 26.042026-09-29 GA
ubuntu-22.04Ubuntu 22.04Deprecated, scheduled for removal on 2027-04-17 (there were brownouts earlier); migrate as soon as possible
windows-latest or windows-2025Windows Server 2025 + Visual Studio 2022officially announced for the coming weeks windows-latest will point to windows-2025-vs2026
windows-2025-vs2026Windows Server 2025 + Visual Studio 20262026-09-29 GA
windows-2022Windows Server 2022 + VS 2022available (Windows 2019 was retired on 2025-12-31)
macOS-latest or macOS-15macOS 15 SequoiamacOS agents always run in the US
macOS-26 / macOS-14macOS 26 Tahoe / macOS 14 SonomamacOS 14 is in the deprecation process

Specs: Windows/Linux have 2 cores, 7 GB RAM, and 14 GB SSD (at least 10 GB guaranteed free); Linux steps run in a cgroup with 6 GB of physical memory; macOS has 3 cores and 14 GB. Runs as administrator (Windows) / a user with passwordless sudo (Linux). The IP ranges cover all Azure regions in the organization's geography (weekly JSON); service tags are not supported, and ExpressRoute/VPN are not supported.

Why: free tier and costs

  • Hosted free tier (private projects): 1 parallel job, up to 1 hour per run, 1,800 minutes per month; takes effect automatically once an Azure subscription is linked. After payment, each job can run for up to 31 hours with no monthly limit. Note: buying one only removes the time limit; to run 2 jobs at once, you must buy 2.
  • Self-hosted free tier: 1 parallel job plus 1 for each Visual Studio Enterprise subscriber in the organization,granted automatically, with no time limit; registering any number of agents is free, and billing depends only on the number of parallel jobs.
  • New organizations are limited to 25 hosted parallel jobs (you can request an increase). Refer to the Azure DevOps pricing pagefor prices.

How: pools, queues, and demands

  • Agent pools are defined at the organization level (Organization settings → Agent pools), and projects reference them through “project-level agent pools.” Pools have security roles (Reader/User/Creator/Administrator), and a pipeline must be authorized the first time it uses a pool. The default pool name is Default.
  • Capabilities: the agent automatically collects at startup its system capabilities (environment variables and installed software such as docker,Agent.OS,Agent.Version) +user capabilities added manually by administrators.
  • Demands: the job's requirements for capabilities. - docker (exists) or - Agent.OS -equals Linux (equals). Microsoft-hosted pools do not support custom demands.
  • Matching rules (official): if an idle, matching agent exists → assign; if matching agents exist but all are busy → keep waiting; if the pool has no matching agent at all → the job fails.
  • Agent version: the current major version is v4 (based on .NET), and agents upgrade automatically as required by the server. You can GitHub releases check the latest version.

When: how to choose

RequirementChoice
Standard Linux/Windows/macOS builds with no internal network dependenciesHosted ubuntu-latest (production pipelines can pin ubuntu-24.04 to avoid latest drift)
Needs access to databases or artifact repositories on a private networkSelf-hosted / VMSS / Managed DevOps Pools (VNet)
Needs GPU, very large memory, or disks over 10 GBSelf-hosted or Managed DevOps Pools
Public repositories, fork PRsHosted agents (do not run untrusted code on your internal machines)
Tool versions must be pinned exactlyContainer jobs (container:) or self-hosted
Common misconceptions① “pool: ubuntu-latest”—this looks for a self-hosted pool named ubuntu-latest; the correct form is pool: { vmImage: ubuntu-latest }. ② “Registering 10 self-hosted agents lets 10 jobs run in parallel”—concurrency is limited by the number of self-hosted parallel jobs (1 free). ③ “Files left by a previous run on a hosted agent are still there this time”—every job gets a new VM. ④ “Self-hosted agent cleanup is automatic”—it is not; you need to workspace: clean: all,checkout clean or clean up regularly.

Architecture diagram: how jobs land on agents

Job requestpool: Defaultdemands: dockerAgent.OS -equals Linux Parallel job gateSelf-hosted: used 0 / 1 Agent pool Default (organization level) agent-lnx-01 Linux · docker · python3.13Idle + meets all demands → assigned ✓ agent-lnx-02 Linux · dockerMeets demands but busy → if 01 is also busy, the job waits agent-win-01 Windows_NT · dockerDoes not meet Agent.OS → never assigned; if no agent matches in the whole pool → job fails
Figure 4-1 Agents actively pull jobs from the server via HTTPS long polling (outbound 443 only), so self-hosted agents do not need inbound ports open

Comparison diagram: job lifecycle for hosted vs. self-hosted

Microsoft-hosted ① Take a fresh VM from the regional pool based on vmImage② Run the job (many tools preinstalled; see the image Readme)③ Job ends → VM is destroyed, leaving nothing behindPros: clean and secure; cons: cold start every time, no local cache Self-hosted ① A long-running agent process polls for jobs② Runs in the _work/N directory, reusing Git objects and Docker layers③ Job ends → files remain (a cleanup policy is needed)Pros: fast, can reach internal networks; cons: state contamination, security risks
Figure 4-2 The fundamental difference between the two agent types is whether state persists across jobs

Interactive simulator: will the job be assigned, wait, or fail?

Set the job's demands, agent status, and the number of self-hosted parallel jobs, then click “Submit job.” The simulator applies the official rules (parallel job gate → matching capabilities → idle/busy/no match) to give the result.

Job demands
Self-hosted parallel jobs: Other jobs already running:
Agent status
agent-lnx-01 (Linux · docker · python3.13):
agent-lnx-02 (Linux · docker):
agent-win-01 (Windows_NT · docker):
After setting the conditions, click “Submit job.”

YAML: choosing an agent

jobs:
- job: linux
  pool: { vmImage: ubuntu-24.04 }        # pinned version, avoids latest drift
- job: windows
  pool: { vmImage: windows-latest }
  steps: [ { pwsh: '$PSVersionTable.PSVersion' } ]
- job: selfhosted
  pool:
    name: Default
    demands:
    - docker
    - Agent.OS -equals Linux
- job: in_container                       # container job: steps run inside a container
  pool: { vmImage: ubuntu-latest }
  container: python:3.13-slim
  steps: [ { script: 'python --version' } ]

CLI: view pools and agents

az pipelines pool list --query "[].{id:id, name:name, hosted:isHosted, type:poolType}" -o table
POOL_ID=$(az pipelines pool list --pool-name Default --query "[0].id" -o tsv)
az pipelines agent list --pool-id $POOL_ID --include-capabilities \
  --query "[].{name:name, status:status, enabled:enabled, version:version, docker:systemCapabilities.docker}" -o table
Id    Name             Hosted    Type
----  ---------------  --------  ----------
1     Default          False     automation
9     Azure Pipelines  True      automation

Name          Status    Enabled    Version    Docker
------------  --------  ---------  ---------  ---------------
lab-agent-01  online    True       4.264.2    /usr/bin/docker

Register a self-hosted agent on Linux (running as a service)

# 1) In the UI: Organization settings → Agent pools → Default → New agent → Linux, and copy the download link
#    (use the download address from that dialog or the GitHub releases page; replace AGENT_URL below)
sudo useradd -m -s /bin/bash azagent && sudo usermod -aG docker azagent
sudo -iu azagent
mkdir myagent && cd myagent
curl -fsSLo agent.tar.gz "$AGENT_URL" && tar zxf agent.tar.gz

# 2) Unattended configuration: the PAT only needs the Agent Pools (Read & manage) scope, and it can be revoked after configuration is complete
./config.sh --unattended --url https://dev.azure.com/<org> --auth pat --token "$AZP_PAT" \
  --pool Default --agent "$(hostname)-01" --acceptTeeEula --replace

# 3) Install as a systemd service (must be run by a user with sudo)
exit
cd /home/azagent/myagent && sudo ./svc.sh install azagent && sudo ./svc.sh start && sudo ./svc.sh status
>> Connect:
Connecting to server ...
>> Register Agent:
Scanning for tool capabilities.
Connecting to the server.
Successfully added the agent
Testing agent connection.
Successfully replaced the agent / Settings Saved.
...
Active: active (running)

Notes: The agent only needs outbound HTTPS 443 to dev.azure.com and similar domains. The PAT used at registration is only used during configuration to obtain the agent's own credentials, and it can be revoked after configuration succeeds. The official guidance is to prefer Microsoft Entra identities over PATs (PAT best practices and the retirement of global PATs are covered in Lesson 1). Whether agent configuration supports other authentication methods (such as service principals) is covered in the official documentation.

Lab 4: multi-OS jobs + self-hosted agent (optional) (about 8 minutes)

Run the same tests on Linux and Windows (two parallel jobs are needed to truly run at the same time; with only one, they run one after another in a queue):
trigger: none
jobs:
- job: linux
  pool: { vmImage: ubuntu-24.04 }
  steps:
  - task: UsePythonVersion@0
    inputs: { versionSpec: '3.13' }
  - script: pip install -r requirements-dev.txt && pytest -q
- job: windows
  pool: { vmImage: windows-latest }
  steps:
  - task: UsePythonVersion@0
    inputs: { versionSpec: '3.13' }
  - script: pip install -r requirements-dev.txt && pytest -q
az pipelines create --name myapp-os-check --repository myapp --repository-type tfsgit --branch main --yml-path os-check.yml

Observe: the two jobs' Initialize job values differ; with only one parallel job, the second job shows “Waiting for an available agent.”

(Optional) Register a self-hosted agent: on the lab VM, register it following the Commands tab lab-agent-01 to Default pool. Confirm it shows as Online under Agent pools → Default → Agents, and find the following in Capabilities: docker.
Make the job run on the self-hosted agent:
- job: selfhosted
  pool:
    name: Default
    demands: [ docker, 'Agent.OS -equals Linux' ]
  workspace: { clean: all }      # self-hosted agents clean the working directory every time
  steps:
  - script: hostname && docker version --format '{{.Server.Version}}'
On the first run, click Permit to authorize the pipeline to use the Default pool. Change demands to gpu , then run again and observe the job fail because no agent matches.
Cleanup: cd /home/azagent/myagent && sudo ./svc.sh stop && sudo ./svc.sh uninstall && sudo -u azagent ./config.sh remove --auth pat --token "$AZP_PAT"; revoke the PAT. If you created a VM in Azure for the lab (such as rg-ado-lab, Standard_B2s costs a few cents per hour), use az group delete -n rg-ado-lab --yes --no-wait to delete it.

Case 1: latest drift caused sudden build failures

Problem:ubuntu-latest After switching from 22.04 to 24.04, a test that depends on the system OpenSSL version failed. Approach: Short term: pin ubuntu-22.04, and after scheduling a fix, switch the pin to ubuntu-24.04; subscribe to runner-images repository announcements and the official deprecation timeline. Lesson: Release pipelines should pin specific versions; exploratory CI can use latest to catch problems early. Note that the 22.04 image is deprecated and will be removed on 2027-04-17.

Case 2: a self-hosted agent was “poisoned”

Problem: An open-source project ran PR builds on an internal self-hosted agent, and an external contributor's PR planted a backdoor process in the build script. Fix: Fork PRs always use hosted agents; self-hosted agents serve only trusted branches; agents run as unprivileged users on disposable VMs (VMSS rebuilt after each job, or Managed DevOps Pools).

Case 3: accessing an internal artifact repository

Problem: The build needs to reach a private PyPI mirror that is reachable only within a VNet, and hosted agents cannot use a VPN. Approach: Use Managed DevOps Pools injected into a VNet (Lesson 7), or deploy a VMSS agent pool inside the VNet. Limitation: Requires your own Azure subscription and incurs costs.

Common errors and fixes

##[error]No agent found in pool Default which satisfies the specified demands: docker, Agent.OS -equals Linux (exact wording may vary)

Cause: No agent in the pool satisfies all demands at once; the official rule is: if matches exist but are all busy, wait; if the pool has no match at all, fail.

az pipelines agent list --pool-id $POOL_ID --include-capabilities --query "[].{n:name,s:status,os:systemCapabilities.\"Agent.OS\",docker:systemCapabilities.docker}" -o table

Fix: Install the missing software and restart the agent service (to rescan capabilities), or reduce the demands.

Pool 'ubuntu-latest' could not be found / Could not find a pool with name ubuntu-latest

Cause: Wrote pool: ubuntu-latest.

Fix:pool: { vmImage: ubuntu-latest }.

##[warning] / ##[error] The image ubuntu-22.04 is deprecated … (brownout)

Cause: A deprecated image is being used; during the brownout it is temporarily rejected.

Fix: Migrate to ubuntu-24.04 or ubuntu-26.04, and check the official deprecation timeline.

System.IO.IOException: No space left on device

Cause: Hosted agents guarantee only about 10 GB of free space; large images or dependencies can exhaust it.

Fix: Before the build, clean up unneeded preinstalled tools or Docker images (docker image prune -af), reduce artifact size; if necessary, use self-hosted agents or Managed DevOps Pools.

Agent shows Offline, and the job stays at “Waiting for an available agent”

Cause: The agent service has stopped, the machine went to sleep, a network proxy is blocking outbound 443, or credentials have expired.

sudo ./svc.sh status
tail -n 50 _diag/Agent_*.log

Fix: Start the service; configure the proxy server (./config.sh --proxyurl); if necessary, use --replace to re-register.

Command-line questions
1. List the names of all offline agents in the Default pool.
az pipelines agent list --pool-id $(az pipelines pool list --pool-name Default --query "[0].id" -o tsv) \
  --query "[?status=='offline'].name" -o tsv
2. Write a job that runs pytest in a python:3.13-slim container, on a Microsoft-hosted Ubuntu host.
- job: test_in_container
  pool: { vmImage: ubuntu-latest }
  container: python:3.13-slim
  steps:
  - script: pip install -r requirements-dev.txt && pytest -q
Scenario analysis
The organization has 5 self-hosted agents, but the pipeline's jobs always run one at a time and never in parallel. Why?

Concurrency is determined by the number of self-hosted parallel jobs, not by the number of agents. The free tier includes only 1 (plus 1 for each Visual Studio Enterprise subscriber). Buy more self-hosted parallel jobs under Organization settings → Parallel jobs so all 5 agents can work at the same time.

Verified instructional videos

▶
Azure DevOps Tutorial for Beginners | CI/CD with Azure Pipelines — TechWorld with Nana
English · explains the concepts of hosted and self-hosted agents (for image labels and the free tier, follow this lesson)

No verified video on “self-hosted agent registration” was found; a storyboard script is provided below.

Official documentation

Video storyboard script (about 80 seconds)

Shot 1 · 0–25s
Visual: on the left, a row of disposable VMs appears and disappears; on the right, one long-running server.
Narration: hosted agents use a new machine for each job and destroy it afterward; self-hosted agents run long-term and are fast, but you are responsible for cleanup and security.
Shot 2 · 25–55s
Visual: a job card tagged docker and Linux looks for a match among three agents; the Windows agent lights up red.
Narration: all demands must be satisfied by capabilities. If the matching agents are all busy, the job waits; if none match, the job fails.
Shot 3 · 55–80s
Visual: the ubuntu-latest pointer moves from 22.04 to 24.04, with a calendar marked 2027-04-17 beside it.
Narration: latest drifts. Pin image versions in release pipelines and keep an eye on the deprecation timeline.
or score ≥ 70% on the quiz

Module 5 · Variables, variable groups, and expressions

29:00 – 37:00 · The same variable can be referenced with three syntaxes, each evaluated at a different time — almost every “variable is empty” problem comes from this
8 minutes$(var) · ${{ }} · $[ ]Secrets are not automatically exposed as environment variables★★★★★
Learning objectives
  • Explain macros $(var), template expressions ${{ variables.var }}, and runtime expressions $[ variables.var ] : when each is evaluated, where it can be used, and what happens when a variable is not found.
  • Be able to define job/stage/root-level variables, reference variable groups (including Key Vault links), and correctly use secret variables (env: mapping).
  • Be able to use ##vso[task.setvariable] to set variables, and to pass output variables to downstream jobs and stages via dependencies / stageDependencies ; be familiar with common predefined variables and runtime parameters.
Prerequisites: the compile-time vs. runtime distinction from Module 1. Importance:★★★★★

What: where variables come from

SourceHow it is definedNotes
YAML variablesRoot / stage / job variables:— the closer the scope, the higher the priority: job > stage > root > pipeline settings UI
UI variablesPipeline Edit → Variablescan be set as secret and ticked Let users override this value when running this pipeline(overridable when queued)
Variable groupsPipelines → Library; in YAML, - group: nameshared by multiple pipelines; can be linked to Azure Key Vault; a protected resource that requires authorization
Variable templates- template: vars.ymlinlined at compile time (Module 7)
Set in script##vso[task.setvariable variable=x]valueAvailable from the next step onward; add isOutput=true so it can cross jobs/stages.
Predefined variablesProvided by the system:Build.*,System.*,Agent.*,Pipeline.*

How: three syntaxes (official comparison table)

SyntaxExampleWhen processedWhere it can appearIf not found
Macro$(var)Runtime,before each task runs Replacesvalues (right side)Left as-is $(var) (in bash, this is treated as command substitution!)
Template expression${{ variables.var }} / ${{ variables['var'] }}compile timekeys or values (either side)empty string
Runtime expression$[ variables.var ]runtime (when a stage/job starts)values, and must fill the entire right-hand sideempty string
  • Macros: most commonly used; suited to task inputs and scripts. Note that macros inside displayName are not expanded in job names.
  • Template expressions: can only see statically defined variables and parameters in YAML, plus a few predefined variables available at compile time (such as Build.SourceBranch,Build.Reason). Suited to “deciding structure at compile time”: ${{ if }},${{ each }}, and passing parameters to templates.
  • Runtime expressions: suited to conditions and dependency data, such as isMain: $[eq(variables['Build.SourceBranch'], 'refs/heads/main')], and reading upstream output variables.
  • Non-secret variables are automatically injected as environment variables: names are uppercased,. becomes _ (Build.SourceBranch → $BUILD_SOURCEBRANCH).
  • Reserved prefixes: variable names cannot start with endpoint,input,secret,path,securefile (case-insensitive), or tasks and scripts cannot read them.

Secret variables

  • Sources: variables locked in the UI, secrets in variable groups, Key Vault-linked variable groups, and issecret=true set with setvariable. Do not write secret values in YAML.
  • Secrets are not automatically exposed as environment variables; you must explicitly map them in each step that needs them: env: { REDIS_PASSWORD: $(redisPassword) }.
  • They are masked on a best-effort basis in logs as ***, but do not echo them or pass them as command-line arguments (some systems record process command lines).
  • PR builds from GitHub forks do not receive secrets by default.

Output variables (across steps / jobs / stages)

Where consumedSet byHow to reference
Later steps in the same job##vso[task.setvariable variable=tag]1.2.3$(tag)
Same job (with isOutput)…;isOutput=true], step name: meta$(meta.tag)
Downstream jobSame as above, job Ajob B dependsOn: A,variables: { tag: $[ dependencies.A.outputs['meta.tag'] ] }
Jobs in a downstream stageSame as above, stage S1 job Astage S2 dependsOn: S1, job variables $[ stageDependencies.S1.A.outputs['meta.tag'] ]
Conditions in a downstream stageSame as abovecondition: eq(dependencies.S1.outputs['A.meta.tag'], '1.2.3')

Only directly dependent (dependsOn) jobs/stages can read them; matrix jobs and deployment jobs use different output variable name formats (deployment jobs need the job name/strategy prefix; see the official Deployment jobs documentation and Lesson 5). If unsure of the name, add a variable in the downstream job deps: $[convertToJson(dependencies)] and print it.

When: parameters or variables?

Runtime parameters parameters:Variables
TypeTyped (string/number/boolean/object…), can be restricted valuesAlways strings
EvaluatedAt compile time, can be used to ${{ if }} change structureMostly at runtime
UIShown as a form in the run dialogMust tick “Allow override when queued”
RecommendedWhen users need to choose at run time (e.g., whether to run the full test suite)Configuration values, secrets, passing values between steps
Common misconceptions① “Being able to read variable group / UI variables inside ${{ }} ” — at compile time the variable group data has not been fetched yet (the variable group itself must be authorized first), so it usually cannot be read. ② “In bash, writing $(MY_VAR) is the same as $MY_VAR” — the former is a macro; if the variable does not exist, it stays as-is, bash runs it as a command, and this produces MY_VAR: command not found. ③ “setvariable takes effect in the current step”—it only applies from the next step. ④ “Secret variables can be used like normal variables, $MYSECRET”—you must env: map explicitly.

Timeline: when each of the three syntaxes is evaluated

Compile / expansion Stage/job start Before each task runs ${{ variables.x }}${{ parameters.p }}${{ if }} / ${{ each }}Sees only static YAML contentNot found → empty string $[ variables.x ]$[ dependencies.A.outputs[…] ]condition: …Must fill the entire right sideNot found → empty string $(x)Task inputs, script bodiesCan read setvariable from the previous stepCan only be used in value positionsNot found → left as $(x) Inside the script process$X (environment variable)Secrets need env: mappingName uppercased, . → _
Figure 5-1 The further right, the more information is visible; the further left, the more it can change the pipeline's structure

Data flow: output variables across stages

Stage Build → Job docker - bash: echo "##vso[task.setvariable variable=imageTag; isOutput=true]$(Build.BuildNumber)" name: meta Stage Scan (dependsOn: Build) → Job trivy variables: tag: $[ stageDependencies.Build.docker .outputs['meta.imageTag'] ]
Figure 5-2 Path = stageName.jobName.outputs['stepName.variableName']; empty if dependsOn is missing

Evaluation timeline simulator

In the YAML below, step 1 uses setvariable to set tag. Step through and observe what each reference is replaced with at each point in time.

variables:
  env: dev
  isMain: $[ eq(variables['Build.SourceBranch'], 'refs/heads/main') ]
steps:
- bash: echo "##vso[task.setvariable variable=tag]1.2.3"
  name: s1
- bash: |
    echo "A=${{ variables.env }}  B=${{ variables.tag }}"
    echo "C=$(env)  D=$(tag)  E=$(isMain)"
    echo "F=$(notDefined)"
    echo "G=$REDIS_PASSWORD"
  env:
    REDIS_PASSWORD: $(redisPassword)   # secret, from variable group
ReferenceCompile timeJob startBefore step 2 runsScript output

YAML snippet

parameters:                      # runtime parameters (optional in the run dialog)
- name: fullTests
  type: boolean
  default: false

variables:
- group: myapp-common            # variable group (Library)
- name: imageName
  value: myapp
- name: isMain
  value: $[ eq(variables['Build.SourceBranch'], 'refs/heads/main') ]

steps:
- bash: |
    short=$(echo $(Build.SourceVersion) | cut -c1-7)
    echo "##vso[task.setvariable variable=imageTag;isOutput=true]$(Build.BuildId)-$short"
  name: meta
- script: docker build -t $(imageName):$(meta.imageTag) .
- ${{ if eq(parameters.fullTests, true) }}:
  - script: pytest -q -m "slow"
- bash: ./smoke.sh
  env:
    REDIS_PASSWORD: $(redisPassword)      # secret: explicit mapping
    SYSTEM_ACCESSTOKEN: $(System.AccessToken)

CLI: pipeline variables and variable groups

# pipeline variable (overridable when queued)
az pipelines variable create --pipeline-name myapp-ci --name logLevel --value info --allow-override true
# secret variable: the value is read from an environment variable to keep it out of shell history
export AZURE_DEVOPS_EXT_PIPELINE_VAR_redisPassword='S3cr3t!'
az pipelines variable create --pipeline-name myapp-ci --name redisPassword --secret true
az pipelines variable list --pipeline-name myapp-ci -o table

# variable group (--authorize true allows all pipelines to use it; in production, per-pipeline authorization is recommended)
az pipelines variable-group create --name myapp-common --variables registry=myacr.azurecr.io pythonVersion=3.13 --authorize false
GID=$(az pipelines variable-group list --group-name myapp-common --query "[0].id" -o tsv)
az pipelines variable-group variable create --group-id $GID --name redisPassword --secret true --value 'S3cr3t!'
az pipelines variable-group variable list --group-id $GID -o table

# runtime override
az pipelines run --name myapp-ci --variables logLevel=debug --parameters fullTests=true
Name           Allow Override    Is Secret    Value
-------------  ----------------  -----------  -------
logLevel       True              False        info
redisPassword  False             True

Name           Is Secret    Value
-------------  -----------  ----------------
pythonVersion  False        3.13
redisPassword  True
registry       False        myacr.azurecr.io

Common predefined variables

VariableExample value / meaning
Build.ReasonIndividualCI, BatchedCI, PullRequest, Schedule, Manual, ResourceTrigger
Build.SourceBranch / Build.SourceBranchNamerefs/heads/main / main (for PR: refs/pull/7/merge / merge)
System.PullRequest.SourceBranch / TargetBranch / PullRequestIdonly has a value during PR runs
Build.SourceVersion / Build.BuildId / Build.BuildNumbercommit SHA / run ID (integer) / run number (determined by name: )
Pipeline.Workspace / Build.SourcesDirectory / Build.ArtifactStagingDirectorysee Module 2, Figure 2-2
Agent.OS / Agent.TempDirectoryLinux / Windows_NT / Darwin; temp directory (cleaned up after the job)
System.AccessTokenjob access token (representing the project's Build Service identity),requires explicit env mapping
System.Debugwhen set to true, outputs diagnostic logs (a great troubleshooting tool)

Lab 5: image tag variable + cross-stage value passing + secrets (about 8 minutes)

Create a variable group (run the variable-group command in the Commands tab,--authorize false).
Modify the Build stage to output the image tag, and add a Report stage that reads it:
- stage: Build
  dependsOn: Test
  variables:
  - group: myapp-common
  jobs:
  - job: docker
    pool: { vmImage: ubuntu-latest }
    steps:
    - bash: |
        short=$(echo "$(Build.SourceVersion)" | cut -c1-7)
        echo "##vso[task.setvariable variable=imageTag;isOutput=true]$(Build.BuildId)-$short"
      name: meta
      displayName: Compute image tag
    - script: docker build -t $(registry)/myapp:$(meta.imageTag) .
    - bash: test -n "$REDIS_PASSWORD" && echo "secret length=${#REDIS_PASSWORD}"
      env: { REDIS_PASSWORD: $(redisPassword) }
      displayName: Secret mapped (prints only its length)

- stage: Report
  dependsOn: Build
  jobs:
  - job: show
    pool: { vmImage: ubuntu-latest }
    variables:
      tag: $[ stageDependencies.Build.docker.outputs['meta.imageTag'] ]
    steps:
    - checkout: none
    - bash: echo "tag = $(tag)"

On the first run, a prompt says the variable group needs authorization; click Permit The Report job does not need source code, so checkout: none.

Verify:
Compute image tag   ##[section]… (no output)
docker build -t myacr.azurecr.io/myapp:58-3f9c2e1 .
Secret mapped      secret length=7
Report › show  tag = 58-3f9c2e1
Experience the three syntaxes: in the docker job, add a step bash: echo "${{ variables.registry }} | $(registry) | $(nope)". In the log, the first is empty (the variable group can't be read at compile time), the second has a value, and the third triggers nope: command not found— this is the consequence of “macros are left as-is when not found.” Delete this step after the lab.
Enable diagnostic logs: az pipelines run --name myapp-ci --variables system.debug=true (requires allowing overrides, or ticking Enable system diagnostics), then observe the extra ##[debug] lines in the log.

Case 1: a variable used for a service connection name in a template

Problem: The team used azureSubscription: $(svcConn), with svcConn set per environment in job variables, and the result was that the service connection could not be found. Cause: Resource authorization happens before the stage starts, when job variables do not yet exist. Fix: Use template parameters ${{ parameters.serviceConnection }} or use static values at the root/stage level.

Case 2: secret leaked into logs

Problem: The script ran curl -u admin:$(apiKey) …, and set -x was also enabled; masking stopped working after URL encoding, and the key appeared in the logs. Fix: Rotate the key immediately; change to env: mapping, and use --netrc-file or read headers from an environment variable; do not use set -x together with secrets. Lesson: Masking is best-effort, not a security boundary.

Case 3: Key Vault-linked variable group

Problem: Multiple pipelines share a database password, and rotating it requires editing each one. Approach: Link the variable group to Azure Key Vault (requires a service connection, Lesson 3); after the key is rotated in Key Vault, the pipeline automatically reads the latest value on its next run. Limitations: Only the secret names you select are synced; the variable group must be authorized for the pipeline.

Common errors and fixes

/home/vsts/work/_temp/xxxx.sh: line 1: imageTag: command not found

Cause: Macro $(imageTag) could not find its variable, so it stayed as-is in the script and bash performed command substitution.

Fix: Check variable name case and scope; when using isOutput=true in the same job, write $(stepName.imageTag); setvariable only applies to subsequent steps.

In a downstream job, $(tag) is empty: variables: tag: $[ dependencies.A.outputs['meta.imageTag'] ]

Cause: Missing dependsOn: A; step has no name: meta; forgot isOutput=true; used dependencies (should be stageDependencies.Stage.Job.outputs[…]); matrix/deployment job names use a different format.

variables:
  deps: $[ convertToJson(dependencies) ]
steps:
- bash: echo '$(deps)'
Unexpected value '$[ variables.x ] suffix' / runtime expression was not evaluated

Cause: A runtime expression must fill the entire right-hand side.

Fix: Use format(): $[ format('{0}-suffix', variables.x) ], or concatenate using macros.

Secret reads as empty in script: echo $MYSECRET prints an empty line

Cause: Secrets are not automatically mapped to environment variables.

Fix: Add env: { MYSECRET: $(mySecret) } to that step.

An error occurred while loading the YAML build pipeline. Variable group was not found or is not authorized for use.

Cause: The variable group name is wrong, or it is not authorized for this pipeline.

Fix: Library → variable group → Pipeline permissions to add the pipeline, or click Permit on the first run.

Command-line questions
1. In a bash step, set a read-only variable releaseChannel=stable, which later steps cannot overwrite.
- bash: echo "##vso[task.setvariable variable=releaseChannel;isReadOnly=true]stable"
2. Define a job variable isPR, which is True during PR runs.
variables:
  isPR: $[ eq(variables['Build.Reason'], 'PullRequest') ]
Scenario analysis
A colleague wrote - ${{ if eq(variables['registry'], 'prod.azurecr.io') }}: to decide whether to insert a push step,registry with the value coming from a variable group. As a result, the push step never appears. Why?

${{ if }} is evaluated at compile time, when the variable group has not been fetched yet (and the variable group must be authorized first),variables['registry'] so it is empty, the condition is always false, and the step is removed during expansion. Fix: use a runtime condition condition: eq(variables['registry'], 'prod.azurecr.io'), or make it a runtime parameter or static YAML variable.

Verified instructional videos

No video on “three variable syntaxes / output variables” verified via YouTube oEmbed was found (several candidate links returned Not Found on oEmbed and were excluded). Please refer to the official documentation and the storyboard below.

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–25s
Visual: a timeline with three alarm clocks labeled “compile,” “job start,” and “before each task”; three bracket symbols fly under their respective clocks.
Narration: ${{ }} is evaluated at compile time, $[ ] at job start, and $( ) is replaced before each task runs.
Shot 2 · 25–50s
Visual: the bash terminal shows “imageTag: command not found,” and the shot pulls back to $(imageTag) in the YAML.
Narration: when a macro can't find its variable, it stays as-is; bash runs it as a command, which is the most common cause of an “empty variable.”
Shot 3 · 50–90s
Visual: a locked secret key can only enter the script through an env gate; on the other side, an output variable flows along a stageDependencies pipe to the next stage.
Narration: secrets must be explicitly mapped; passing values across jobs and stages requires isOutput, the step name, and the dependency relationship to all be in place.
or score ≥ 70% on the quiz

Module 6 · Pipeline artifacts and caching

37:00 – 44:00 · Artifacts are “outputs that downstream steps must have”; caching is an accelerator that makes things faster but still works without it — don't mix the two up
7 minutesPublishPipelineArtifact@1 · DownloadPipelineArtifact@2Cache@2★★★★☆
Learning objectives
  • Use publish/download (or the corresponding task) to pass artifacts between jobs, stages, and pipelines, and know where downloads go by default and how deployment jobs download automatically.
  • Use Cache@2 to cache pip dependencies, design a key that includes a lock-file hash, and restoreKeys fallbacks, and understand that caches are immutable, expire after 7 days without access, and are scoped by branch/PR.
  • Be able to decide whether a file should be an artifact or cached, and troubleshoot “cache never hits / never updates.”
Prerequisites: working directories from Module 2 and variables from Module 5. Importance:★★★★☆

What: artifacts vs. caching

Pipeline artifactsPipeline caching
PurposePass a job's outputs to other jobs/stages/pipelines (without it, downstream steps fail)Reuse dependencies downloaded by a previous run to save time (it still works without this, just slower)
IdentifierUnique per run: artifact namekey (string + file hash)
MutabilityArtifacts with the same name cannot be published twice in the same runCache Immutable: once a key is created in a scope, it is never updated
LifetimeRetained with the run (follows the project's run retention policy)7 days without access expires; manual deletion is not supported (just change the key)
CostOfficial: artifacts and caches are free on all tiers (for rules on counting toward Artifacts storage, see the official documentation)
TaskPublishPipelineArtifact@1 / DownloadPipelineArtifact@2, shortcut keyword publish / downloadCache@2 (automatically appends a Post-job: Cache step at job end to save the cache)

How: artifacts

  • - publish: <path> + artifact: <name> is equivalent to PublishPipelineArtifact@1. You can place .artifactignore in the directory to exclude files.
  • - download: current (this run) or - download: <pipeline resource alias> (upstream pipeline, Module 3); you can add artifact: and patterns:. By default, they download to $(Pipeline.Workspace)/<artifact name>.
  • Regular jobs do not automatically download artifacts; deployment jobs automatically download all artifacts from this run (write - download: none if not needed).
  • The older PublishBuildArtifacts@1 (Build artifacts) still work, but official guidance recommends the faster Pipeline artifacts.
  • CLI download: az pipelines runs artifact download --run-id N --artifact-name image --path ./out.

How: how Cache@2 works

  1. When the Cache@2 step runs, it uses key to look in the “scopes visible to this job” for an exact match; if found → download and extract to path (cacheHitVar = true).
  2. If not found, use restoreKeys in order from top to bottom for prefix matching, taking the most recently created match (cacheHitVar = inexact); if none → false.
  3. Subsequent steps run normally (pip install uses the restored cache directory).
  4. Job all steps succeed, the automatic Post-job: Cache step runs when there is no exact match and packages path and uploads it to this run's job scope.

Key composition

  • Separated by | segments: string (such as python,"$(Agent.OS)"),file path (contents are hashed; the file must exist),file pattern (such as **/requirements*.txt; must match at least one file).
  • Segments that look like paths (containing .) are treated as files! Wrap strings in double quotes: "my.key".
  • You don't need to include project/pipeline/branch information in the key — scopes already provide isolation.

Scope (who can read, who can write)

Run typeReadableWritable
CI / manual / scheduledsource branch,main,mastersource branch
PRsource branch, target branch, intermediate branch refs/pull/N/merge, main, masterWrite only: refs/pull/N/merge
Fork PRtarget branch, intermediate branch, main, masterintermediate branch

Conclusion: let CI on main run once first so that all branches and PRs can read main's cache; cache written by PR builds does not pollute main.

When: which

file to useUseWhy
Dependencies downloaded by pip/npm/MavenCacheCan be re-downloaded if missing
Test reports, code coveragePublishTestResults / artifactNeeds to be shown or archived in the UI
Built wheel, image tar, Helm chartArtifact (or pushed to Azure Artifacts/ACR)The deploy stage must get the same output (“build once, deploy many”)
Docker layer cacheCache (buildx type=local) or registry cacheSpeeds things up, not required
Common misconceptions① “Using a fixed key lets you reuse it forever” — caches are immutable, so a fixed key keeps the cache stuck on the content from the first run, so after a dependency update you still hit the old cache. ② “Cache node_modules together with npm ci” — npm ci deletes node_modules, so cache npm's shared cache directory instead. ③ “Caches are saved even when the job fails” — caches are only saved when all steps succeed. ④ “Downstream jobs can see the upstream job's files directly” — every job runs on a new machine, so you must publish/download.

Data flow: artifacts moving between jobs

Job docker (VM #1)docker build -t myapp:58docker save | gzip > a/myapp.tar.gz- publish: $(Build.ArtifactStagingDirectory) artifact: image Upload Azure Pipelines artifact storageRun 58 / artifact "image"Retained with the run, deduplicated by content Download Job scan (VM #2)- download: current artifact: image→ $(Pipeline.Workspace)/image/docker load -i …/myapp.tar.gz
Figure 6-1: artifacts let the “build once” output be reused by later jobs, stages and even downstream pipelines

Timing: Cache@2 restore and save

Cache@2 (restore)exact key → restoreKeys prefix pip installAlmost no network access on a hit pytest / buildOther steps Post-job: Cache (automatic)All steps succeeded and not an exact hit → upload to the write scope key = python | "Linux" | requirements.txt (hash 9f3a…) → exact hit: cacheHitVar = true, no upload when the job ends requirements.txt changed → new hash c71e… no exact match → restoreKeys "python | \"Linux\"" hits the old cache (inexact) → pip only downloads the differences → upload the new key when the job ends Fixed key "pip" (counter-example) → after the first run it always hits the old content exactly, so the cache never updates even when dependencies change
Figure 6-2: a key containing the lock file hash plus a restoreKeys prefix fallback is the standard design that both hits and updates

Interactive simulator: will the cache hit?

Click the event buttons in order. The simulator tracks cache entries in each scope and computes the result using the official scope read/write rules and the order “exact match → restoreKeys prefix → miss”. Switch to the “fixed key” counter-example to see why the cache never updates.

Cache entries
Current state
Click an event to start.

Artifacts: full and shorthand syntax

steps:
# Publish (the two forms are equivalent)
- task: PublishPipelineArtifact@1
  inputs:
    targetPath: $(Build.ArtifactStagingDirectory)
    artifact: image
    publishLocation: pipeline
- publish: $(Build.ArtifactStagingDirectory)
  artifact: image

# Download (the two forms are equivalent)
- task: DownloadPipelineArtifact@2
  inputs:
    buildType: current
    artifactName: image
    targetPath: $(Pipeline.Workspace)/image
- download: current
  artifact: image
  patterns: '**/*.tar.gz'

Cache@2: pip

variables:
  PIP_CACHE_DIR: $(Pipeline.Workspace)/.pip      # keep pip's cache in a predictable location

steps:
- task: UsePythonVersion@0
  inputs: { versionSpec: '3.13' }
- task: Cache@2
  displayName: Cache pip
  inputs:
    key: 'python | "$(Agent.OS)" | "3.13" | requirements.txt | requirements-dev.txt'
    restoreKeys: |
      python | "$(Agent.OS)" | "3.13"
      python | "$(Agent.OS)"
    path: $(PIP_CACHE_DIR)
    cacheHitVar: PIP_CACHE_RESTORED
- script: pip install -r requirements-dev.txt
- script: echo "cache hit = $(PIP_CACHE_RESTORED)"
Resolving key:
 - python                [string]
 - "Linux"               [string]
 - "3.13"                [string]
 - requirements.txt      [file] --> 9F3A1C…
 - requirements-dev.txt  [file] --> 7B20E4…
Resolved to: python|"Linux"|"3.13"|requirements.txt|requirements-dev.txt
Cache hit for: python|"Linux"|"3.13"|…   ← exact hit
…
Post-job: Cache pip
Cache with fingerprint … already exists for key …. Skipping upload.

Notes: The log wording is an example; follow the actual output. How to verify: Compare the duration of the “Install dependencies” step across two runs; check cacheHitVar. Common mistake: Writing "3.13" as 3.13 without quotes, a segment containing . is treated as a file path and reports that the file does not exist.

CLI: download a run's artifact

az pipelines runs artifact list --run-id 58 -o table
az pipelines runs artifact download --run-id 58 --artifact-name image --path ./image58 && ls -lh ./image58

Lab 6: pip cache + image artifact passing (about 7 minutes)

Add a pip cache to the Test stage: put the Cache@2 snippet from the “Commands” tab before the “Install dependencies” step of the Test stage's pytest job (and add PIP_CACHE_DIR) to the root-level variables. Push to main twice and record the duration of the “Install dependencies” step.
1st run: Cache misses (cache hit = false), Install dependencies takes 38s, Post-job uploads the cache
2nd run: Cache exact hit (cache hit = true), Install dependencies takes 6s, Post-job skips the upload
Publish the image artifact in the Build stage:
    - script: |
        docker save myapp:$(Build.BuildId) | gzip > $(Build.ArtifactStagingDirectory)/myapp.tar.gz
        ls -lh $(Build.ArtifactStagingDirectory)
      displayName: Export image
    - publish: $(Build.ArtifactStagingDirectory)
      artifact: image
Add a Smoke stage: download the artifact, load the image, run the health check:
- stage: Smoke
  dependsOn: Build
  jobs:
  - job: run
    pool: { vmImage: ubuntu-latest }
    steps:
    - checkout: none
    - download: current
      artifact: image
    - script: |
        docker load -i $(Pipeline.Workspace)/image/myapp.tar.gz
        docker run -d --name app -p 5000:5000 myapp:$(Build.BuildId)
        for i in $(seq 1 20); do curl -fsS localhost:5000/healthz && break; sleep 1; done
        docker logs app | tail -5
      displayName: Smoke test
Loaded image: myapp:61
ok
[2026-11-15 10:21:03 +0000] [7] [INFO] Booting worker with pid: 7
Download the artifact locally: use az pipelines runs artifact download to download it and docker load, then run the same image locally. This is “build once, run anywhere”.

Case 1: cache “hit” but the dependencies are stale

Problem: The key was written as pip | $(Agent.OS), so after upgrading Flask, CI still tested the old version's behaviour. Cause: The cache is immutable and the key did not include a lock file hash. Fix: Add the requirements file to the key; to invalidate immediately, prefix the key with v2.

Case 2: caching is slower than not caching

Problem: Caching the entire .venv (1.8 GB, including build outputs) took 70 seconds to restore, whereas pip install takes only 40 seconds. Fix: Switched to caching pip's download cache directory (about 200 MB). Lesson: Official guidance: caching only pays off when restore + save takes less time than regenerating the output, so measure before deciding.

Case 3: the deploy stage quietly rebuilds

Problem: The deploy stage re-runs docker build, so the image that was tested differs from the one that goes live. Fix: The build stage produces the artifact (or pushes to ACR and records the digest), and the deploy stage only downloads or references that same artifact (Lesson 3 implements this with the ACR digest).

Common errors and fixes

##[error]Artifact image already exists for build 58.

Cause: The same artifact name is published more than once in one run (a common cause is matrix jobs that each publish the same name).

Fix: Add distinguishing information to the artifact name, for example artifact: test-results-$(System.JobName), or publish from only one job.

##[error]Path does not exist: /home/vsts/work/1/a

Cause: The directory being published is empty or does not exist (the build step did not put files in it, or they were generated in another job).

Fix: Before publishing, check ls -la ; make sure generation and publishing happen in the same job.

Cache Restore: Cache miss (misses every time)

Investigate:① the key includes a value that changes on every run ($(Build.BuildId), time); ② the previous run failed and did not save; ③ the run is a PR and main has never successfully saved the cache; ④ the cache expired after 7 days without access; ⑤ keys differ across OSes.

##[error]One or more errors occurred. (File not found: 3.13) — the Cache@2 key segment was treated as a file (exact wording may differ)

Cause: Segments containing . are treated as file paths.

Fix: Add double quotes around the string segment: "3.13".

tar: … Cannot open: Permission denied (saving the cache failed on a self-hosted agent)

Cause: The self-hosted agent is missing GNU tar (Linux/Windows) or BSD tar (macOS), or the cache directory contains files owned by root (written as root in a container).

Fix: Install the required tar; in container jobs, watch file ownership, or use sudo chown to fix it.

Command-line exercises
1. Write a Cache@2 step that caches the npm shared cache directory, with a key based on package-lock.json and an OS-prefix restore fallback.
variables:
  npm_config_cache: $(Pipeline.Workspace)/.npm
steps:
- task: Cache@2
  inputs:
    key: 'npm | "$(Agent.OS)" | package-lock.json'
    restoreKeys: |
      npm | "$(Agent.OS)"
    path: $(npm_config_cache)
- script: npm ci
2. From upstream pipeline resource ci , download the artifact named image .
- download: ci
  artifact: image
Scenario analysis
In PR builds the team sees a cache hit, but the first CI run on main after merging misses. Why? How can this be improved?

PR runs can only write to the refs/pull/N/merge scope, and main's CI cannot read it. If main has never successfully saved that key before, it misses. Improvement: make sure main regularly has successful CI runs (or scheduled runs) to write to the main scope, and use restoreKeys so small dependency changes get an inexact hit.

Verified teaching video

No video on “pipeline artifacts / Cache@2” verified via YouTube oEmbed was found. Please rely on the official documentation and the storyboard below.

Official documentation

Video storyboard script (about 80 seconds)

Shot 1 · 0–25s
Visual: two separate virtual machines with a wall between them; a package is passed across via “artifact storage”.
Narration: every job is a new machine. Files that downstream jobs need are passed as artifacts.
Shot 2 · 25–55s
Visual: the cache key is made of three blocks: python, Linux and the requirements hash; when the hash changes, that block changes colour and restoreKeys finds the old block.
Narration: put the lock file hash in the key so a dependency change produces a new cache; restoreKeys first uses the old cache as a base and only downloads the differences.
Shot 3 · 55–80s
Visual: PR runs write the cache into the small refs/pull drawer; main's large drawer is unaffected.
Narration: PRs can read main's cache but cannot write to main. Caches are immutable and expire after seven days without use.
or score ≥ 70% on the quiz

Module 7 · Templates and tasks (tasks)

44:00 – 51:00 · Pull repeated YAML into templates with typed parameters; use the right task versions and don't let Marketplace extensions become hidden dependencies
7 minutesstep / job / variable templatesLimits: 100 files · 100 levels · 20 MB★★★★☆
Learning objectives
  • Write step, job and variable templates and pass parameters; understand how templates are compile time expanded,${{ each }}/${{ if }} showing how the structure is generated.
  • Declare parameter types (string/number/boolean/object/stepList/jobList…), reference templates from other repositories and pin them ref.
  • Understand tasks Name@major version version rules, and the installation and governance of Marketplace extensions.
Prerequisites: Modules 2 and 5. Importance:★★★★☆ (extends and required templates are covered in depth in Lesson 5)

What: two types of templates

Includes (insert) templatesExtends (inherit) templates
PurposeInserts a block of steps/jobs/stages/variables at the reference point, like #includeThe template defines the overall structure; the pipeline can only fill in blanks where the template allows
Syntax- template: path.yml + parameters:extends: { template: path.yml, parameters: … }
UseReuse (this module)Security and compliance enforcement; can be combined with the “required template” check (Lesson 5)

How: how templates are processed

  • Templates are expanded in the first step (compile time). Parameters are substituted at this point; after expansion, the pipeline “looks as if it were all written in one file”. So template parameters cannot come from runtime variables.
  • Template files must exist in the repository when the run starts (they cannot come from an artifact). A path that starts with / is an absolute path within the repository; otherwise it is relative to the file that references it.
  • Templates from other repositories: declare them (resources.repositories in type: git for Azure Repos,name: project/repo; type: github a service connection is needed), and reference them with path.yml@alias. Omitting ref defaults to refs/heads/main; pin to a tag or 40-character commit SHA. The repository is resolved only once when the run starts, and it only uses the template files, so it cannot run scripts in the template repository (unless you check it out separately).
  • Limits: at most 100 YAML files (directly or indirectly), at most 100 levels of nesting, and at most 20 MB of memory during parsing (roughly equivalent to 600 KB–2 MB of YAML).
  • Triggers and schedules cannot be defined in templates (Module 3).

Parameter types (official list)

TypeDescription
stringString, can use values: to restrict values
stringListMulti-select string list (not available in templates, use object)
number / booleanNumber (can restrict with values) / true, false
objectAny YAML structure (lists, mappings)
step / stepListSingle step / step sequence
job / jobList,deployment / deploymentList,stage / stageListJob, deployment job, stage (and their sequences)

Default values can only be literals. Scalar parameters without a declared type are treated as strings: eq(true, parameters['x']) when x is the string "false", it may still be true (a non-empty string is truthy in a boolean context), so always write type: boolean.

Tasks and versions

  • Reference format TaskName@major-version, for example UsePythonVersion@0,PublishTestResults@2,Cache@2. The major version is fixed; minor and patch versions automatically use the latest; a major version upgrade (for example @1 → @2) can include breaking changes and requires you to change it yourself.
  • Built-in tasks are open source at microsoft/azure-pipelines-tasks; the run log's Initialize job prints the version actually downloaded.
  • Marketplace extensions: installed at the organization level by an organization administrator (Project Collection Administrators); regular users can only “request” them. Tasks from extensions are used the same way as built-in tasks. Governance advice: maintain an allow list, review publishers, and check whether the extension is still maintained.
  • Task runtime: tasks run on the agent's built-in Node.js or PowerShell; older tasks that depend on a deprecated Node runtime show deprecation warnings, so prefer a newer major version or an alternative task.
  • If a one-line script command solves it, there is no need to add an extension; use a task only when you need platform integration (service connections, test results, caching).

When: when to extract a template

  • The same steps appear in more than 3 jobs/pipelines.
  • Several teams need a unified security scan or signing step (consider extends + required templates).
  • Don't abstract too early for a single pipeline: templates add reading cost, and debugging requires looking at the expanded YAML.
Common misconceptions① “Template parameters can use $(var) to decide dynamically” — templates expand at compile time; a macro is just text at that point, so it is passed through unchanged. ② “Scripts in the template repository run directly” — only template files are used; scripts need a separate checkout. ③ “@2 never changes” — minor versions update automatically; to fully freeze, you must self-host and control task versions, or switch to scripts.

Expansion process: main file + template → final YAML

azure-pipelines.yml jobs:- template: templates/python-test.yml parameters: versions: ['3.12', '3.13'] withRedis: true templates/python-test.yml parameters:- { name: versions, type: object }- { name: withRedis, type: boolean }jobs:- ${{ each v in parameters.versions }}: - job: py_${{ replace(v,'.','') }} ${{ if parameters.withRedis }}: services: { redis: redis } Compile time After expansion (expanded YAML) jobs:- job: py_312 services: { redis: redis } steps: …- job: py_313 services: { redis: redis } steps: …View on the run page: ⋮ → Download logs
Figure 7-1: each and if “generate” YAML at compile time; no ${{ }} remains visible at runtime

Task version resolution

- task: PublishTestResults@2Only major version 2 is specified Versions available on the server: 2.255.0 · 2.259.1 · 2.262.0(example) Agent downloads 2.262.0 (the latest of major version 2)Cached in the agent's _work/_tasks
Figure 7-2: the major version is your “compatibility contract”; minor versions are rolled out by the platform

Template expander

Change the parameters passed to the template, click “Expand” to see the final YAML generated at compile time; you can also deliberately pass the wrong type to see the compile-time error.

versions (object)
withRedis (boolean)
runLint (undeclared type, treated as string)
Syntax in the template:
(click “Expand”)

Step template and job template

parameters:
- name: pythonVersion
  type: string
  default: '3.13'
- name: requirements
  type: string
  default: requirements-dev.txt

steps:
- task: UsePythonVersion@0
  inputs: { versionSpec: '${{ parameters.pythonVersion }}' }
- task: Cache@2
  inputs:
    key: 'python | "$(Agent.OS)" | "${{ parameters.pythonVersion }}" | ${{ parameters.requirements }}'
    restoreKeys: |
      python | "$(Agent.OS)" | "${{ parameters.pythonVersion }}"
    path: $(Pipeline.Workspace)/.pip
- script: pip install -r ${{ parameters.requirements }}
  env: { PIP_CACHE_DIR: $(Pipeline.Workspace)/.pip }
  displayName: Install dependencies (Python ${{ parameters.pythonVersion }})
parameters:
- name: versions
  type: object
  default: [ '3.13' ]
- name: withRedis
  type: boolean
  default: false

jobs:
- ${{ each v in parameters.versions }}:
  - job: pytest_${{ replace(v, '.', '') }}
    displayName: pytest (Python ${{ v }})
    pool: { vmImage: ubuntu-latest }
    ${{ if parameters.withRedis }}:
      services:
        redis: redis
      variables:
        REDIS_HOST: localhost
    steps:
    - template: python-setup.yml          # relative path: relative to this template file
      parameters: { pythonVersion: '${{ v }}' }
    - script: pytest -q --junitxml=$(Common.TestResultsDirectory)/junit-${{ v }}.xml
    - task: PublishTestResults@2
      condition: succeededOrFailed()
      inputs:
        testResultsFiles: $(Common.TestResultsDirectory)/junit-*.xml
        testRunTitle: pytest-${{ v }}
resources:
  containers:
  - container: redis
    image: redis:7-alpine
    ports: [ '6379:6379' ]
jobs:
- template: templates/python-test.yml
  parameters:
    versions: [ '3.12', '3.13' ]
    withRedis: true

Reference from a shared template repository and pin the version

resources:
  repositories:
  - repository: templates
    type: git
    name: platform/pipeline-templates     # project/repo
    ref: refs/tags/v1.4.0                 # pin a tag (or a 40-character commit SHA)
jobs:
- template: python/test.yml@templates
  parameters: { versions: [ '3.13' ] }

CLI: extension management

az devops extension list --query "[].{publisher:publisherId, ext:extensionId, version:version}" -o table
az devops extension search --search-query "sonarqube" --query "[0:3].{id:extensionId, pub:publisher.publisherName}" -o table
# Installing requires organization administrator permission
az devops extension install --publisher-id <publisher> --extension-id <extension>

Lab 7: extract a python-ci template (about 7 minutes)

Create the template files: in the myapp repository, create templates/python-setup.yml and templates/python-test.yml (see the “Commands” tab for the content).
Rewrite the Test stage:
resources:
  containers:
  - container: redis
    image: redis:7-alpine
    ports: [ '6379:6379' ]

# …Lint stage unchanged…
- stage: Test
  dependsOn: Lint
  jobs:
  - template: templates/python-test.yml
    parameters:
      versions: [ '3.12', '3.13' ]
      withRedis: true

Note: resources is a root-level keyword; place it at the top of the file (at the same level as trigger).

Run and check: the Test stage shows pytest (Python 3.12) and pytest (Python 3.13) two jobs; with Redis, the second test is no longer skipped (Tests tab: 2 passed). Download the logs to check azure-pipelines-expanded.yaml, and confirm that each/if has been expanded.
Deliberately pass the wrong type: change withRedis: true to withRedis: yes please, click Validate in the editor, and observe the compile-time error (something like “The 'withRedis' parameter value 'yes please' is not a valid Boolean.”; the exact wording may differ). Change it back and commit.

Case 1: standardizing Python CI across 100 repositories

Problem: Each repository maintained its own CI, and security scan versions were all over the place. Approach: The platform team creates a pipeline-templates repository and publishes semantic version tags; application repositories ref: refs/tags/v1.x reference it. When upgrading, trial the new tag in a few repositories first. Limitation: Tags are movable; for high-security requirements, pin the commit SHA.

Case 2: a template update broke builds company-wide

Problem: Application repositories referenced the template without writing ref (defaults to main); the platform team merged a breaking change, and several hundred pipelines failed at once. Fix: Roll back the template; require all references to pin ref; add PR build validation to the template repository itself, and validate templates with a test pipeline.

Case 3: a Marketplace extension stopped being maintained

Problem: A third-party extension depended on a deprecated Node runtime; logs kept warning, and it eventually failed on new agents. Approach: Inventory the extensions installed in the organization (az devops extension list), and replace them with script or an official task; set up extension approval and an annual review.

Common errors and fixes

/azure-pipelines.yml: File /templates/python-tests.yml not found in repository … branch refs/heads/feature/x

Cause: A misspelled path, a wrong base for the relative path (relative to the file that references it), or the template file does not exist on this branch yet.

Fix: Use an absolute path starting with / , and confirm the file is committed to the branch being run.

The 'withRedis' parameter value 'yes please' is not a valid Boolean. (exact wording may differ)

Cause: Parameter type validation failed (compile time).

Fix: Pass the correct type; for multi-select, use object.

Unexpected parameter 'pythonversion'

Cause: A parameter not declared by the template was passed (names are case-sensitive).

Fix: Compare against the template's parameters list.

A task is missing. The pipeline references a task called 'SonarQubePrepare'. This usually indicates the task isn't installed…

Cause: The extension is not installed in the organization, or the task name/major version is wrong.

Fix: Ask an organization administrator to install the extension; confirm TaskName@N that the major version exists.

Maximum number of included YAML files exceeded / template expansion exceeded limits

Cause: Exceeded the limit of 100 files, 100 levels of nesting, or 20 MB of parsing memory (common when a large template is repeatedly referenced inside each).

Fix: Reduce nesting levels, merge small templates, and avoid inserting large templates inside big loops.

Command-line exercises
1. Write a step template that accepts a stepList typed parameter extraSteps, and insert it after the fixed lint step.
parameters:
- name: extraSteps
  type: stepList
  default: []
steps:
- script: ruff check .
- ${{ each s in parameters.extraSteps }}:
  - ${{ s }}
2. Reference the template in the GitHub repository contoso/templates (service connection name gh-conn), pinned to tag v2.0.0.
resources:
  repositories:
  - repository: shared
    type: github
    name: contoso/templates
    endpoint: gh-conn
    ref: refs/tags/v2.0.0
steps:
- template: steps/lint.yml@shared
Scenario analysis
The template contains - ${{ if parameters.publish }}:, and the caller passes publish: false yet the publish step still appears. The publish parameter in the template has no type. Why?

Untyped scalar parameters are treated as strings, so 'false' is a non-empty string and is truthy in a boolean context. Fix: declare it as type: boolean, or use eq(parameters.publish, 'true') an explicit string comparison.

Verified teaching video

No video on “YAML templates and parameters” verified via YouTube oEmbed was found (mirror-site links that came up could not be verified via oEmbed, so they were excluded). Please rely on the official documentation and the storyboard below.

Official documentation

Video storyboard script (about 75 seconds)

Shot 1 · 0–25s
Visual: a block of steps repeated in three pipelines is cut out, placed into a template box, and replaced with a one-line template reference.
Narration: the template extracts the repeated YAML and inserts it back in place at compile time.
Shot 2 · 25–50s
Visual: the two version numbers in the versions parameter enter an each loop and generate two job cards.
Narration: each and if generate structure at compile time. Always declare parameter types, otherwise the string false is also true.
Shot 3 · 50–75s
Visual: below the task label PublishTestResults@2, 2.255, 2.259 and 2.262 scroll by, and the latest one lights up.
Narration: tasks pin the major version and minor versions update automatically. Pin shared templates to a tag or commit.
or score ≥ 70% on the quiz

Module 8 · CI readiness review and common failures

51:00 – 60:00 · Review a pipeline with a checklist and locate failures with a tree: first decide “which lifecycle step is it stuck at”, then read the specific error
9 minutesInteractive troubleshooting tree10 common failure types★★★★★
Learning objectives
  • Use a 12-item checklist to review whether a CI pipeline “can block bad PRs”.
  • Map common failures back to the Module 1 lifecycle: no trigger → compile failure → authorization failure → queued → agent → steps → artifacts/cache.
  • Handle with confidence: pipeline not triggering,No hosted parallelism has been purchased or granted, YAML parse errors, empty variables, resources and permissions not authorized, cache misses, and so on.
Prerequisites: Modules 1–7. Importance:★★★★★

What: CI readiness review checklist

#Check itemWhyRelated module
1YAML lives in the repository; changes are reviewed through PRsTraceable and reversibleM1
2The target branch has a required build validation policy (Azure Repos), with path filters consistent with the YAMLBad code can't get into mainM3
3trigger explicitly lists branches instead of relying on implicit triggers; documentation-only changes don't run CISaves parallel jobsM3
4Fast first, slow later: lint → unit tests → build; custom conditions include succeeded()fail fast and don't publish by mistakeM2
5Pin the image version (for example ubuntu-24.04), with sensible job settings timeoutInMinutesreproducible, prevents hangsM4
6Dependency cache key includes a lock file hash + restoreKeysFast and correctM6
7Upload test results with PublishTestResults (succeededOrFailed())Shows which test failed when it failsM0/M6
8Build outputs are passed as artifacts, “build once”deploys exactly what was testedM6
9Secrets are not in YAML; use variable groups/Key Vault, and scripts access them via env: mappingto prevent leaksM5
10Extract repeated steps into templates; pin shared templates refConsistency, controlled upgradesM7
11Checkout parameters are explicit (fetchDepth/fetchTags)Not affected by UI default valuesM2
12Resources (pools, variable groups, service connections, repositories) are authorized per pipeline, not “open to all pipelines”Least privilegeM1/M5

How: locate failures by lifecycle

SymptomStuck at which stepCheck first
No run at all after a push/PRTriggerTriggers UI override, branch/path filters, [skip ci], branch policies
Run fails within seconds, no jobsCompile / resource authorizationError at the top of the run summary; download the expanded YAML
Stuck in QueuedParallel job gate / agentParallel jobs page, agent status in the pool, demands
A step is redRuntimeThat step's log; system.debug=true
All steps green but the result is wrongVariables / conditions / cacheSkip reason (hover to see condition evaluation), variable output, cacheHitVar

Why: why locate the stage first

The same “pipeline broke” could mean it never triggered, didn't compile at all, is queued, or the tests really failed — the person who handles it and the fix are completely different (a developer fixes code vs an administrator grants authorization vs finance buys parallel jobs). Locating the stage first can cut troubleshooting from hours to minutes.

When: when to enable diagnostic logs

When a run is queued, check Enable system diagnostics, or set the variable System.Debug=true: tasks will output ##[debug] -level information (variable expansion, HTTP calls, file matching results). Turn it off when done; diagnostic logs are larger and may contain more environment information.

Common misconceptions① “Just rerun it” — this helps with network blips, but for configuration errors it only wastes parallel-job minutes; first see which step failed. ② “A Queued run means an Azure outage” — in most cases parallel jobs are full or no agent is available; check the Parallel jobs page first, then status.dev.azure.com.

Failure map: where common errors fall in the lifecycle

Trigger Compile/expansion Resource authorization Queue/parallel Agent/steps Artifacts/cache/state UI overrides YAMLBranch/path mismatchPath case[skip ci]Writing pr: in Azure Repostrigger in a templateSchedule: UI overridePipeline disabled Unexpected valueIndentation / tabsTemplate file doesn't existWrong parameter typeExceeds template limits${{ }} can't read the variable group Service connection not authorizedVariable group not authorizedAgent pool not authorizedRepository resource not authorizedName uses a runtime variable No hostedparallelism…Parallel jobs fully usedMonthly minutes exhaustedNo matching demandsAgent offline checkout 403/TF401019Shallow clone missing history$(x) undefinedSecret not mapped1-hour timeoutInsufficient disk spaceHeartbeat lost Cache misses every timeCache never updatesArtifact already existsDownload can't find artifactPR status not written backBuild validation expired
Figure 8-1: first locate the column, then find the specific cause within it

Failure replay: at which step did it fail?

Choose a real error; the replayer advances along the lifecycle, stops at the problematic stage, and gives the key diagnostic points.

Choose a failure.

Common troubleshooting commands

# 1) Recent failed runs and their causes
az pipelines runs list --pipeline-ids $PIPE_ID --result failed --top 5 \
  --query "[].{id:id,reason:reason,branch:sourceBranch,finish:finishTime}" -o table

# 2) Timeline of a run (status and errors for each stage/job/step)
az devops invoke --area build --resource timeline \
  --route-parameters project=myapp-lab buildId=$RUN --api-version 7.1 \
  --query "records[?result=='failed'].{type:type,name:name,issues:issues[0].message}" -o table

# 3) Rerun in diagnostic mode
az pipelines run --name myapp-ci --branch main --variables system.debug=true

# 4) Trigger settings and policies
az repos policy list --repository-id $REPO_ID --branch main -o table
az pipelines show --name myapp-ci --query "{yaml:process.yamlFilename, queueStatus:queueStatus}" -o table

# 5) Agents and pools
az pipelines agent list --pool-id $POOL_ID --query "[].{n:name,s:status,e:enabled}" -o table
Type    Name           Issues
------  -------------  -----------------------------------------------------------
Task    pytest         Bash exited with code '1'.
Job     pytest py313
Stage   Test           

Notes: timeline is the fastest API for finding which step failed and what the error message is; queueStatus when paused/disabled is set to false, the run does not execute. Common mistake: Confusing the run ID with the pipeline ID —az pipelines runs uses the run ID,--pipeline-ids uses the definition ID.

Troubleshooting helpers in YAML

- bash: env | sort                         # print all non-secret variables (do not use in steps that contain secrets)
  displayName: Print environment
  condition: eq(variables['System.Debug'], 'true')
- bash: echo '$(deps)'
  displayName: Print dependency outputs
  env: {}
# job variable: deps: $[ convertToJson(dependencies) ]

Lab 8: deliberately create 4 failures and fix them (about 8 minutes)

YAML parse error: on a feature branch, change a steps: to be misspelled as step: and push. Observe that the run fails within seconds with no jobs, and the error is Unexpected value 'step'. Use Validate in the editor to locate and fix it.
Empty variable: change the Build stage's $(meta.imageTag) to $(imageTag). In the logs, watch for imageTag: command not found or an abnormal image tag; understand the reference format after isOutput. Fix it.
Resource not authorized: create a new variable group myapp-secrets (--authorize false) and reference it in the YAML. The run stops at “This pipeline needs permission to access a resource before this run can continue”; click View → Permit then continue.
Cache misses: add to the Cache@2 key | $(Build.BuildId), run twice in a row; both are misses. After removing it, hits are restored.
Review with the troubleshooting tree: open the troubleshooting tree on this module's “Troubleshooting” tab, walk through the path for each failure, and confirm your diagnosis matches your observations.

Case 1: the first day of a new organization, all pipelines are queued

Problem: After creating a new organization and migrating in 30 pipelines, all of them failed at No hosted parallelism has been purchased or granted. Approach: The organization administrator linked an Azure subscription (Billing); after the free tier took effect, critical pipelines were restored first; parallel jobs were bought based on team size; and two self-hosted agents were registered as a contingency. Lesson: Add an item for “billing and parallel jobs” to the new-organization go-live checklist.

Case 2: CI tag push fails after permissions are tightened

Problem: After enabling Limit job authorization scope to current project , the step that tags and pushes reports TF401027: You need the Git 'GenericContribute' permission. Fix: Grant myapp-lab Build Service (org) Contribute and Create tag on that repository; set checkout to persistCredentials: true. Lesson: Tightening authorization scope is the right direction, but you also need to work out the minimum permissions the Build Service identity requires.

Case 3: the “intermittent failures” were really shared state

Problem: Tests failed intermittently on the self-hosted agent, while the Microsoft-hosted agent never failed. Cause: A Redis container left over from a previous job was holding port 6379. Fix:workspace: clean: all, and at the end of the job condition: always() to clean up the container; in the long run, switch to disposable agents.

Interactive troubleshooting tree

Start from the symptom and select step by step; leaf nodes give diagnostic commands and fixes. You can go back to the previous step at any time.

Quick reference for common errors

##[error]No hosted parallelism has been purchased or granted.

The organization has no Microsoft-hosted parallel jobs. Link an Azure subscription to enable the free tier (follow the current official documentation), or use a self-hosted agent. See Modules 1 and 4.

This pipeline needs permission to access a resource before this run can continue to Stage X

Protected resources (service connections, variable groups, agent pools, environments, repositories, secure files) are not yet authorized for the pipeline. Click View → Permit, or add it under the resource's Pipeline permissions.

TF401027: You need the Git 'GenericContribute' permission to perform this action.

The pipeline identity (Build Service) has no write permission on the repository. Grant permission to the corresponding Build Service, and confirm the job authorization scope setting.

##[warning]Unable to resolve the reference … / Could not find a pool with name …

The pool name is wrong, or the project does not reference the organization-level pool (add it under Project settings → Agent pools), or you confused name with vmImage.

Command-line exercises
1. Use one command to find the failed records (stage/job/task) in run RUN and their first error message.
az devops invoke --area build --resource timeline --route-parameters project=myapp-lab buildId=$RUN \
  --api-version 7.1 --query "records[?result=='failed'].{type:type,name:name,msg:issues[0].message}" -o table
2. Re-queue myapp-ci on main in diagnostic mode.
az pipelines run --name myapp-ci --branch main --variables system.debug=true
Scenario analysis
A developer reports: “My PR keeps showing the myapp-ci check as Queued, but other people's PRs run fine.” In what order would you investigate?

① Check whether the run is really queued (Parallel jobs → View in-progress jobs: is a long-running job occupying all the parallel jobs?); ② whether a different pool/demands is used (the PR branch changed the pool) and the matching agents are offline or busy; ③ whether it is waiting for resource authorization (the run page prompts for Permit); ④ whether the free-tier monthly minutes are exceeded; ⑤ finally, check the service status page. Follow the order: “parallel jobs → agent matching → authorization → quota → platform”.

Verified teaching video

▶
Azure DevOps Tutorial for Beginners | CI/CD with Azure Pipelines — TechWorld with Nana
English · can serve as a review of the whole lesson; for troubleshooting, the troubleshooting tree in this module takes precedence

No verified video on “Azure Pipelines troubleshooting” was found, so the storyboard script below is provided instead.

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–25s
Visual: a subway line map with six stations — trigger, compile, authorize, queue, execute, artifacts; a “run” train stops at one station and flashes red.
Narration: the first step in troubleshooting is finding which station the train stopped at.
Shot 2 · 25–60s
Visual: show four scenes in turn — “no run”, “fails within seconds with no jobs”, “stuck in queue”, and “step failed” — each pointing to its station.
Narration: no trigger → check filters and policies; fails within seconds → check YAML and authorization; stuck in queue → check parallel jobs and agents; step failed → check logs and diagnostic mode.
Shot 3 · 60–90s
Visual: the 12 checklist items are ticked off one by one, and a green required check appears on the PR page.
Narration: review your pipeline with the checklist so that every bad PR is kept out of main.
or score ≥ 70% on the quiz

Command cheat sheet

Azure Pipelines YAML and az pipelines · every code block can be copied with one click
After-class reference

Running and viewing

az pipelines create --name N --repository R --repository-type tfsgit --branch main --yml-path azure-pipelines.yml
az pipelines run --name N --branch B --variables k=v --parameters p=v
az pipelines runs list --pipeline-ids ID --top 5 -o table
az pipelines runs show --id RUN --open
az pipelines runs artifact download --run-id RUN --artifact-name A --path ./out
az devops invoke --area build --resource timeline --route-parameters project=P buildId=RUN --api-version 7.1

Structure and conditions

stages:
- stage: Test
  dependsOn: Lint            # [] = no dependencies, run in parallel
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
  jobs:
  - job: t
    timeoutInMinutes: 15
    pool: { vmImage: ubuntu-24.04 }
    steps:
    - checkout: self
      fetchDepth: 0           # full history
      fetchTags: true
    - script: make test
      condition: succeededOrFailed()   # always() / failed() / canceled()

Triggers

trigger:
  batch: true
  branches: { include: [ main, releases/* ], exclude: [ releases/old* ] }
  paths: { exclude: [ docs/*, '*.md' ] }
  tags: { include: [ v* ] }
pr: { branches: { include: [ main ] } }     # GitHub/Bitbucket only
schedules:
- cron: '0 7 * * Mon-Fri'                   # UTC
  branches: { include: [ main ] }
  always: false
resources:
  pipelines:
  - pipeline: ci
    source: myapp-ci
    trigger: { branches: { include: [ main ] } }
# Azure Repos PR: az repos policy build create …

Variables

variables:
- group: myapp-common
- name: isMain
  value: $[ eq(variables['Build.SourceBranch'], 'refs/heads/main') ]
# $(x) before task | ${{ variables.x }} compile time | $[ variables.x ] runtime
- bash: echo "##vso[task.setvariable variable=tag;isOutput=true]1.2.3"
  name: meta
# same job $(meta.tag)
# downstream job $[ dependencies.A.outputs['meta.tag'] ]
# downstream stage $[ stageDependencies.S.A.outputs['meta.tag'] ]
- bash: ./use-secret.sh
  env: { TOKEN: $(token) }   # secrets must be mapped

Agents

pool: { vmImage: ubuntu-latest }   # = ubuntu-24.04; ubuntu-26.04 is also available
pool: { vmImage: windows-latest }  # = windows-2025 (will be repointed to windows-2025-vs2026)
pool: { vmImage: macOS-latest }    # = macOS-15
pool:
  name: Default
  demands: [ docker, 'Agent.OS -equals Linux' ]
pool: server                        # agentless job
container: python:3.13-slim         # container job

Artifacts and cache

- publish: $(Build.ArtifactStagingDirectory)
  artifact: image
- download: current        # or a pipeline resource alias
  artifact: image          # → $(Pipeline.Workspace)/image
- task: Cache@2
  inputs:
    key: 'python | "$(Agent.OS)" | requirements.txt'
    restoreKeys: |
      python | "$(Agent.OS)"
    path: $(Pipeline.Workspace)/.pip
    cacheHitVar: CACHE_HIT   # true / inexact / false

Templates

parameters:
- { name: versions, type: object, default: [ '3.13' ] }
- { name: withRedis, type: boolean, default: false }
jobs:
- ${{ each v in parameters.versions }}:
  - job: py_${{ replace(v, '.', '') }}
    ${{ if parameters.withRedis }}:
      services: { redis: redis }
# reference: - template: t.yml@repoAlias   pin resources.repositories[].ref to a tag/SHA
# limits: 100 files · 100 levels · 20 MB

Matrix and service containers

resources:
  containers:
  - container: redis
    image: redis:7-alpine
    ports: [ '6379:6379' ]
jobs:
- job: test
  strategy:
    matrix:
      py312: { pythonVersion: '3.12' }
      py313: { pythonVersion: '3.13' }
    maxParallel: 2
  services: { redis: redis }   # non-container jobs access it via localhost:6379

Variable groups / policies / agent CLI

az pipelines variable-group create --name G --variables k=v --authorize false
az pipelines variable-group variable create --group-id ID --name s --secret true --value '…'
az pipelines variable create --pipeline-name N --name k --value v --allow-override true
az repos policy build create --repository-id RID --branch main --build-definition-id PID \
  --display-name "PR validation" --blocking true --enabled true \
  --manual-queue-only false --queue-on-source-update-only true --valid-duration 720
az pipelines pool list -o table
az pipelines agent list --pool-id ID --include-capabilities -o table

Predefined variables

Build.Reason            IndividualCI | BatchedCI | PullRequest | Schedule | Manual | ResourceTrigger
Build.SourceBranch      refs/heads/main | refs/pull/7/merge
Build.SourceVersion     commit SHA        Build.BuildId  run ID
Pipeline.Workspace      /home/vsts/work/1
Build.SourcesDirectory  …/s             Build.ArtifactStagingDirectory  …/a
System.AccessToken      job token (requires env mapping)
System.Debug            true = diagnostic logs
Build.CronSchedule.DisplayName  name of the schedule that triggered this run

Capstone lab + final quiz

Deliver a complete CI pipeline for myapp: multiple stages + matrix + Redis service container + cache + artifacts + smoke test + PR build validation
After class ≈ 35 minutesIntegrates all modules
Scenario myapp is about to be handed to Lesson 3 for deployment to Azure. Team requirements: any code that enters main must pass lint, pass tests on Python 3.12/3.13 against a real Redis, successfully build the image, and pass the smoke test; dependency installation must use caching; the image is produced as an artifact for later deployment; PRs that fail checks cannot be merged. Everything is done in the project myapp-lab 's Microsoft-hosted agents (it can be completed on the free tier alone; the matrix jobs run one after another).
Prerequisite checks (Modules 0, 3, 5, 7)
az pipelines show --name myapp-ci --query "{id:id, yaml:process.yamlFilename}" -o table
az pipelines variable-group list --query "[].name" -o tsv        # should include myapp-common
ls templates/                                                       # python-setup.yml python-test.yml
az repos policy list --repository-id $(az repos show --repository myapp --query id -o tsv) --branch main -o table

If any item is missing, go back to the corresponding module's “Lab” tab and complete it.

Complete azure-pipelines.yml
name: $(Date:yyyyMMdd)$(Rev:.r)

trigger:
  branches: { include: [ main ] }
  paths: { exclude: [ docs/*, '*.md' ] }

resources:
  containers:
  - container: redis
    image: redis:7-alpine
    ports: [ '6379:6379' ]

variables:
- group: myapp-common
- name: imageName
  value: myapp
- name: PIP_CACHE_DIR
  value: $(Pipeline.Workspace)/.pip

stages:
# ---------- 1. Lint ----------
- stage: Lint
  jobs:
  - job: ruff
    pool: { vmImage: ubuntu-24.04 }
    timeoutInMinutes: 10
    steps:
    - checkout: self
      fetchDepth: 1
    - template: templates/python-setup.yml
    - script: ruff check .
      displayName: ruff

# ---------- 2. Test (matrix + Redis service container) ----------
- stage: Test
  dependsOn: Lint
  jobs:
  - job: pytest
    pool: { vmImage: ubuntu-24.04 }
    timeoutInMinutes: 20
    strategy:
      matrix:
        py312: { pythonVersion: '3.12' }
        py313: { pythonVersion: '3.13' }
      maxParallel: 2
    services:
      redis: redis
    variables:
      REDIS_HOST: localhost
    steps:
    - template: templates/python-setup.yml
      parameters: { pythonVersion: $(pythonVersion) }   # the macro is passed as text and expanded at runtime in the task input
    - script: pytest -q --junitxml=$(Common.TestResultsDirectory)/junit.xml
      displayName: pytest (Python $(pythonVersion))
    - task: PublishTestResults@2
      condition: succeededOrFailed()
      inputs:
        testResultsFiles: $(Common.TestResultsDirectory)/junit.xml
        testRunTitle: pytest-$(pythonVersion)
    - publish: $(Common.TestResultsDirectory)
      artifact: junit-$(pythonVersion)          # artifact names must be unique within the matrix
      condition: succeededOrFailed()

# ---------- 3. Build ----------
- stage: Build
  dependsOn: Test
  jobs:
  - job: docker
    pool: { vmImage: ubuntu-24.04 }
    steps:
    - bash: |
        short=$(echo "$(Build.SourceVersion)" | cut -c1-7)
        echo "##vso[task.setvariable variable=imageTag;isOutput=true]$(Build.BuildId)-$short"
      name: meta
      displayName: Compute image tag
    - script: |
        docker build -t $(imageName):$(meta.imageTag) .
        docker save $(imageName):$(meta.imageTag) | gzip > $(Build.ArtifactStagingDirectory)/myapp.tar.gz
        echo "$(meta.imageTag)" > $(Build.ArtifactStagingDirectory)/TAG
      displayName: Build and export image
    - publish: $(Build.ArtifactStagingDirectory)
      artifact: image

# ---------- 4. Smoke (artifacts + service container) ----------
- stage: Smoke
  dependsOn: Build
  jobs:
  - job: run
    pool: { vmImage: ubuntu-24.04 }
    services:
      redis: redis
    variables:
      imageTag: $[ stageDependencies.Build.docker.outputs['meta.imageTag'] ]
    steps:
    - checkout: none
    - download: current
      artifact: image
    - script: |
        set -e
        docker load -i $(Pipeline.Workspace)/image/myapp.tar.gz
        docker run -d --name app --network host -e REDIS_HOST=localhost $(imageName):$(imageTag)
        for i in $(seq 1 20); do curl -fsS localhost:5000/healthz && break; sleep 1; done
        a=$(curl -fsS localhost:5000/); b=$(curl -fsS localhost:5000/)
        echo "$a"; echo "$b"
        test "$a" != "$b"     # the counter should increase, proving the Redis connection works
      displayName: Smoke test (healthz + Redis counter)
    - script: docker rm -f app || true
      condition: always()
      displayName: Clean up

Key point: matrix variable $(pythonVersion) can only be expanded at runtime, so what is passed to the template is only text $(pythonVersion), and it is only replaced when it finally appears in a task input or cache key — this is exactly the “three syntaxes” from Module 5 in practice. For non-container jobs, the service container is reachable via port mapping on localhost:6379 is available, and --network host the app container can also reach it.

Push and verify
git checkout -b feature/full-ci && git add -A && git commit -m "full CI" && git push -u origin feature/full-ci
az pipelines run --name myapp-ci --branch feature/full-ci
Lint    ✓ ruff                         0:42
Test    ✓ pytest py312   ✓ pytest py313  (runs one after another with 1 free-tier parallel job)
Build   ✓ docker                       1:35
Smoke   ✓ run    Hello from fv-az…, hits=1 / hits=2
Tests tab: 4 passed (2 per Python version)
Artifacts: image, junit-3.12, junit-3.13
Verify caching: run again, confirm that the Cache step in both matrix jobs shows an exact hit and the dependency install time drops significantly; then modify requirements.txt (for example, change redis==5.* to redis==5.2.*), and run again; an inexact hit should appear and a new cache should be saved.
PR build validation: confirm the Build validation policy on main exists (Module 3), then create a PR:
az repos pr create --source-branch feature/full-ci --target-branch main --title "Full CI" --open
In the PR, deliberately push a commit that makes test_healthz fail. Confirm the PR check fails and the PR cannot be completed; after the fix, the check turns green and you complete the merge.
Download and run the artifact locally
RUN=$(az pipelines runs list --pipeline-ids $(az pipelines show --name myapp-ci --query id -o tsv) --branch main --top 1 --query "[0].id" -o tsv)
az pipelines runs artifact download --run-id $RUN --artifact-name image --path ./image
docker load -i ./image/myapp.tar.gz && cat ./image/TAG
Return to Module 0 and redo the “pipeline readiness self-assessment”, and compare the scores. Cleanup: this lab uses only Microsoft-hosted agents and free storage and incurs no Azure resource charges; if you created a self-hosted agent VM in Module 4, run az group delete -n rg-ado-lab --yes --no-wait; revoke the PATs created in the lab. Keep the pipeline and repository for use in Lesson 3.
Acceptance checklist

Open-ended self-check (answer first yourself, then expand the reference answer)

1. What is the processing order of a run? Which errors appear before jobs are created?

Expand templates and evaluate template expressions → select stages by stage dependencies → authorize the stage's resources → select jobs by job dependencies, expand the matrix, evaluate conditions → request an agent (parallel-job gate, demands matching) → the agent downloads tasks, executes step by step, and reports logs and artifacts. YAML structure errors, missing templates, parameter type errors and unauthorized resources all occur before jobs are created.

2. Why do Azure Repos PRs use branch policies instead of pr:?

PR triggers in Azure Repos are implemented by build validation in branch policies; the YAML pr: only applies to GitHub/Bitbucket. Policies also provide Required, expiration, path filtering and the ability to block merges.

3. What scenario suits each of the three variable syntaxes?

${{ }}: compile-time structure decisions (if/each, template parameters); $[ ]: runtime conditions and dependency data (output variable mapping, isMain checks); $(x): general values in task inputs and script bodies; can read variables set by earlier steps.

4. What is the difference between artifacts and caches? Give an example of each.

Artifacts are outputs that downstream steps require; names are unique within a run, for example an image tar or a test report. Caches are optional speed-ups, reused by key, immutable, and expire after 7 days without access, for example a pip download cache.

5. With only 1 hosted parallel job, what happens to the two matrix jobs? How can you speed things up?

They run one after another (the second is queued). You can buy more parallel jobs, reduce the matrix dimensions (for example, PRs run only the latest version and main runs all), use caching to shorten each job, or add self-hosted parallel jobs.

6. Seeing No hosted parallelism has been purchased or granted, what are your next steps?

Check the hosted free-tier status on the organization's Parallel jobs page; link an Azure subscription (set up billing) per the current official documentation to enable the free tier, or purchase one; before it takes effect, register a self-hosted agent and temporarily switch to pool: { name: Default }; add “billing and parallel jobs” to the new-organization go-live checklist.

Final quiz (12 questions, covering all modules)

Sources and version notes

Verification basis for all technical facts in this lesson (verified 2026-11-15)
TopicVerified conclusionSource (accessed 2026-11-15)
Run processing orderExpand templates and template expressions → stage dependencies → resource authorization → job dependencies/matrix expansion/conditions → request agent; tasks execute step by step as independent processes; heartbeat once per minute, failure after 5 minutes without a heartbeat; runtime variables do not exist during the expansion phase; service connection/environment names cannot come from stage/job variablesPipeline runs(page updated 2026-05)
Microsoft-hosted imagesubuntu-latest= 24.04; ubuntu-26.04 2026-09-29 GA; ubuntu-22.04 deprecated, scheduled for removal on 2027-04-17; windows-latest= windows-2025 (VS2022), to be repointed to windows-2025-vs2026 (2026-09-29 GA); Windows 2019 retired on 2025-12-31; macOS-latest= macOS-15, plus macOS-26 and macOS-14 (being deprecated); 2 cores/7 GB/14 GB SSD (≥10 GB available), Linux cgroup 6 GB; if no image is specified, the default is ubuntu-latestMicrosoft-hosted agents(page updated 2026-11-09)
Parallel jobs and free tierHosted free tier for private projects: 1 parallel job, 1 hour per run, 1,800 minutes per month,takes effect automatically once a valid Azure subscription is linked (billing set up); paid per-job limit 31 hours; self-hosted free 1 + 1 per VS Enterprise subscriber, granted automatically; new organization hosted parallel job cap 25; public projects are retired and will become private in 2027; approval waits and agentless jobs do not consume parallel jobsConfigure and pay for parallel jobs(page updated 2026-11-03)
CI/PR triggers and checkoutImplicit CI trigger and sprint 227's “Disable implied YAML CI trigger”; paths are case-sensitive; tags don't trigger by default; skip-ci variants; Azure Repos PRs use build validation policies, and draft PRs don't trigger; after sprint 209 (2022-09), some organizations' new pipelines default to a shallow clone depth of 1,fetchDepth: 0 overrides; the YAML's fetchTags takes precedence over the UI; Protect access to repositories is enabled by default for organizations and projects created after 2020-05Build Azure Repos Git repositories(page updated 2026-08-07)
Scheduled triggerscron is UTC, with no daylight saving time handling; always default is false; batch; UI schedules override YAML; evaluated against the branch's own YAML; about 1,000 runs per week, 10 runs per 15 minutes; Build.CronSchedule.DisplayNameConfigure schedules(page updated 2026-11-03)
VariablesComparison table of the three syntaxes (timing, location, behavior when not found); runtime expressions must occupy the entire right-hand side; precedence job > stage > root > UI; reserved prefixes endpoint/input/secret/path/securefile; secrets are not automatically mapped to environment variables; GitHub fork PRs have no secrets by defaultDefine variables(page updated 2026-09-17)
Output variablesisOutput/isSecret/isReadOnly; dependencies.A.outputs['step.var'],stageDependencies.S.A.outputs['step.var']; only direct dependencies can read them; deployment job syntax differsSet variables in scripts
CacheCache@2's key/restoreKeys/cacheHitVar (true/inexact/false); caches are immutable; saved in Post-job after the job succeeds; branch/PR/fork scope read-write table; expires after 7 days without access; no size limit; clearing is not supportedPipeline caching(page updated 2026-05)
TemplatesLimits of 100 files / 100 levels / 20 MB; path rules; templates from other repositories default to refs/heads/main, can be pinned to a tag or SHA; only template files are usedTemplates(page updated 2026-06-22)
Template parameter typesstring, stringList (not available in templates), number, boolean, object, step, stepList, job, jobList, deployment, deploymentList, stage, stageList; default values can only be literals; scalars without a declared type are treated as stringsTemplate parameters(page updated 2025-12-19)
ADO_HELM_SPEC verified factsShallow clone and fetchFilter/sparseCheckoutDirectories (agent 3.253.0/4.253.0+); PAT best practices and the global PAT retirement date (Lesson 1)Verified by another courseware author in the same repository (2026-11-15)

Video verification notes

The following videos were verified on 2026-11-15 via the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json), titles and channels confirmed: TechWorld with Nana “Azure DevOps Tutorial for Beginners | CI/CD with Azure Pipelines” (4BibQ69MD8c); Microsoft Visual Studio “Building and Deploying your Code with Azure Pipelines” (NuYDAs3kNV8); Tech Tutorials with Piyush “FREE Azure DevOps Full Course for Beginners | DevOps Tutorial Zero to Hero Series (Day 0)” (A_N5oHwwmTQ). oEmbed does not return durations or publish dates, so no specific durations are listed on the cards. Several searched “variables / templates” topic video IDs returned Not Found or Bad Request via oEmbed and were all excluded, so the video tabs for Modules 5, 6 and 7 only provide official documentation and storyboard scripts. All videos are in English and were recorded before this lesson's verification date; image tags, free-tier rules and similar details follow this lesson and the official documentation.

Audio narration notes

The “Audio” tab 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 (Windows “Microsoft Xiaoxiao/Yunxi”, macOS “Tingting”, etc.). The environment that generated this courseware cannot call a TTS service, so no MP3 is embedded; if offline audio is needed, give the narration script to a TTS service such as Azure AI Speech to generate it.

Known limitations

  • The run IDs, commit SHAs, agent names, image versions, task version numbers, durations and timestamps in the “Expected output” sections are example values; the commands in this courseware were not run in a real organization when it was written, so actual output depends on your environment.
  • The wording of some error messages is marked “subject to actual output”: Azure DevOps adjusts its text, so when troubleshooting, match on keywords (such as parallelism,Unexpected value,not authorized) to match.
  • No hosted parallelism has been purchased or granted 's earlier version included a manual request form link; the current official documentation states that the free tier takes effect automatically once an Azure subscription is linked. If your organization's interface still shows a request form, follow the interface and the latest release notes.
  • windows-latest repointed to windows-2025-vs2026 The exact date of the change is only given as “in the coming weeks”; follow the hosted agents page.
  • Get the self-hosted agent download URL and latest version number from the organization's “New agent” dialog or GitHub releases; this lesson does not hard-code a version number. Whether agents support authentication methods other than PAT is determined by the official documentation.
  • Durations, job names and cache entries in the animations are illustrative values used to explain the mechanism. The output variable syntax of deployment jobs, extends and required templates, and Environments approvals are covered in Lessons 3 and 5.