azureazure-devopsazure-cli

Trigger / queue build policy pipeline on ADO PR with Azure CLI


In a repository on Azure DevOps (ADO), I have a build validation policy on my main branch that PRs which wish to merge into main must first complete a successful Azure pipeline run.

I would like to use the Azure CLI to trigger this build validation pipeline.

I know that I can trigger this pipeline with az pipelines run or az pipelines build queue, and point to my PR with the --branch argument as eg. az pipelines build queue --branch "refs/pull/123/merge" --definition-id 456.

However, when I do so, the pipeline run doesn't count towards the PR's build validation. That is, even if my pipeline succeeds, it is not reflected in my PR, and I still can't merge my changes.

How can I trigger my pipeline with the Azure CLI, so that it counts towards my PR's build validation? I am looking for the Azure CLI equivalent to clicking the "Queue" button on my PR's pipeline (image taken from this comment):

Queue button on ADO PR


Solution

  • You need to use the az repos pr policy command group to achieve this.

    Start by determining the build validation evaluation ID associated with your PR. Note that this value changes on a per PR basis.

    You can determine this value for your PR with:

    az repos pr policy list --id <YOUR-PR-NUMBER-HERE> --query "[?configuration.type.displayName=='Build'].evaluationId"
    

    Your evaluation ID will be a long alpha-numeric string, separated with hyphens. It'll look something like: d2hr35yd-9fe0-y4t5-hb35-5een2cr04b2.

    You then need to pass this value to az repos pr policy queue as eg.

    az repos pr policy queue --evaluation-id <BUILD-EVAL-ID-HERE> --id <YOUR-PR-NUMBER-HERE>
    

    Putting these two steps together, and doing a little string manipulation to make things work, gives us:

    # Your PR number here
    pr_id=123
    
    build_pipeline_eval_id=$(
      az repos pr policy list \
          --id $pr_id \
          --query "[?configuration.type.displayName=='Build'].evaluationId | [0]" \
          --out tsv
    )
    az repos pr policy queue --evaluation-id $build_pipeline_eval_id --id $pr_id
    

    This will now run your required build pipeline, against your PR, as if you had clicked the "Queue" button from the ADO UI, as desired.