Hướng Dẫn Azure DevOps CI/CD Pipelines: YAML Multi-Stage Pipeline Toàn Diện
Hướng dẫn toàn diện Azure DevOps Pipelines — YAML multi-stage, triggers, agents, environments, approval gates và secrets management cho doanh nghiệp.
Azure Pipelines là CI/CD platform cho build, test, deploy — support mọi language (.NET, Java, Node.js, Python, Go) và mọi target (Azure, AWS, GCP, on-prem, Kubernetes). YAML-based pipelines (Infrastructure-as-Code), multi-stage (build → test → staging → production), approval gates, environment protection rules. Auth qua Microsoft Entra ID, secrets management qua Azure Key Vault, audit qua Microsoft Purview. Admin quản lý agent pools, service connections, security policies qua Azure DevOps Organization Settings. Free tier: 1,800 CI/CD minutes/month.
TL;DR: Azure Pipelines dùng YAML pipelines (pipeline-as-code) với multi-stage deployment: build → test → staging (approval) → production (approval + business hours). Agents có 3 loại: Microsoft-hosted (1,800 min/month free), self-hosted (unlimited), scale set (auto-scaling). Secrets quản lý qua Azure Key Vault, environments có approval gates + branch control + exclusive locks. Templates cho phép reuse pipeline code across projects.
Bạn cần tư vấn thiết kế CI/CD pipeline chuyên nghiệp cho doanh nghiệp? Liên hệ PUPAM ngay để được hỗ trợ từ đội ngũ chuyên gia DevOps.
Pipeline Types
| Type | Definition | Version Control | Recommended |
|---|---|---|---|
| YAML Pipelines | Code (azure-pipelines.yml) | ✅ Git tracked | ✅ Yes |
| Classic Editor | GUI click-based | ❌ Not in Git | Legacy only |
| Release Pipelines | GUI for deployments | ❌ Not in Git | Migrating to YAML |
YAML vs Classic — So Sánh Chi Tiết
YAML Pipelines (recommended):
- Pipeline-as-code — reviewed trong Pull Requests
- Version controlled — full git history
- Branching — different pipeline configuration per branch
- Templates — reusable across projects và organizations
- Multi-stage — build + deploy trong 1 file YAML
- YAML schema validation với IDE support (VS Code extension)
Classic Editor (legacy):
- GUI dễ dùng cho beginners
- Không version controlled, không branching support
- Khó review changes, không template reuse
- Chỉ dùng cho quick prototype → sau đó migrate sang YAML
YAML Pipeline Structure
Ví dụ multi-stage YAML pipeline hoàn chỉnh cho .NET project:
# azure-pipelines.yml
trigger:
branches:
include:
- main
- release/*
pool:
vmImage: 'ubuntu-latest'
variables:
buildConfiguration: 'Release'
dotnetVersion: '8.0.x'
stages:
- stage: Build
displayName: 'Build & Test'
jobs:
- job: BuildJob
steps:
- task: UseDotNet@2
inputs:
version: $(dotnetVersion)
- script: dotnet restore
displayName: 'Restore packages'
- script: dotnet build --configuration $(buildConfiguration)
displayName: 'Build project'
- script: dotnet test --configuration $(buildConfiguration)
displayName: 'Run tests'
- task: PublishBuildArtifacts@1
inputs:
pathToPublish: '$(Build.ArtifactStagingDirectory)'
artifactName: 'drop'
- stage: Deploy_Staging
displayName: 'Deploy to Staging'
dependsOn: Build
condition: succeeded()
jobs:
- deployment: DeployStaging
environment: 'staging'
strategy:
runOnce:
deploy:
steps:
- task: AzureWebApp@1
inputs:
azureSubscription: 'My-Azure-Connection'
appName: 'myapp-staging'
package: '$(Pipeline.Workspace)/drop'
- stage: Deploy_Production
displayName: 'Deploy to Production'
dependsOn: Deploy_Staging
condition: succeeded()
jobs:
- deployment: DeployProd
environment: 'production'
strategy:
runOnce:
deploy:
steps:
- task: AzureWebApp@1
inputs:
azureSubscription: 'My-Azure-Connection'
appName: 'myapp-production'
package: '$(Pipeline.Workspace)/drop'
Triggers
| Trigger Type | Khi Nào | Configuration |
|---|---|---|
| CI trigger | Push to branch | branches: include/exclude |
| PR trigger | Pull request created/updated | pr: branches |
| Scheduled | Cron schedule | schedules: - cron: |
| Pipeline trigger | Another pipeline completes | resources: pipelines |
| Manual | Click "Run pipeline" | trigger: none |
Ví Dụ Các Loại Trigger
CI trigger — auto-build khi push code:
trigger:
branches:
include: [main, develop, release/*]
exclude: [feature/experimental/*]
paths:
include: [src/**, tests/**]
exclude: [docs/**, README.md]
PR trigger — auto-build khi tạo/update Pull Request:
pr:
branches:
include: [main, develop]
paths:
include: [src/**]
Scheduled trigger — nightly build lúc 2:00 AM:
schedules:
- cron: '0 2 * * *'
displayName: 'Nightly build 2 AM'
branches:
include: [main]
always: true
Pipeline trigger — deploy sau khi build pipeline hoàn thành:
resources:
pipelines:
- pipeline: buildPipeline
source: 'My-Build-Pipeline'
trigger:
branches:
include: [main]
Batch trigger — gộp nhiều pushes trong thời gian ngắn thành 1 build:
trigger:
batch: true
branches:
include: [main]
Agents
| Agent Type | Hosted By | OS | Free Minutes | Use Case |
|---|---|---|---|---|
| Microsoft-hosted | Microsoft | Ubuntu/Windows/macOS | 1,800/month | Most projects |
| Self-hosted | Your infra | Any | Unlimited | Enterprise, special needs |
| Scale set | Your Azure VMs | Any | Pay per use | Auto-scaling |
Microsoft-Hosted Agents
Available images: ubuntu-latest (Ubuntu 22.04 — phổ biến nhất), windows-latest (Windows Server 2022), macos-latest (macOS 14), và specific versions (ubuntu-20.04, windows-2019).
Pre-installed tools: .NET SDK, Node.js, Python, Java, Go, Docker, kubectl, helm, Azure CLI, AWS CLI, gcloud, Git, Maven, Gradle, npm, yarn.
Limitations:
- 6 hours max per job
- 10 GB storage
- Fresh VM per job (không cache giữa các runs)
- 1,800 free minutes/month (public repos: unlimited)
Self-Hosted Agents
Setup chỉ mất 10 phút:
- Organization Settings → Agent pools → + New pool
- Download agent package (Windows/Linux/macOS)
- Configure:
./config.sh --url https://dev.azure.com/org --auth PAT - Run:
./run.sh(interactive) hoặc install as service
Khi nào dùng self-hosted:
- Cần specific hardware (GPU, high RAM)
- Access on-prem resources (databases, file shares)
- Compliance — data không được rời network
- Faster builds — persistent cache, faster disk
- Cost optimization — own VMs = không giới hạn minutes
# Self-hosted pool
pool:
name: 'MyPool'
# Microsoft-hosted
pool:
vmImage: 'ubuntu-latest'
Variables & Secrets
Các Loại Variables
1. Pipeline variables (inline trong YAML):
variables:
buildConfig: 'Release'
appName: 'myapp'
2. Variable groups (shared across pipelines):
Vào Pipelines → Library → Variable groups → tạo group. Reference trong YAML:
variables:
- group: 'production-vars'
3. Azure Key Vault integration:
Pipelines → Library → Variable groups → Link to Key Vault. Secrets auto-fetched at runtime, values masked in logs.
4. Runtime parameters:
parameters:
- name: environment
displayName: 'Deploy to'
type: string
default: 'staging'
values: ['staging', 'production']
Secret Management Best Practices
- NEVER hardcode secrets trong YAML file
- Dùng Variable groups linked to Azure Key Vault
- Mark sensitive variables as "secret" (masked in logs, không export được)
- Scope secrets to specific environments (staging secrets ≠ production secrets)
- Rotate secrets regularly — Key Vault hỗ trợ auto-rotation
- Admin audit secret access qua Microsoft Defender for Key Vault
📌 Cần hỗ trợ thiết kế CI/CD pipeline và secrets management cho doanh nghiệp? Đội ngũ PUPAM chuyên cấu hình Azure Pipelines, Key Vault integration, approval gates và self-hosted agents. Liên hệ →
Environments & Approvals
| Environment | Protection | Approvals | Use Case |
|---|---|---|---|
| Development | None | None | Auto-deploy |
| Staging | Basic | 1 approver | QA/Testing |
| Production | Strict | 2 approvers + business hours | Live deployment |
Thiết Lập Environment
- Vào Pipelines → Environments → + New Environment
- Đặt tên (ví dụ: "production")
- Chọn Resource: Kubernetes, VMs, hoặc none
Approval & Protection Checks
Approval gate:
- Add check → Approvals → chọn approvers (lead-dev, PM)
- All must approve (hoặc any 1 of N)
- Timeout: 72 hours
- Instructions: "Review staging test results before approving"
Business hours gate:
- Add check → Business Hours → Mon-Fri, 9 AM – 5 PM (UTC+7)
- Không cho phép deployment ngoài giờ làm việc
Branch control:
- Add check → Branch control → chỉ cho phép deploy từ branch "main"
- Ngăn feature branches deploy lên production
Exclusive lock:
- Add check → Exclusive lock → chỉ 1 deployment tại một thời điểm
- Queue mode: đợi deployment hiện tại hoàn thành
# Environment reference trong YAML — triggers approval tự động
jobs:
- deployment: DeployProd
environment: 'production'
strategy:
runOnce:
deploy:
steps: ...
Templates (Reusable)
Pipeline templates giúp DRY (Don't Repeat Yourself) — tái sử dụng pipeline code across projects.
Step Template
# templates/build-dotnet.yml
parameters:
- name: dotnetVersion
default: '8.0.x'
- name: projects
default: '**/*.csproj'
steps:
- task: UseDotNet@2
inputs:
version: ${{ parameters.dotnetVersion }}
- script: dotnet restore ${{ parameters.projects }}
- script: dotnet build ${{ parameters.projects }} -c Release
- script: dotnet test ${{ parameters.projects }} -c Release
Job Template
# templates/deploy-webapp.yml
parameters:
- name: environment
- name: appName
- name: azureSubscription
jobs:
- deployment: Deploy
environment: ${{ parameters.environment }}
strategy:
runOnce:
deploy:
steps:
- task: AzureWebApp@1
inputs:
azureSubscription: ${{ parameters.azureSubscription }}
appName: ${{ parameters.appName }}
package: '$(Pipeline.Workspace)/drop'
Main Pipeline Sử Dụng Templates
stages:
- stage: Build
jobs:
- job: Build
steps:
- template: templates/build-dotnet.yml
parameters:
dotnetVersion: '8.0.x'
- stage: DeployStaging
jobs:
- template: templates/deploy-webapp.yml
parameters:
environment: 'staging'
appName: 'myapp-staging'
azureSubscription: 'Azure-Connection'
- stage: DeployProd
jobs:
- template: templates/deploy-webapp.yml
parameters:
environment: 'production'
appName: 'myapp-prod'
azureSubscription: 'Azure-Connection'
Template Repository (Shared Across Projects)
resources:
repositories:
- repository: templates
type: git
name: 'SharedProject/pipeline-templates'
ref: refs/heads/main
stages:
- template: stages/dotnet-cicd.yml@templates
Checklist CI/CD Pipeline
- Tạo
azure-pipelines.ymlở repo root với CI triggers (branches, paths) và build steps (restore, build, test, publish artifacts) - Tạo environments (dev, staging, production) với approval gates và branch control cho staging/production
- Cấu hình service connections (Azure subscription) và variable groups linked to Azure Key Vault cho secrets
- Tạo pipeline templates (build, deploy) để reuse across projects và teams
- Thiết lập branch policies: require PR, build validation, minimum reviewers
- Setup notifications cho build failures và deployment status changes
- Monitor pipeline analytics (duration, pass rate, flaky tests) và optimize slow stages
- Document pipeline architecture cho team và review security settings (agent pools, secret scoping)
FAQ — Câu Hỏi Thường Gặp
Azure Pipelines vs GitHub Actions — khi nào dùng gì?
Azure Pipelines cho Azure DevOps ecosystem, GitHub Actions cho GitHub-native workflow. Azure Pipelines: multi-stage YAML, environments with approval gates, integration với Boards/Repos/Test Plans, agent pools (self-hosted), template repositories across orgs — phù hợp enterprise CI/CD. GitHub Actions: simpler YAML, marketplace (15,000+ actions), tight GitHub integration (PR checks, issue ops), free cho public repos. Cost: Azure Pipelines 1,800 min/month free → $40/parallel job; GitHub Actions 2,000 min/month free → $0.008/min.
Self-hosted agent có khó setup không?
Không — download agent, chạy config script, 10 phút là xong. Organization Settings → Agent pools → New pool → download agent package. Chạy: ./config.sh --url https://dev.azure.com/org --auth PAT → nhập Personal Access Token → done. Run as service: sudo ./svc.sh install && sudo ./svc.sh start. Hardware recommended: 4 vCPU, 8 GB RAM, 100 GB SSD. Docker agent: dùng Microsoft-published Docker image, run on Kubernetes (auto-scale). Agent chỉ pull jobs — không cần inbound firewall rules, chỉ cần outbound HTTPS.
Pipeline secrets có an toàn không?
An toàn — secrets encrypted at rest, masked in logs, scoped to environments. Variable groups: mark variable as "secret" → giá trị encrypted, không hiển thị trong logs. Azure Key Vault integration: secrets stored trong Key Vault (FIPS 140-2 Level 2 HSM), pipeline fetches at runtime, auto-rotation support. Secret scope: lock variable group to specific pipeline/environment — staging secrets khác production secrets. Audit qua Microsoft Purview logs all secret access.
Multi-stage pipeline có support rollback không?
Có — dùng deployment strategy (canary, blue-green) hoặc manual re-deploy previous version. Rollback approaches: (1) Re-run previous successful deployment (Pipelines → Runs → select previous → Rerun stage), (2) Blue-green: swap deployment slot back (App Service slots), (3) Canary: auto-rollback nếu health check fails. YAML canary: strategy: canary: increments: [10, 50, 100] — deploy 10% → check → 50% → check → 100%. Admin monitor deployments qua environment deployment history — full audit trail with Microsoft Entra ID user identity.
Pipeline analytics có gì hữu ích?
Pipeline analytics hiển thị build duration, pass rate, failure trends — giúp optimize CI/CD liên tục. Vào Pipelines → Analytics: pass rate by stage (target >95%), average duration trend, failure analysis (stages/tests fail nhiều nhất), wait time (queue time trước khi agent pick up job), flaky test detection. Optimization: slow builds → thêm caching (NuGet, npm, Docker layers), parallel jobs, self-hosted agents. Flaky tests → quarantine → fix → re-enable.
Free tier của Azure Pipelines bao gồm những gì?
1,800 CI/CD minutes/month với 1 parallel job cho private repos. Public repos được unlimited minutes miễn phí. Mỗi parallel job thêm: $40/tháng (Microsoft-hosted) hoặc $15/tháng (self-hosted). Free tier đủ cho team nhỏ (2–5 developers) với builds không quá phức tạp. Nếu cần nhiều hơn: self-hosted agents trên own infrastructure = unlimited minutes, chỉ trả $15/tháng per parallel job. Stakeholders (view-only) không cần license riêng.
Nguồn Tham Khảo
- Microsoft Azure Pipelines — Official Docs
- YAML Pipeline Schema Reference
- Azure Pipelines Templates
- Workload Identity Federation for Pipelines
- DORA CI/CD Best Practices
- OWASP DevSecOps Guideline
- Azure Pipelines Pricing
Hành Động Ngay Hôm Nay
- Tạo YAML pipeline đầu tiên: Thêm file
azure-pipelines.ymlvào repo root với stages build → test → staging (approval gate) → production (approval + business hours) - Migrate secrets sang Azure Key Vault: Tạo variable group linked to Key Vault, enable Workload Identity Federation để loại bỏ stored credentials, scope secrets theo environment
- Thiết lập environment protection: Tạo 3 environments (dev, staging, production), thêm approval gates + branch control + exclusive locks cho staging/production
Bài Liên Quan
- Azure DevOps Boards Work Tracking
- Azure App Service Web Apps Hosting
- Azure AD Managed Identities Azure Resources
- Azure AD Tenant Creation Best Practices
- Microsoft 365 Security Best Practices
Kết Luận
| Khía Cạnh | Best Practice | Chi Tiết |
|---|---|---|
| Pipeline-as-Code | YAML multi-stage với templates | Version controlled, reviewable trong PRs, reusable across projects |
| Security | Key Vault + approval gates + branch control | Secrets encrypted/masked, environment protection rules, audit trail |
| Performance | Microsoft-hosted hoặc self-hosted agents | 1,800 min/month free, self-hosted cho persistent cache và unlimited builds |
Azure Pipelines là enterprise-grade CI/CD platform. YAML pipelines (Infrastructure-as-Code) — version controlled, reviewable, template-able. Multi-stage: build → test → staging (approval) → production (approval + business hours). Environments với protection rules: approvals, branch control, business hours, exclusive locks. Agent flexibility: Microsoft-hosted (zero maintenance) hoặc self-hosted (own infra). Secrets management qua Azure Key Vault — encrypted, masked, scoped. Free tier: 1,800 min/month cho 1 parallel job. Đối với doanh nghiệp Việt Nam triển khai DevOps lần đầu, Azure Pipelines với prebuilt tasks cho AWS, GCP, Docker, Kubernetes giúp rút ngắn thời gian setup từ tuần xuống ngày.
Cần triển khai Azure DevOps CI/CD pipelines cho doanh nghiệp? Liên hệ PUPAM — đội ngũ chuyên gia hỗ trợ thiết kế multi-stage pipeline, approval gates, secrets management, self-hosted agents và DevSecOps integration.