How to add container security scanning to Azure DevOps pipelines

Step‑by‑step guide for developers to integrate automated container security scanning into Azure DevOps pipelines, ensuring images are safe before release.

Short answer: To add container security scanning to Azure DevOps pipelines, integrate a scanner like Trivy as a step in your YAML pipeline, store the scanner’s credentials in a secure Azure Key Vault or pipeline secret, configure fail‑fast policies, and publish the scan results as a build artifact or Azure DevOps Test Result.

Introduction

Container images are a common attack surface in modern CI/CD workflows. Without automated vulnerability checks, insecure images can slip into production, exposing your applications to known CVEs and misconfigurations. Azure DevOps provides native support for custom tasks, making it straightforward to embed a scanner such as Trivy directly into your build pipeline.

After following this guide you will be able to:

  • Run Trivy against every image built in an Azure DevOps pipeline.
  • Store and rotate scanner credentials securely.
  • Fail the pipeline automatically when critical vulnerabilities are found.
  • Publish a readable HTML/JSON report that can be reviewed in the Azure DevOps UI.

What You’ll Learn

  • Prerequisites and required Azure resources.
  • How to install Trivy in a container‑based build agent.
  • Secure token management with Azure Key Vault and pipeline variables.
  • Configuring fail‑fast policies based on severity thresholds.
  • Exporting and publishing scan reports.
  • Common pitfalls and how to avoid them.

Prerequisites

  • An Azure DevOps organization with permission to create pipelines and service connections.
  • A self‑hosted or Microsoft‑hosted ubuntu-latest agent (Trivy runs on Linux).
  • Docker installed on the agent (required to build and scan images).
  • An Azure Key Vault (optional but recommended for secret management).
  • Read‑only access to the container registry that stores the images you will scan (Azure Container Registry, Docker Hub, etc.).

Set up Azure Key Vault for scanner credentials

1. Create the vault (if it does not exist)

az group create --name rg-security --location eastus
az keyvault create --name kv-trivy-<UNIQUE_SUFFIX> --resource-group rg-security --location eastus

2. Add a secret for the registry token

Generate a token with read‑only pull rights in your registry (e.g., ACR). Then store it:

az keyvault secret set --vault-name kv-trivy-<UNIQUE_SUFFIX> \
  --name RegistryToken \
  --value <BASE64_ENCODED_TOKEN>

3. Grant the Azure DevOps project access

Create a service principal for the pipeline and give it get permission on the vault:

az ad sp create-for-rbac --name "devops-trivy-sp" --skip-assignment
az keyvault set-policy --name kv-trivy-<UNIQUE_SUFFIX> \
  --spn <APP_ID> \
  --secret-permissions get

4. Add a service connection in Azure DevOps

Navigate to Project Settings → Service connections → New service connection → Azure Resource Manager (service principal) and select the subscription, resource group, and the service principal created above. Name it kv-trivy-conn.

Pro Tip: Rotate the registry token every 90 days and update the Key Vault secret; Azure DevOps will pick up the new value automatically.

Create the Azure DevOps YAML pipeline

Save the following as azure-pipelines.yml at the root of your repo.

trigger:
  - main

variables:
  # Pull the token from Key Vault at runtime
  - group: kv-trivy-conn
  - name: REGISTRY_TOKEN
    value: $(RegistryToken)   # secret from Key Vault

stages:
  - stage: Build
    jobs:
      - job: BuildImage
        displayName: Build Docker image
        pool:
          vmImage: 'ubuntu-latest'
        steps:
          - task: Docker@2
            displayName: Build
            inputs:
              command: build
              repository: $(ACR_NAME).azurecr.io/$(IMAGE_NAME)
              Dockerfile: Dockerfile
              tags: |
                $(Build.BuildId)
          - task: Docker@2
            displayName: Push
            inputs:
              command: push
              repository: $(ACR_NAME).azurecr.io/$(IMAGE_NAME)
              tags: |
                $(Build.BuildId)

  - stage: Scan
    dependsOn: Build
    jobs:
      - job: TrivyScan
        displayName: Scan image with Trivy
        pool:
          vmImage: 'ubuntu-latest'
        steps:
          # Install Trivy (see next section)
          - script: |
              curl -sSfL https://github.com/aquasecurity/trivy/releases/latest/download/trivy_0.46.0_Linux-64bit.tar.gz | tar -xz -C /usr/local/bin trivy
            displayName: Install Trivy

          # Log in to the registry using the secret
          - script: |
              echo $(REGISTRY_TOKEN) | docker login $(ACR_NAME).azurecr.io -u 00000000-0000-0000-0000-000000000000 --password-stdin
            displayName: Docker login

          # Pull the image to scan
          - script: |
              docker pull $(ACR_NAME).azurecr.io/$(IMAGE_NAME):$(Build.BuildId)
            displayName: Pull image

          # Run Trivy, output JSON and HTML
          - script: |
              trivy image --format json --output trivy-report.json \
                $(ACR_NAME).azurecr.io/$(IMAGE_NAME):$(Build.BuildId)
              trivy image --format template --template "@{{range .Results}}{{range .Vulnerabilities}}{{.Severity}}:{{.VulnerabilityID}} {{.Title}}\n{{end}}{{end}}" \
                --output trivy-report.txt $(ACR_NAME).azurecr.io/$(IMAGE_NAME):$(Build.BuildId)
            displayName: Run Trivy

          # Fail fast if critical/high severity exceeds threshold
          - script: |
              CRITICAL=$(jq '[.Results[].Vulnerabilities[] | select(.Severity=="CRITICAL")] | length' trivy-report.json)
              HIGH=$(jq '[.Results[].Vulnerabilities[] | select(.Severity=="HIGH")] | length' trivy-report.json)
              if [ $CRITICAL -gt 0 ] || [ $HIGH -gt 5 ]; then
                echo "##vso[task.logissue type=error]Too many critical/high vulnerabilities."
                exit 1
              fi
            displayName: Enforce policy
            env:
              jq: $(Agent.ToolsDirectory)/jq

          # Publish the JSON report as an artifact
          - publish: trivy-report.json
            artifact: TrivyReport
            displayName: Publish report

          # Optional: Publish as a Test Result for UI visibility
          - task: PublishTestResults@2
            inputs:
              testResultsFormat: 'JUnit'
              testResultsFiles: '**/trivy-report.xml'
            condition: succeededOrFailed()

Install Trivy in the build agent

Trivy is distributed as a single binary. The script in the pipeline downloads the latest release from GitHub (official release page). If you prefer a container‑based approach, you can replace the install step with:

docker run --rm -v $(Agent.TempDirectory):/output aquasec/trivy:latest image \
  --format json --output /output/trivy-report.json \
  $(ACR_NAME).azurecr.io/$(IMAGE_NAME):$(Build.BuildId)

Using the container image guarantees version consistency across agents.

Run the scan and enforce policies

  • Severity thresholds: Adjust the numbers in the “Enforce policy” script to match your risk tolerance.
  • Fail‑fast: The script exits with a non‑zero status, causing Azure DevOps to mark the job as failed and stop subsequent stages.
  • Custom policies: Trivy supports policy files (Rego). Add a .trivyignore or a Rego file and pass --policy /path/to/policy.rego if you need more granular control.

Publish the vulnerability report

Two built‑in Azure DevOps mechanisms make the results easy to consume:

  1. Artifacts: The JSON file is stored as a pipeline artifact (TrivyReport) and can be downloaded from the run summary.
  2. Test results: Converting the JSON to JUnit XML (using trivy convert or a small script) lets you view findings under the “Tests” tab, with each vulnerability shown as a failed test case.

Troubleshooting & best practices

Common errors

  • “permission denied while trying to connect to Docker daemon” – Ensure the agent runs with Docker privileges. On Microsoft‑hosted agents this is pre‑configured; on self‑hosted agents add the user to the docker group.
  • “Failed to retrieve token from Key Vault” – Verify the service connection name matches the variable group and that the service principal has get secret permission.
  • Empty scan results – Confirm the image tag matches the built image; mismatched tags cause Trivy to scan a different (or non‑existent) layer.

Best practices

  • Run the scan on the exact image that will be promoted to production (use the same tag).
  • Cache Trivy’s vulnerability database between runs to speed up scans. Add a step that copies /root/.cache/trivy to the agent’s workspace and restores it on the next run.
  • Rotate registry tokens regularly and audit Key Vault access logs.
  • Consider integrating the report with Azure Security Center for broader visibility.

Scanner comparison table

Scanner Open‑source / Commercial Supported image sources Ease of integration (Azure DevOps) Pricing model Typical use‑case
Trivy Open‑source (Apache 2.0) Docker Hub, ACR, ECR, GCR, local tarballs Simple CLI, Docker image, or Azure DevOps task (community) Free (self‑hosted). Enterprise support via Aqua Security (subscription) General‑purpose CI/CD scanning with fast updates
Microsoft Defender for Containers (image scanning) Commercial (included with Azure Defender tier) ACR only (native integration) Built‑in Azure DevOps extension, minimal config Pay‑as‑you‑go per node or per image scan (see Azure pricing page) Enterprises already using Azure Defender, need unified view
Snyk Container Commercial (free tier limited to 100 tests/month) Docker Hub, ACR, private registries via API token Official Azure DevOps marketplace task Free tier, then per‑developer or per‑scan pricing (Snyk pricing) Teams that want integrated remediation suggestions

Frequently Asked Questions

Can I scan images stored in a private registry other than Azure Container Registry?

Yes. Trivy supports any registry reachable from the build agent as long as you provide valid credentials (username/password or token). Store those credentials in Azure Key Vault and reference them in the pipeline.

Do I need a separate Azure DevOps agent for Trivy?

No. Trivy runs on any Linux agent with Docker installed. If you use a Microsoft‑hosted ubuntu-latest agent, the required tools are already present.

How often is Trivy’s vulnerability database updated?

Trivy pulls the latest DB from the public GitHub repository at each run unless a cached copy exists. For faster builds you can cache /root/.cache/trivy between pipeline runs.

What is the difference between “severity” and “CVSS score” in Trivy reports?

Severity is a categorical label (CRITICAL, HIGH, MEDIUM, LOW, UNKNOWN) derived from the CVSS score range. The CVSS numeric score (0‑10) provides finer granularity; you can filter by score in custom scripts if needed.

Can I fail the pipeline only on CVSS ≥ 9.0 instead of severity?

Yes. Use a custom script that parses the JSON output and checks the .Vulnerability.CVSS.ScoreV3 field. Example:

if jq '[.Results[].Vulnerabilities[] | select(.CVSS.ScoreV3 >= 9.0)] | length' trivy-report.json | grep -q '[1-9]'; then
  echo "Critical CVSS found"
  exit 1
fi

Is it possible to run Trivy as a pre‑commit hook?

Trivy can be invoked locally before committing Dockerfiles, but that is outside the scope of Azure DevOps pipelines. Refer to the official Trivy docs for setup details.

Conclusion & next steps

Embedding container security scanning into Azure DevOps pipelines turns vulnerability detection into an automated gate rather than an after‑thought. With the steps above you have a repeatable, auditable process that:

  • Builds the image,
  • Scans it with Trivy,
  • Enforces fail‑fast policies, and
  • Publishes a consumable report.

Next actions:

  1. Pin the Trivy version in your pipeline (replace latest with a specific release tag) to avoid unexpected changes.
  2. Enable caching of Trivy’s DB to reduce scan time.
  3. Integrate the generated report with Azure Security Center or a Slack webhook for immediate alerts.
  4. Evaluate additional policies (e.g., disallowing root user, checking for insecure ports) using Trivy’s Rego support.

Official documentation