Azure DevOps Hour 2: Azure Pipelines Core
- 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,dependsOnandcondition,taskandscript,checkoutdefault shallow-clone depth (in some organizations, new pipelines setfetchDepthto 1). - Configure the four trigger types correctly: CI
trigger(branch/path/tag filters), PR (Azure Repos uses branch policy build validation, GitHub usespr:),schedules(cron,UTC),resources.pipelinespipeline 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,demandsand 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
| # | Time | Module | Core content | Animation / interaction | Lab (project myapp-lab) |
|---|---|---|---|---|---|
| 0 | Before class | Bridge and warm-up | Commit myapp code to the repo, enable the free parallel job, first YAML (lint + pytest + docker build) | Pipeline readiness self-check | First green run |
| 1 | 00–07 | Architecture and how it works | YAML vs classic, compile/expand phase vs runtime phase, agent jobs / agentless jobs / deployment jobs, parallel jobs, timeouts and heartbeats | Core animation: the lifecycle of a run (3 failure types can be injected) | Reading run logs and “downloading the expanded YAML” |
| 2 | 07–15 | YAML structure | stages/jobs/steps, dependsOn, condition, task vs script, checkout options, timeouts | Dependency and condition simulator | Refactor into three stages: Lint/Test/Build |
| 3 | 15–22 | Triggers | CI trigger, implicit triggers, path filters, PR (build validation vs pr:), schedules (UTC), pipeline resources | “Will this push trigger a run?” checker | Path filters + nightly build + downstream pipeline |
| 4 | 22–29 | Agents and agent pools | Hosted image labels and hardware, free tier, demands/capabilities, self-hosted agents, container jobs | Agent matching and queueing simulator | Multi-OS jobs + self-hosted agent (optional) |
| 5 | 29–37 | Variables and expressions | Macro / template / runtime expressions, variable groups, secrets, output variables across jobs and stages, predefined variables, runtime parameters | Timeline of the three syntaxes' evaluation | Image tag variable + passing values across stages |
| 6 | 37–44 | Artifacts and caching | PublishPipelineArtifact/DownloadPipelineArtifact, publish/download shorthand, Cache@2 key and scope | Cache key hit simulator | pip cache + image artifact passing |
| 7 | 44–51 | Template basics and tasks | step/job/variable templates, parameter types, each/if, template repositories, Marketplace tasks and versions | Template expander | Extract the python-ci template |
| 8 | 51–60 | CI readiness review and common failures | Review checklist, 10 common failure types and diagnosis | Failure replay + interactive troubleshooting tree | Deliberately trigger 4 failures and fix them |
| — | After class | Cheat sheet · Capstone lab | Full CI: multi-stage + matrix + Redis service container + caching + artifacts + PR build validation | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / keywords | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Explain the run lifecycle and why jobs queue | ✓ | · | · | ✓ | · | · | · | ✓ | az pipelines runs show | M1 lab |
| Write multi-stage YAML, dependencies and conditions | · | ✓ | · | · | ✓ | · | ✓ | · | dependsOn,condition | three-stage CI |
| Control checkout (shallow clone, tags, multiple repos) | · | ✓ | · | · | · | · | · | ✓ | checkout: self,fetchDepth | M2 lab |
| Configure CI / PR / schedule / resource triggers | · | · | ✓ | · | · | · | · | ✓ | trigger,pr,schedules,resources | nightly build |
| Choose agents; understand parallel jobs and costs | ✓ | · | · | ✓ | · | · | · | ✓ | pool.vmImage,demands | multi-OS jobs |
| Variables, secrets, output variables | · | · | · | · | ✓ | · | ✓ | ✓ | ##vso[task.setvariable] | passing values across stages |
| Artifact passing and dependency caching | · | · | · | · | · | ✓ | · | ✓ | publish,download,Cache@2 | pip cache |
| Template reuse and task versions | · | · | · | · | · | · | ✓ | · | template:,parameters,Task@N | python-ci template |
| PR quality gate (build validation) | ✓ | · | ✓ | · | · | · | · | ✓ | az repos policy build create | Capstone lab |
What this hour does not cover (and where to learn it)
| Topic | Why it is not in this hour | Where to learn it |
|---|---|---|
| Service connections, workload identity federation, deploying to Azure, Environments approvals and checks | These belong to CD and cloud-platform topics; this hour covers CI only, with no image push and no cloud connection | Lesson 3: Moving to the cloud platform (Azure) |
| Enforced extends templates, protected resource checks, deployment strategies (runOnce/rolling/canary), Azure Artifacts feeds | Requires first mastering this hour's templates and deployment job basics | Lesson 5: Production-grade pipelines |
| Managed DevOps Pools, VMSS agent scaling, agent performance tuning | Belongs to platform operations | Lesson 7 |
| Git details in Azure Repos (clone authentication, Git-side behavior of branch policies) | covered in the Git course | Git 8-hour course Lesson 3 |
| GitHub Actions comparison | This hour compares only where necessary | GitHub 8-hour course |
| Writing Dockerfiles and image optimization | This hour reuses the myapp from the Docker course directly | Docker 8-hour course |
How to use this courseware
Theory · diagrams · animation · commands · lab · production case · troubleshooting · quiz · audio · video. Start with “Theory” and “Animation”, then do the “Lab”.
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).
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.
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
- CompletedLesson 1: organization
https://dev.azure.com/<org>, projectmyapp-lab, and you are a member of Project Administrators; Azure CLI and theazure-devopsextension are installed, and you have runaz 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
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.
Module 1 · Azure Pipelines architecture and how it works
- 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.
What: what Azure Pipelines is made of
- Pipeline: a definition; a YAML pipeline's definition is the
azure-pipelines.ymlin 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/pwshor atask. - 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 pipelines | Classic build / release | |
|---|---|---|
| Where definitions live | In the same repo as the code, goes through PR review, has Git history | Stored on the server, edited in the UI, history only on the server |
| Branch differences | Each 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 governance | Templates (includes/extends), required template checks | Task groups |
| CD capabilities | Multi-stage + Environments + approvals and checks (Lessons 3 and 5) | Classic release pipelines |
| New features | Microsoft'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:
| Phase | Who does it | What it does | What can be used at this point |
|---|---|---|---|
| Compile / expand (compile time) | Azure Pipelines service | Takes 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 dependencies | Only YAML text, parameters and a few predefined variables (such as Build.SourceBranch,Build.Reason). Runtime variables do not exist yet |
| Resource authorization | Service | Before 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 pipeline | Therefore stage/job variables cannot be used to decide service connection or environment names |
| Job scheduling | Service | Selects 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) | agent | Downloads 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 artifacts | Macros $(var) (replaced before the task runs), environment variables, logging commands ##vso[...] |
Three job types
| Type | YAML | Where it runs | Uses a parallel job? | Typical use |
|---|---|---|---|---|
| Agent job | - job: + pool | Agent (on a VM or in a container job) | Yes | Build, test, package |
| Agentless job (server job) | - job: + pool: server | Azure Pipelines server | No | A few server-side tasks such as Delay, ManualValidation, InvokeRESTAPI, and calling an Azure Function |
| Deployment job | - deployment: + environment + strategy | Agent | Yes | Deploys 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 Pipelines | GitHub Actions | GitLab CI | |
|---|---|---|---|
| Definition | azure-pipelines.yml, stages/jobs/steps | .github/workflows/*.yml, jobs/steps | .gitlab-ci.yml, stages/jobs |
| Executor | Agent (hosted / self-hosted / VMSS / Managed DevOps Pools) | Runner | Runner |
| Compile-time expressions | ${{ }} Template expressions | No separate compile time (${{ }} evaluated at runtime) | include/rules |
| Concurrency billing | By parallel jobs | By minutes (private repos) | By compute minutes |
${{ 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
Hierarchy: Run → Stage → Job → Step
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)
| Command | Purpose | Key parameters / notes |
|---|---|---|
az pipelines create | Create a pipeline from a YAML file in the repo | --repository-type tfsgit|github,--yml-path,--skip-first-run |
az pipelines run | Manually queue a run | --branch,--variables k=v (override when queuing is allowed),--parameters k=v |
az pipelines runs list / show | View run status and results | --status,--result,--top,--open |
az pipelines runs artifact list/download | List and download pipeline artifacts | --run-id,--artifact-name,--path |
az pipelines build cancel | Cancel a run | --id |
az devops invoke | Call 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)
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.
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.
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.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.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.
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 table2. 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
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
Official documentation
- Pipeline runs (processing order of a run)
- Key concepts for new Azure Pipelines users
- Specify jobs in your pipeline (agent / agentless jobs)
- Deployment jobs
- Configure and pay for parallel jobs
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.
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.
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.
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.
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.
Module 2 · YAML structure: stage, job, step
- Write a complete
stages → jobs → stepsstructure, and understand how the shorthand (writing onlystepsorjobs) is filled in on the server. - Use
dependsOnto organize serial, fan-out and fan-in flows, and useconditionto control failure notifications, cleanup, and “build only on main”. - Distinguish
taskandscript/bash/pwsh, and knowcheckout's options:fetchDepth,fetchTags,clean,path, and multi-repo checkout.
What: the three-layer structure and common keywords
| Level | Keyword | Common properties | Default behavior |
|---|---|---|---|
| Pipeline | trigger pr schedules resources parameters variables pool stages/jobs/steps | name (run number format, e.g. $(Date:yyyyMMdd)$(Rev:.r)) | Writing only steps makes the server fill in 1 stage + 1 job |
| Stage | - stage: Name | displayName dependsOn condition variables pool jobs | Depends 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 services | Jobs within the same stage are independent and run in parallel by default |
| Step | - script - bash - pwsh - powershell - task - checkout - download - publish - template | displayName name (for output variables) condition env continueOnError timeoutInMinutes retryCountOnTaskFailure workingDirectory | Run 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: AordependsOn: [A, B](fan-in); multiple jobs depending ondependsOn: Ais 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 isand(succeeded(), eq(...)). - In a step,
conditionchecks the status “so far in this job”; on a job or stage, it checks the status of its dependencies.
task vs script
script/bash/pwsh | task: Name@Major | |
|---|---|---|
| Nature | is a shorthand for the CmdLine/Bash/PowerShell tasks | a packaged Node.js/PowerShell program with input validation and a UI form |
| Best for | familiar command lines: pip, pytest, docker | need platform integration: publishing test results, using service connections, caching, artifacts |
| Cross-platform | script cmd on Windows, bash on Linux; bash/pwsh specify the interpreter | is determined by the task itself |
| Version | — | references the major version and automatically gets the latest minor version (Module 7) |
checkout: checkout options and defaults
| Property | Meaning | Default / notes |
|---|---|---|
checkout: self | none | <repo alias> | checks out the current repo / no checkout / checks out a repo declared in resources | Automatic when a regular job does not write checkout checkout: self; deployment jobs do not check out automatically |
fetchDepth | Shallow clone depth | After 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 |
fetchTags | Whether to sync tags | An 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) |
clean | Whether to clean the working directory before checkout | matters for self-hosted agents (hosted agents always use a new VM) |
path | Checks out to $(Agent.BuildDirectory) subdirectory | Default for a single repo s; with multiple repos, each repo is checked out to s/<repo name> |
persistCredentials | Keep the access token for later git commands (e.g. pushing after tagging) | Default false |
submodules / lfs | Submodules (true/recursive) / Git LFS | Not handled by default |
fetchFilter / sparseCheckoutDirectories / sparseCheckoutPatterns | Partial clone (e.g. blob:none) / sparse checkout | requires 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 setfetchDepth: 0.
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
Directory diagram: working directory on the agent (Linux hosted agent)
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.
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)
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)
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.--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.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.
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()
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
No verified dedicated videos on “dependencies and conditions” or “checkout options” were found; the storyboard script is provided below.
Official documentation
- YAML schema reference
- Add stages, dependencies, & conditions
- Pipeline conditions
- steps.checkout definition
- Check out multiple repositories
Video storyboard script (about 80 seconds)
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.
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.
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.
Module 3 · Triggers: CI, PR, schedules and pipeline resources
- 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 usespr:. - Write the correct
schedules(five-field cron,UTC, no daylight saving time), understandalwaysand its relationship to branch versions; know how to useresources.pipelinesso downstream pipelines run automatically after upstream completes.
What: the four trigger types
| Trigger | YAML | Build.Reason | Which branch's YAML is used |
|---|---|---|---|
| CI (push) | trigger: | IndividualCI / BatchedCI | The pushed branch |
| PR | Azure Repos: branch policy Build validation; GitHub: pr: | PullRequest | PR's merge commit (refs/pull/N/merge) |
| Scheduled | schedules: | Schedule | For each branch, the schedule in the YAML on that branch and its branch filters decide |
| Pipeline completion | resources.pipelines[].trigger | ResourceTrigger | see below |
| Manual / API | — | Manual | The branch you choose |
CI trigger rules (Azure Repos Git, verified)
- Implicit trigger: when YAML has no
triggersection, 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: noneTurn 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 Git | GitHub / GitHub Enterprise / Bitbucket Cloud | |
|---|---|---|
| Where it is configured | Target branch's Branch policies → Build validation (the YAML pr: is ignored) | Set in YAML pr: (branch/path filters,autoCancel,drafts) |
| Default | None; must be added manually | YAML pipelines have CI and PR triggers enabled by default |
| Status reporting | policy 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 PRs | do not trigger | drafts: 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: truerun 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.DisplayNameConditions 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:
triggerinclude onlymainandreleases/*, use build validation for PRs, and run a full test nightly (always: trueas 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.
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?
Sequence diagram: Azure Repos PR build validation
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 ] }
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)
azure-pipelines.yml top section with the content below and merge into main.
trigger:
branches: { include: [ main ] }
paths:
exclude: [ docs/*, '*.md' ]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
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.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 trueAfter 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.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.
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: true2. Turn off CI and (GitHub) PR triggers for a pipeline so that it can only be run manually.
trigger: none pr: none
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
No verified video specifically on triggers was found; a storyboard script is provided below.
Official documentation
- Triggers in Azure Pipelines
- Build Azure Repos Git repositories (CI/PR/skip ci/shallow clone)
- Configure schedules to run pipelines
- Trigger one pipeline after another
- Branch policies (Build validation)
Video storyboard script (about 80 seconds)
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.
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.
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.
Module 4 · Agents and agent pools
- Remember the current Microsoft-hosted image labels and specs, and know that
*-latestwill “drift,” and when to pin versions in production. - Understand the relationship between agent pools (organization level) and projects,
demandsand 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.
What: types of agent sources
| Type | Maintained by | Characteristics | Best for |
|---|---|---|---|
| Microsoft-hosted (pool Azure Pipelines) | Microsoft | A fresh VM for each job, destroyed when the job ends; images are updated roughly weekly; no remote login, cannot join corporate networks, cannot increase specs | CI for most open-source and small/medium projects; safer for running untrusted code (such as fork PRs) |
| Self-hosted | You | any machine, spec, or network; caches and Docker layers can be kept, so it may be faster; you must handle patching, cleanup, and isolation | Needs internal network access, special hardware (GPU), large disks, or fixed software versions |
| VMSS agent pool | You (Azure scaling) | Azure Virtual Machine Scale Sets scale on demand and can be rebuilt after each job | Elastic self-hosted needs |
| Managed DevOps Pools | Microsoft-managed infrastructure + your configuration | choice of specs, images, VNet injection, standby agents | Enterprise managed pools (Lesson 7) |
Microsoft-hosted images (verified 2026-11-15)
YAML vmImage | Actual image | Status / notes |
|---|---|---|
ubuntu-latest or ubuntu-24.04 | Ubuntu 24.04 | Used when YAML specifies no pool or image: default image |
ubuntu-26.04 | Ubuntu 26.04 | 2026-09-29 GA |
ubuntu-22.04 | Ubuntu 22.04 | Deprecated, scheduled for removal on 2027-04-17 (there were brownouts earlier); migrate as soon as possible |
windows-latest or windows-2025 | Windows Server 2025 + Visual Studio 2022 | officially announced for the coming weeks windows-latest will point to windows-2025-vs2026 |
windows-2025-vs2026 | Windows Server 2025 + Visual Studio 2026 | 2026-09-29 GA |
windows-2022 | Windows Server 2022 + VS 2022 | available (Windows 2019 was retired on 2025-12-31) |
macOS-latest or macOS-15 | macOS 15 Sequoia | macOS agents always run in the US |
macOS-26 / macOS-14 | macOS 26 Tahoe / macOS 14 Sonoma | macOS 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
| Requirement | Choice |
|---|---|
| Standard Linux/Windows/macOS builds with no internal network dependencies | Hosted ubuntu-latest (production pipelines can pin ubuntu-24.04 to avoid latest drift) |
| Needs access to databases or artifact repositories on a private network | Self-hosted / VMSS / Managed DevOps Pools (VNet) |
| Needs GPU, very large memory, or disks over 10 GB | Self-hosted or Managed DevOps Pools |
| Public repositories, fork PRs | Hosted agents (do not run untrusted code on your internal machines) |
| Tool versions must be pinned exactly | Container jobs (container:) or self-hosted |
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
Comparison diagram: job lifecycle for hosted vs. self-hosted
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.
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)
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.”
lab-agent-01 to Default pool. Confirm it shows as Online under Agent pools → Default → Agents, and find the following in Capabilities: docker.- 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.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 tableFix: 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.
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 -qThe 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
No verified video on “self-hosted agent registration” was found; a storyboard script is provided below.
Official documentation
- Microsoft-hosted agents
- Microsoft-hosted image deprecation schedule
- Azure Pipelines agents (capabilities)
- Self-hosted Linux agents
- Container jobs
Video storyboard script (about 80 seconds)
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.
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.
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.
Module 5 · Variables, variable groups, and expressions
- 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 viadependencies/stageDependencies; be familiar with common predefined variables and runtime parameters.
What: where variables come from
| Source | How it is defined | Notes |
|---|---|---|
| YAML variables | Root / stage / job variables: | — the closer the scope, the higher the priority: job > stage > root > pipeline settings UI |
| UI variables | Pipeline Edit → Variables | can be set as secret and ticked Let users override this value when running this pipeline(overridable when queued) |
| Variable groups | Pipelines → Library; in YAML, - group: name | shared by multiple pipelines; can be linked to Azure Key Vault; a protected resource that requires authorization |
| Variable templates | - template: vars.yml | inlined at compile time (Module 7) |
| Set in script | ##vso[task.setvariable variable=x]value | Available from the next step onward; add isOutput=true so it can cross jobs/stages. |
| Predefined variables | Provided by the system: | Build.*,System.*,Agent.*,Pipeline.* |
How: three syntaxes (official comparison table)
| Syntax | Example | When processed | Where it can appear | If not found |
|---|---|---|---|---|
| Macro | $(var) | Runtime,before each task runs Replaces | values (right side) | Left as-is $(var) (in bash, this is treated as command substitution!) |
| Template expression | ${{ variables.var }} / ${{ variables['var'] }} | compile time | keys or values (either side) | empty string |
| Runtime expression | $[ variables.var ] | runtime (when a stage/job starts) | values, and must fill the entire right-hand side | empty string |
- Macros: most commonly used; suited to task inputs and scripts. Note that macros inside
displayNameare 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=trueset 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 consumed | Set by | How 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 job | Same as above, job A | job B dependsOn: A,variables: { tag: $[ dependencies.A.outputs['meta.tag'] ] } |
| Jobs in a downstream stage | Same as above, stage S1 job A | stage S2 dependsOn: S1, job variables $[ stageDependencies.S1.A.outputs['meta.tag'] ] |
| Conditions in a downstream stage | Same as above | condition: 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 | |
|---|---|---|
| Type | Typed (string/number/boolean/object…), can be restricted values | Always strings |
| Evaluated | At compile time, can be used to ${{ if }} change structure | Mostly at runtime |
| UI | Shown as a form in the run dialog | Must tick “Allow override when queued” |
| Recommended | When users need to choose at run time (e.g., whether to run the full test suite) | Configuration values, secrets, passing values between steps |
${{ }} ” — 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
Data flow: output variables across stages
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
| Reference | Compile time | Job start | Before step 2 runs | Script 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
| Variable | Example value / meaning |
|---|---|
Build.Reason | IndividualCI, BatchedCI, PullRequest, Schedule, Manual, ResourceTrigger |
Build.SourceBranch / Build.SourceBranchName | refs/heads/main / main (for PR: refs/pull/7/merge / merge) |
System.PullRequest.SourceBranch / TargetBranch / PullRequestId | only has a value during PR runs |
Build.SourceVersion / Build.BuildId / Build.BuildNumber | commit SHA / run ID (integer) / run number (determined by name: ) |
Pipeline.Workspace / Build.SourcesDirectory / Build.ArtifactStagingDirectory | see Module 2, Figure 2-2 |
Agent.OS / Agent.TempDirectory | Linux / Windows_NT / Darwin; temp directory (cleaned up after the job) |
System.AccessToken | job access token (representing the project's Build Service identity),requires explicit env mapping |
System.Debug | when set to true, outputs diagnostic logs (a great troubleshooting tool) |
Lab 5: image tag variable + cross-stage value passing + secrets (about 8 minutes)
--authorize false).- 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.
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
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.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.
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') ]
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
- Define variables (three-syntax comparison table)
- Set variables in scripts (output variables)
- Set secret variables
- Variable groups
- Predefined variables
- Runtime parameters
Video storyboard script (about 90 seconds)
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.
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.”
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.
Module 6 · Pipeline artifacts and caching
- 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@2to cache pip dependencies, design a key that includes a lock-file hash, andrestoreKeysfallbacks, 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.”
What: artifacts vs. caching
| Pipeline artifacts | Pipeline caching | |
|---|---|---|
| Purpose | Pass 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) |
| Identifier | Unique per run: artifact name | key (string + file hash) |
| Mutability | Artifacts with the same name cannot be published twice in the same run | Cache Immutable: once a key is created in a scope, it is never updated |
| Lifetime | Retained with the run (follows the project's run retention policy) | 7 days without access expires; manual deletion is not supported (just change the key) |
| Cost | Official: artifacts and caches are free on all tiers (for rules on counting toward Artifacts storage, see the official documentation) | |
| Task | PublishPipelineArtifact@1 / DownloadPipelineArtifact@2, shortcut keyword publish / download | Cache@2 (automatically appends a Post-job: Cache step at job end to save the cache) |
How: artifacts
- publish: <path>+artifact: <name>is equivalent toPublishPipelineArtifact@1. You can place.artifactignorein the directory to exclude files.- download: current(this run) or- download: <pipeline resource alias>(upstream pipeline, Module 3); you can addartifact:andpatterns:. 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: noneif 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
- When the Cache@2 step runs, it uses
keyto look in the “scopes visible to this job” for an exact match; if found → download and extract topath(cacheHitVar=true). - If not found, use
restoreKeysin order from top to bottom for prefix matching, taking the most recently created match (cacheHitVar=inexact); if none →false. - Subsequent steps run normally (pip install uses the restored cache directory).
- Job all steps succeed, the automatic Post-job: Cache step runs when there is no exact match and packages
pathand uploads it to this run's job scope.
Key composition
- Separated by
|segments: string (such aspython,"$(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 type | Readable | Writable |
|---|---|---|
| CI / manual / scheduled | source branch,main,master | source branch |
| PR | source branch, target branch, intermediate branch refs/pull/N/merge, main, master | Write only: refs/pull/N/merge |
| Fork PR | target branch, intermediate branch, main, master | intermediate 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 use | Use | Why |
|---|---|---|
| Dependencies downloaded by pip/npm/Maven | Cache | Can be re-downloaded if missing |
| Test reports, code coverage | PublishTestResults / artifact | Needs to be shown or archived in the UI |
| Built wheel, image tar, Helm chart | Artifact (or pushed to Azure Artifacts/ACR) | The deploy stage must get the same output (“build once, deploy many”) |
| Docker layer cache | Cache (buildx type=local) or registry cache | Speeds things up, not required |
Data flow: artifacts moving between jobs
Timing: Cache@2 restore and save
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.
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)
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
- script: |
docker save myapp:$(Build.BuildId) | gzip > $(Build.ArtifactStagingDirectory)/myapp.tar.gz
ls -lh $(Build.ArtifactStagingDirectory)
displayName: Export image
- publish: $(Build.ArtifactStagingDirectory)
artifact: image- 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
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.
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 ci2. From upstream pipeline resource ci , download the artifact named image .
- download: ci artifact: image
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
- Publish and download pipeline artifacts
- Pipeline caching (scopes, keys, 7-day expiry)
- Cache@2 task
- steps.download definition
Video storyboard script (about 80 seconds)
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.
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.
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.
Module 7 · Templates and tasks (tasks)
- 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 themref. - Understand tasks
Name@major versionversion rules, and the installation and governance of Marketplace extensions.
What: two types of templates
| Includes (insert) templates | Extends (inherit) templates | |
|---|---|---|
| Purpose | Inserts a block of steps/jobs/stages/variables at the reference point, like #include | The 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: … } |
| Use | Reuse (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.repositoriesintype: gitfor Azure Repos,name: project/repo;type: githuba service connection is needed), and reference them withpath.yml@alias. Omittingrefdefaults torefs/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)
| Type | Description |
|---|---|
string | String, can use values: to restrict values |
stringList | Multi-select string list (not available in templates, use object) |
number / boolean | Number (can restrict with values) / true, false |
object | Any YAML structure (lists, mappings) |
step / stepList | Single step / step sequence |
job / jobList,deployment / deploymentList,stage / stageList | Job, 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 exampleUsePythonVersion@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
scriptcommand 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.
$(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
Task version resolution
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.
(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)
templates/python-setup.yml and templates/python-test.yml (see the “Commands” tab for the content).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).
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.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.
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@sharedThe 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
- Templates (limits, reference paths, other repositories)
- Template parameters (parameter types)
- Template expressions (each / if)
- Task types & usage (task versions)
- Install extensions
Video storyboard script (about 75 seconds)
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.
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.
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.
Module 8 · CI readiness review and common failures
- 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.
What: CI readiness review checklist
| # | Check item | Why | Related module |
|---|---|---|---|
| 1 | YAML lives in the repository; changes are reviewed through PRs | Traceable and reversible | M1 |
| 2 | The target branch has a required build validation policy (Azure Repos), with path filters consistent with the YAML | Bad code can't get into main | M3 |
| 3 | trigger explicitly lists branches instead of relying on implicit triggers; documentation-only changes don't run CI | Saves parallel jobs | M3 |
| 4 | Fast first, slow later: lint → unit tests → build; custom conditions include succeeded() | fail fast and don't publish by mistake | M2 |
| 5 | Pin the image version (for example ubuntu-24.04), with sensible job settings timeoutInMinutes | reproducible, prevents hangs | M4 |
| 6 | Dependency cache key includes a lock file hash + restoreKeys | Fast and correct | M6 |
| 7 | Upload test results with PublishTestResults (succeededOrFailed()) | Shows which test failed when it fails | M0/M6 |
| 8 | Build outputs are passed as artifacts, “build once” | deploys exactly what was tested | M6 |
| 9 | Secrets are not in YAML; use variable groups/Key Vault, and scripts access them via env: mapping | to prevent leaks | M5 |
| 10 | Extract repeated steps into templates; pin shared templates ref | Consistency, controlled upgrades | M7 |
| 11 | Checkout parameters are explicit (fetchDepth/fetchTags) | Not affected by UI default values | M2 |
| 12 | Resources (pools, variable groups, service connections, repositories) are authorized per pipeline, not “open to all pipelines” | Least privilege | M1/M5 |
How: locate failures by lifecycle
| Symptom | Stuck at which step | Check first |
|---|---|---|
| No run at all after a push/PR | Trigger | Triggers UI override, branch/path filters, [skip ci], branch policies |
| Run fails within seconds, no jobs | Compile / resource authorization | Error at the top of the run summary; download the expanded YAML |
| Stuck in Queued | Parallel job gate / agent | Parallel jobs page, agent status in the pool, demands |
| A step is red | Runtime | That step's log; system.debug=true |
| All steps green but the result is wrong | Variables / conditions / cache | Skip 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.
Failure map: where common errors fall in the lifecycle
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.
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)
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.$(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.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.| $(Build.BuildId), run twice in a row; both are misses. After removing it, hits are restored.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.
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 table2. Re-queue myapp-ci on main in diagnostic mode.
az pipelines run --name myapp-ci --branch main --variables system.debug=true
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
No verified video on “Azure Pipelines troubleshooting” was found, so the storyboard script below is provided instead.
Official documentation
- Troubleshoot pipeline runs
- Troubleshoot pipeline triggers
- Review logs to diagnose pipeline issues
- Job access tokens
- Resource authorization
Video storyboard script (about 90 seconds)
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.
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.
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.
Command cheat sheet
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 mappedAgents
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 jobArtifacts 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 / falseTemplates
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 MBMatrix 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:6379Variable 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
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).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.
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.
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
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.az repos pr create --source-branch feature/full-ci --target-branch main --title "Full CI" --openIn 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.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
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.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
| Topic | Verified conclusion | Source (accessed 2026-11-15) |
|---|---|---|
| Run processing order | Expand 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 variables | Pipeline runs(page updated 2026-05) |
| Microsoft-hosted images | ubuntu-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-latest | Microsoft-hosted agents(page updated 2026-11-09) |
| Parallel jobs and free tier | Hosted 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 jobs | Configure and pay for parallel jobs(page updated 2026-11-03) |
| CI/PR triggers and checkout | Implicit 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-05 | Build Azure Repos Git repositories(page updated 2026-08-07) |
| Scheduled triggers | cron 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.DisplayName | Configure schedules(page updated 2026-11-03) |
| Variables | Comparison 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 default | Define variables(page updated 2026-09-17) |
| Output variables | isOutput/isSecret/isReadOnly; dependencies.A.outputs['step.var'],stageDependencies.S.A.outputs['step.var']; only direct dependencies can read them; deployment job syntax differs | Set variables in scripts |
| Cache | Cache@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 supported | Pipeline caching(page updated 2026-05) |
| Templates | Limits 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 used | Templates(page updated 2026-06-22) |
| Template parameter types | string, 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 strings | Template parameters(page updated 2025-12-19) |
| ADO_HELM_SPEC verified facts | Shallow 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-latestrepointed towindows-2025-vs2026The 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.