AzureIntermediate

Azure DevOps Pipeline: Complete CI/CD Implementation Guide

DevHub Team
9 min read

TL;DR

A comprehensive guide to implementing CI/CD pipelines using Azure DevOps, including best practices, templates, and advanced deployment strategies

Azure DevOps Pipeline: Complete CI/CD Implementation Guide

Executive Summary

An Azure DevOps pipeline earns its keep when it is the only path to production and everyone trusts what it produces. This guide covers building that pipeline in YAML: a build stage that restores, compiles, tests, and publishes a versioned artifact; deployment jobs that promote the same artifact through environments with approvals and checks; slot-based blue-green releases for App Service; and security scanning wired in as a gate rather than an afterthought. After reading it you will be able to structure a multi-stage pipeline with templates and variable groups that stays maintainable as the number of services grows.

Why This Matters

Pipelines fail organisations in two ways. The first is absence: deployments by hand from a developer machine, unrepeatable and unaudited, where "what is running in production" has no certain answer. The second is decay: a pipeline exists but is slow, flaky, or routinely bypassed, so the team routes around it and the official path becomes fiction. Both end the same way — a bad release with no clean rollback and no record of what changed. A pipeline is a production system in its own right; it needs the same care with reliability, security, and observability as the software it ships.

Core Concepts

The Pipeline Model

Azure Pipelines is a hierarchy: a stage groups jobs; a job runs on one agent and executes steps (tasks or scripts) in order. Stages run sequentially by default and form the promotion path — Build, then Deploy to Dev, then Staging, then Production. Deployment jobs are a special job type that target an environment, which is where approvals, checks, and deployment history attach. Environments are the control point: a production environment can require manual approval, business-hours windows, and checks against external systems before any deployment job targeting it may run.

A Build Pipeline That Produces One Artifact

The build stage's job is to produce a single, versioned artifact that every later stage deploys unchanged. Rebuilding per environment destroys the property that what you tested is what you shipped.

# azure-pipelines.yml
trigger:
  branches:
    include:
      - main
      - develop
  paths:
    exclude:
      - docs/*
      - '*.md'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

stages:
- stage: Build
  jobs:
  - job: BuildJob
    pool:
      vmImage: 'ubuntu-latest'
    steps:
    - task: DotNetCoreCLI@2
      inputs:
        command: 'restore'
        projects: '$(solution)'

    - task: DotNetCoreCLI@2
      inputs:
        command: 'build'
        projects: '$(solution)'
        arguments: '--configuration $(buildConfiguration)'

    - task: DotNetCoreCLI@2
      inputs:
        command: 'test'
        projects: '**/*Tests/*.csproj'
        arguments: '--configuration $(buildConfiguration)'

    - task: DotNetCoreCLI@2
      inputs:
        command: 'publish'
        publishWebProjects: true
        arguments: '--configuration $(buildConfiguration) --output $(Build.ArtifactStagingDirectory)'

    - task: PublishBuildArtifacts@1
      inputs:
        pathtoPublish: '$(Build.ArtifactStagingDirectory)'
        artifactName: 'drop'

Note the trigger hygiene: path filters keep documentation changes from burning agent minutes, and tests run in the build stage so a failing test blocks the artifact, not the deployment.

Container Builds

For containerised workloads the artifact is an image, tagged with the build ID so every deployment is traceable to a commit and a pipeline run:

# container-pipeline.yml
trigger:
  branches:
    include:
      - main

variables:
  dockerRegistry: 'myregistry.azurecr.io'
  imageName: 'myapp'
  tag: '$(Build.BuildId)'

stages:
- stage: Build
  jobs:
  - job: BuildJob
    pool:
      vmImage: 'ubuntu-latest'
    steps:
    - task: Docker@2
      inputs:
        containerRegistry: 'ACR'
        repository: '$(imageName)'
        command: 'buildAndPush'
        Dockerfile: '**/Dockerfile'
        tags: |
          $(tag)
          latest

Tag with the build ID (or commit SHA) and deploy by that immutable tag; treat latest as a convenience for humans, never as a deployment reference.

Environments and Deployment Jobs

EnvironmentApprovalStrategy
DevelopmentNone — automatic on build successDirect deployment
StagingTeam lead or automatic with checksBlue-green via deployment slots
ProductionNamed approvers, business-hours checkSlot swap after staging validation, or canary where the platform supports traffic splitting

A deployment job declares its environment and strategy. For App Service, the blue-green pattern is: deploy the artifact to the staging slot, run smoke tests against it, swap slots so staging becomes production, then watch health signals — with the previous version still warm in the now-staging slot for an instant swap-back:

# deployment-strategies.yml
stages:
- stage: Deploy
  jobs:
  - deployment: DeployStagingSlot
    environment: staging
    strategy:
      runOnce:
        deploy:
          steps:
          - task: AzureWebApp@1
            inputs:
              azureSubscription: 'Azure'
              appName: '$(webAppName)'
              deployToSlotOrASE: true
              slotName: 'staging'
              package: '$(Pipeline.Workspace)/drop/**/*.zip'
        routeTraffic:
          steps:
          - task: AzureAppServiceManage@0
            inputs:
              azureSubscription: 'Azure'
              action: 'Swap Slots'
              webAppName: '$(webAppName)'
              sourceSlot: 'staging'
              targetSlot: 'production'
        postRouteTraffic:
          steps:
          - task: AppInsightsAlerts@0
            inputs:
              applicationInsightsWebTestId: '$(webTestId)'
              alertRule: 'Availability < 99%'

Deployment jobs support three lifecycle strategies — runOnce, rolling, and canary — with hooks (preDeploy, deploy, routeTraffic, postRouteTraffic, onFailure) where validation and rollback logic belong. For Kubernetes and VM targets, the canary and rolling strategies apply directly; for slot-based platforms, the hooks around a swap achieve the same shape.

Security and Compliance in the Pipeline

Scanning belongs in the build stage, gated: a critical vulnerability or a failed quality gate stops the artifact. Static analysis and dependency scanning are the standard pair, and secrets come from Key Vault at run time, never from repository variables in plain text:

# security-pipeline.yml
trigger:
  branches:
    include:
      - main

variables:
  sonarQubeProject: 'myproject'

steps:
- task: SonarQubePrepare@4
  inputs:
    SonarQube: 'SonarQube'
    scannerMode: 'MSBuild'
    projectKey: '$(sonarQubeProject)'

- task: DotNetCoreCLI@2
  inputs:
    command: 'build'

- task: SonarQubeAnalyze@4

- task: WhiteSource@21
  inputs:
    cwd: '$(System.DefaultWorkingDirectory)'

- task: AzureKeyVault@1
  inputs:
    azureSubscription: 'Azure'
    KeyVaultName: '$(keyVaultName)'
    SecretsFilter: '*'

Service connections are the pipeline's credentials into Azure; scope each one to the subscription or resource group it deploys to, and prefer workload identity federation over stored service principal secrets so there is no long-lived secret to rotate or leak.

Templates and Variable Groups

Copy-pasted pipeline YAML across repositories drifts within a quarter. Templates extract the repeated stages and steps behind parameters:

# template.yml
parameters:
  environment: ''
  serviceConnection: ''

steps:
- task: AzureWebApp@1
  inputs:
    azureSubscription: ${{ parameters.serviceConnection }}
    appName: '$(webAppName)'
    deployToSlotOrASE: true
    resourceGroupName: '$(resourceGroup)'
    slotName: ${{ parameters.environment }}

Variable groups separate shared values from per-environment ones, and secret variables belong in groups linked to Key Vault:

variables:
  - group: common-vars
  - group: ${{ parameters.environment }}-vars
  - name: buildConfiguration
    value: 'Release'
  - name: solution
    value: '**/*.sln'

Watching the Pipeline Itself

Track the delivery metrics that predict trouble: build and deployment duration trends, success rate, and how often a deployment is rolled back. A build that creeps from six minutes to twenty trains developers to batch changes and skip runs; a success rate sliding below the team's own threshold means flaky tests or infrastructure that nobody owns. Azure DevOps pipeline analytics and OData reporting expose these numbers — review them like production metrics, because the pipeline is production infrastructure for every change you ship.

Decision Framework

SituationRecommendation
New application, one teamSingle multi-stage YAML pipeline in the app repo; environments for staging and production
Many services with the same shapeTemplate repository with shared stages; consuming pipelines stay thin
Regulated production environmentEnvironment approvals and checks, gated security scans, immutable artifacts, deployment history as the audit record
App Service workloadSlot deployment with swap and post-swap health hooks
Kubernetes workloadDeployment job with canary strategy and manifest baking from the same pipeline
Pipeline runs longer than the team's patienceCache dependencies, parallelise jobs, split test suites — fix duration before adding stages

Implementation Checklist

  • [ ] One artifact (package or image) built once and promoted unchanged through every environment
  • [ ] Tests and security scans run in the build stage and gate the artifact
  • [ ] Production is an environment with named approvers; no direct deployments outside the pipeline
  • [ ] Service connections scoped least-privilege, using workload identity federation where possible
  • [ ] Secrets sourced from Key Vault; no credentials in YAML or plain-text variables
  • [ ] Rollback rehearsed: previous artifact redeploy or slot swap-back, timed
  • [ ] Repeated YAML extracted into versioned templates; variable groups per environment
  • [ ] Branch policies require a green build and review before merge to the release branch
  • [ ] Pipeline duration and success rate reviewed on a cadence, with an owner
  • Trade-offs

    YAML pipelines are reviewable and versioned with the code, but complex logic in YAML — nested templates, compile-time expressions — becomes hard to debug, and there is a real skill in knowing when a step should be a script in the repo instead. Approvals and gates buy safety with latency: every manual check is a queue a release can sit in, so gate production hard and lower environments lightly. Microsoft-hosted agents remove agent maintenance but limit customisation and can queue at peak times; self-hosted agents invert both properties. Templates reduce duplication while coupling repositories to a shared dependency that needs its own versioning discipline.

    When Not to Use

  • Classic (UI) release pipelines are the wrong choice for new work; they are not versioned with code and cannot be reviewed in a pull request. Build in YAML.
  • A manual approval on every environment is the wrong choice for development environments; it teaches the team to batch and bypass. Gate where the risk is — production.
  • Rebuilding the application per environment is always the wrong choice; it invalidates testing. Promote one artifact, vary configuration, never the binary.
  • Azure Pipelines itself may be the wrong choice if your organisation has standardised on another CI system with its compliance evidence already built; a second pipeline platform doubles the governance surface. Consistency across the estate usually beats per-team preference.
  • Conclusion

    A good Azure DevOps pipeline is boring in the best way: one artifact, promoted through checked environments, deployed with a rehearsed rollback, and scanned before it ships. Build that with YAML, templates, and environment gates, and measure the pipeline's own health as production infrastructure. The goal is not a sophisticated pipeline — it is a trusted one, because a trusted pipeline is the one nobody routes around.

    References

  • Azure DevOps Documentation
  • YAML Schema Reference
  • Pipeline Best Practices
  • Security and Compliance
  • Pipeline Analytics
  • Deployment Strategies
  • Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.