Configuring Pipeline dependencies in Azure Pipelines - azure-devops

I have 2 Azure Pipelines, deploy and test. As their names imply one is used for deploying a product and the other is used for testing. When a developer wants to run their own tests on the existing deployment they trigger test. When a deployment is required they trigger deploy. If the test pipeline is in execution when the deploy pipeline is triggered I want the deploy to wait till the test has finished executing.
Is there a way to configure this dependency within the pipeline.yaml themselves, or a workaround to achieve the mentioned requirement

Is there a way to configure this dependency within the pipeline.yaml themselves, or a workaround to achieve the mentioned requirement
Here are two methods could meet your requirement:
1.You could add the Environment in your Yaml Pipeline. Add you could add Invoke Rest API check in the environment. Rest API: Latest - Get
In Yaml Pipeline, you could call this environment.
Example:
stages:
- stage: deploy
jobs:
- deployment: DeployWeb
displayName: deploy Web App
pool:
vmImage: 'Ubuntu-latest'
environment: 'EnvironmentName'
strategy:
runOnce:
deploy:
steps:
...
When you run the pipeline, the environment will check the latest build status of the test Pipeline. If the build has completed , it will run the deploy pipeline.
Result:
2.You could directly add a Powershell task in the Deploy task to check the status of the Test Pipeline.
$token = "PAT"
$url="https://dev.azure.com/{OrganizationName}/{ProjectName}/_apis/build/definitions/{DefinitionID}?includeLatestBuilds=true&api-version=5.1"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
$buildid = $response.latestBuild.id
echo $buildid
$success = $false
do{
try{
$Buildurl2 = "https://dev.azure.com/{OrganizationName}/{ProjectName}/_apis/build/builds/$($buildid)?api-version=5.0"
$Buildinfo2 = Invoke-RestMethod -Method Get -ContentType application/json -Uri $Buildurl2 -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$BuildStatus= $Buildinfo2.status
$result = $Buildinfo2.result
echo $result
echo $BuildStatus
if($BuildStatus -eq "completed" ) {
write-output "No Running Pipeline, starting Next Pipeline"
$success = $true
} else {
Write-output "Pipeline Build In Progress, Waiting for it to finish!"
Write-output "Next attempt in 30 seconds"
Start-sleep -Seconds 30
}
}
catch{
Write-output "catch - Next attempt in 30 seconds"
write-output "1"
Start-sleep -Seconds 30
# Put the start-sleep in the catch statemtnt so we
# don't sleep if the condition is true and waste time
}
$count++
}until($count -eq 2000 -or $success -eq $true )
if ($result -ne "succeeded" )
{
echo "##vso[task.logissue type=error]Something went very wrong."
}
if(-not($success)){exit}
You can also refer to my another ticket.

You will probably have to merge the pipelines into one and, depending on the steps in them, you can convert them to jobs or even to stages. In both cases, you can specify dependencies via dependsOn (e.g. docs for jobs).
So you will have something like:
jobs:
- job: test
steps:
- step1...
- step2...
- job: deploy
dependsOn: test
steps:
- step1...
- step2...
Also, if you go this way, consider using deployment jobs for deployment, they have some related build-in functionality.

Related

Prevent schedule from triggering when I have ongoing or failed builds in azure devops

In azure devops and yaml I can set a schedule trigger like this:
schedules:
- cron: "0 0 * * *"
displayName: Daily midnight build
branches:
include:
- main
And it will now trigger every night if main have new code since the last successful build.
But my problem is that I have builds that are long running with multiple stages (acc, int, prod) that we manually approve on different days.
So how do I prevent it from queueing new builds (with the same code) if it already have a build with x commit? Even it it's ongoing or in failed state. I can't seem to find anything in the documentation.
You can't accomplish this out of the box. However, you can write the logic into your pipeline.
To accomplish this, you would need to add a task into your pipeline that can:
Query for the last pipeline run
Evaluate if the current pipeline should proceed based on the last run's data
The step would look something like this:
- powershell: |
$header = #{ Authorization = "Bearer $env:System_AccessToken" }
$buildsUrl = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/builds/builds"
$builds = Invoke-RestMethod -Uri $buildsUrl -Method Get -Header $header
$inProgressBuilds = $builds.value.Where({ ($.status -eq 'inProgress') -and ($_.definition.name -eq '$(Build.DefinitionName)') -and ($_.id -ne $(Build.BuildId)) })
if ( $inProgressBuilds.Count -gt 0 ) {
throw 'Pipeline run already in progress.'
}
displayName: "Validate Current Pipeline Runs"

In an Azure Devops pipeline, how can I detect and cancel other build jobs from the same Git branch?

How do I write an Azure Pipeline script that detects whether any other CI build jobs are running using the same Git branch, and cancels those other jobs?
I want to cancel only CI build jobs. Any PR build jobs and manually triggered jobs from the same Git branch should be ignored, and allowed to continue running.
Any build jobs from other Git branches should also be ignored.
The Azure DevOps VM is a self-hosted Windows VM, so the task must be a PowerShell or Windows script, not bash. The source is in Bitbucket Cloud -- this is important, because ADO handles Bitbucket Cloud repositories differently from other repositories.
If a canned task is available, I can use it as well.
The following questions are related, but they do not directly address this use case.
Is an Azure DevOps build pipeline, is there a way to cancel one pipeline job from another job?
Azure devops build pipeline depends on other build pipeline
You can first use the API "Builds - List" to list all the builds which have been trigged but not completed.
GET https://dev.azure.com/{organization}/{project}/_apis/build/builds?reasonFilter={reasonFilter}&statusFilter={statusFilter}&branchName={branchName}&repositoryId={repositoryId}&api-version=6.0
For your case,
The value of reasonFilter should be batchedCI and individualCI.
The value of statusFilter should be inProgress, notStarted and postponed.
The value of branchName is the branch you specify.
The value of repositoryId is the ID of your Git repository.
Then use the API "Builds - Update Build" to cancel all the builds (except the current build) in a loop.
You can add powershell script step into your build definition to check active builds on the same branch. As an example
$user = ""
$token = "$(System.AccessToken)"
$buildDef = "$(System.DefinitionId)"
$branchName = "$(Build.SourceBranch)"
$teamProject = "$(System.TeamProject)"
$orgUrl = "$(System.CollectionUri)"
$buildId = $(Build.BuildId) -as [int]
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
$uriGetActiveBuilds = "$orgUrl/$teamProject/_apis/build/builds?definitions=$buildDef&statusFilter=inProgress&branchName=$branchName&api-version=5.1"
$resultStatus = Invoke-RestMethod -Uri $uriGetActiveBuilds -Method Get -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
if ($resultStatus.count -gt 0)
{
foreach ($build in $resultStatus.value)
{
$bid = $build.id -as [int]
if ($buildId -gt $bid) //if exists a lower value of the build id on the same branch, the current build should be stoped
{
exit 1
}
}
}
The answer from #Shamrai-Alexsandr cancels the current build, but what I want to do was cancel all other builds (that is, CI builds on the current branch) still in progress.
The answer from #bright-ran-msft gave me enough clues to combine #bright's solution with #shamrai's solution, replacing the exit 1 with code that cancels the other builds:
if ($buildId -gt $bid)
{
$build.status = "Cancelling"
$cancelRequest = $build | ConvertTo-Json -Depth 10
$uriCancel = "$orgUrl$teamProject/_apis/build/builds/$($build.id)?api-version=6.0"
$resultOfCancel = Invoke-RestMethod -Uri $uriCancel -Method Patch -ContentType "application/json" -body $cancelRequest -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
Write-Host "Result of Cancel request: " $resultOfCancel.status
}

Identify build policy responsible for run of pull request build in Azure DevOps pipeline

I would like to identify the build policy for a build that was run by clicking the Queue (or Re-queue) button against a required/optional check from within a pull request. I wish to identify the policy programmatically from within a pipeline; e.g. a script task. Open to any approach, been exploring the az CLI but no luck thus far.
I've setup two build policies against a branch that both target the same build definition - Policy A and Policy B. Both are setup to be run manually - A is required, B is optional. Both will surface in the UI for a pull request as checks - A being required, B being optional. When a build is run by clicking the Queue (or Re-queue) button against either check, I would like to be able to identify which of the two policies the run was initiated from, (which policy provided the Queue or Re-queue button that was clicked).
EDIT: A bit more background on what I'm doing ...
I've got a single pipeline for building an application.
I've recently got a request to update the pipeline to support publishing to Chromatic.
I've added a Publish to Chromatic parameter to the pipeline and a task to push to Chromatic when the parameter is set to true.
I received a subsequent request to make it easier to publish changes from a feature branch to Chromatic. One engineer threw out the idea of having an optional check available in pull requests to give a single button click experience.
While researching my options, I was wondering if it would be possible to enhance the existing pipeline to set the Publish to Chromatic parameter to true during a run. I found this comment on Reddit which ultimately led to me posting here ...
set a default for your parameter (I like to use 'auto') add a script >task near the beginning that reads the pull request comment and sets a variable for you to use in later logic if the parameter is auto . you can even condition this to only run on a PR.
I am aware that I could create a separate pipeline for publishing to Chromatic instead of updating the existing one; that's one of a few options I have. At this point, I'm more-so curious whether or not this particular approach is technically feasible even if I opt not to go forward with it.
Hope that adds some clarity!
The policy that queued the pipeline isn't something that is visible to the pipeline as a pipeline variable. In fact, there doesn't seem to be any indication if the PullRequest was queued manually or automatically.
There might be a few other ways to approach this...
I would start by putting a publishChromatic parameter in the pipeline and then building up conditions in the pipeline execution around this variable. By default, let's assume that the value is false so that if you're manually queueing a pipeline run you can opt-in.
triggers:
- include:
branches:
- develop
parameters:
- name: publishChromatic
displayName: 'Publish build to Chromatic'
type: boolean
default: false
jobs:
- job: Build
variables:
publishChromatic: ${{ parameters.publishChromatic }}
steps:
... pre-execution steps
- task: CmdLine#2
displayName: Publish to Chromatic
condition: and(succeeded(), eq(variables['publishChromatic'], 'true'))
inputs:
script: npx chromatic --project-token=$(CHROMATIC_PROJECT_TOKEN) --branch=$(Build.SourceBranch)
... post execution steps
Option 1: Pull Request Labels
One option might be to inspect the pull request for the presence of a label as outlined in this answer. As a pre-execution step, a simple script could flip the flag when the label is present:
- pwsh: |
$urlFormat = "{0}/{1}/_apis/git/repositories/{1}/pullRequests/{2}/labels?api-version=6.0-preview.1"
$url = $urlFormat -f `
$env:SYSTEM_TEAMFOUNDATIONSERVERURI, `
$env:SYSTEM_TEAMPROJECTID, `
$env:BUILD_REPOSITORY_NAME, `
$env:SYSTEM_PULLREQUEST_PULLREQUESTID
$headers = #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
$response = Invoke-RestMethod -Uri $url -Method Get -Headers $headers
$labels = $response.value.name
Write-Host "##vso[task.setvariable variable=PullRequestTag]$labels"
displayName: 'Fetch Pull Request Labels'
condition: and( succeeded(), eq(variables['Build.Reason'], 'PullRequest'))
env:
SYSTEM_ACCESSTOKEN: $(System.AccessToken)
- pwsh: |
if ("$(PullRequestLabels)" -like "*chromatic*") {
Write-Host "##vso[task.setvariable variable=publishChromatic]true"
}
condition: and( succeeded(), eq(variables['Build.Reason'], 'PullRequest'))
displayName: 'Check for Chromatic label'
I like this option in that it provides a bit of traceability for which Pull Requests were deployed. Unfortunately, there's no way to queue a build automatically when the PR labels are modified so you'd need to have the tag on the PR before triggering the pipeline.
You could also establish a different pattern such as triggering based on a convention like a value that appears in the name of the Pull Request, etc.
Option 2: Pipeline to Trigger Chromatic
If you'd rather have a Build Validation option labeled 'Deploy to Chromatic' to automate triggering your deployment to Chromatic, a simple option would be to create a pipeline that triggers your pipeline with the publishChromatic parameter.
trigger: none
steps:
- checkout: none
- pwsh: |
$pipelineId = 1234
$urlFormat = "{0}/{1}/_apis/pipelines/{2}/runs?api-version=6.0-preview.1
$url = $urlFormat -f `
$env:SYSTEM_TEAMFOUNDATIONSERVERURI, `
$env:SYSTEM_TEAMPROJECTID `
$pipelineId
$headers = #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
$body = #{
resources = #{ repositories = #{ self = #{ refName = "$(Build.SourceBranch)" } } }
variables = #{
originalPrId = #{
value = "$(System.PullRequest.PullRequestId)
}
}
templateParameters = #{
publishChromatic = $true
}
}
Invoke-RestMethod -Uri $url -Method Post -Body $body -Headers $headers
displayName: 'Trigger Chromatic Pipeline'
condition: eq(variables['Build.Reason'],'PullRequest')
env:
SYSTEM_ACCESSTOKEN: $(System.AccessToken)
This simple script performs a fire-and-forget approach to triggering your original pipeline.
If you need to have a successful deployment to Chromatic as part of your PR, you could adjust the original pipeline to report a pull-request status.
In your original pipeline, add the following as a post-execution step:
- pwsh: |
$urlFormat = "{0}/{1}/_apis/git/repositories/{2}/pullRequests/{3}/statuses?api-version=6.0-preview.1
$url = $urlFormat -f `
$env:SYSTEM_TEAMFOUNDATIONSERVERURI, `
$env:SYSTEM_TEAMPROJECTID, `
$env:BUILD_REPOSITORY_NAME, `
"$(originalPrId)"
$headers = #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
$body = #{
status = "succeeded"
description = "completed chromatic regression"
context = #{
name = "qualitygate/chromatic"
}
targetUrl = "http://chromatic.com/your/buildid"
}
Invoke-RestMethod -Uri $url -Method POST -Body $body -Headers $headers
displayName: Report status to PR
condition: and( succeeded(), ne(variables['originalPrId'],''))
env:
SYSTEM_ACCESSTOKEN: $(System.AccessToken)
To require a successful chromatic quality gate, add a Status Check to your Branch Policy with the same name mentioned above qualitygate/chromatic.
Option 3: Further down the Rabbit hole
You can establish even deeper integration with Chromatic by building a custom extension that allows you to add specialized menus to the Pull Request checks menu. The custom menu could include javascript-enabled buttons to trigger your pipeline without the need for a custom pipeline mentioned in Option 2.
While not necessarily dependent on writing a custom extension, you could also create an Azure Function App that listens for webhooks from Chromatic and posts status updates back to your PR with the a custom UI that links back to the Chromatic build. You'd simply need to query the Azure DevOps API to map the branch name in the Chromatic payload to the corresponding PR.

Limit Simultaneous Azure Pipelines Stage

I have an Azure DevOps Multi Stage Pipeline with multiple agents. Generally my stages consist of:
Build and Publish Artifacts
Deploy to environment 1
UI Test environment 1
Deploy to environment 2
UI Test environment 2
and so on for several environments. How do I allow simultaneous pipelines runs (e.g. Building and Publishing Artifacts for Build #2 while simultaneously UI Testing environment 2 for Build #1), while ensuring that no two agents will ever perform a UI Test for a given environment at the same time?
trigger: batch seems close to what I want, but I believe that disallows concurrency at the pipeline level, not at the stage level.
Your
UI Test environment 1 stage (specifically deployment job which Runs the tests) should target
env1uitest environment.
UI Test environment 2 stage (specifically deployment job which Runs the tests) should target
env2uitest environment.
Then set a exclusive lock ( https://learn.microsoft.com/en-us/azure/devops/release-notes/2020/pipelines/sprint-172-update#exclusive-deployment-lock-policy) policy on these two environments.
It should address your need:
"ensuring that no two agents will ever perform a UI Test for a given environment at the same time"
https://learn.microsoft.com/en-us/azure/devops/pipelines/process/approvals?view=azure-devops&tabs=check-pass#exclusive-lock
It seems that if somebody runs the release pipeline twice, You need it to run it one by one, not in parallel, right?
As a workaround:
Each release will start from stage 1. Thus we can add a PowerShell task as the first task for stage 1 to check if there are previous in-progress deployments.
In this PowerShell task, we can call this Rest API to check release stage status.
Power shell script:
# Base64-encodes the Personal Access Token (PAT) appropriately
$token = "$(pat)"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$success = $false
$count = 0
do{
try{
$stageurl2 = "https://vsrm.dev.azure.com/{org name}/{project name}/_apis/release/deployments?definitionId={release definition ID}&deploymentStatus=inProgress&api-version=6.0"
$stageinfo2 = Invoke-RestMethod -Method Get -ContentType application/json -Uri $stageurl2 -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$inprogressdeployments = $stageinfo2.value | where {($_.deploymentStatus -eq "inProgress") -and ($_.release.name -ne $ENV:RELEASE_RELEASENAME) -and ($_.releaseEnvironment.name -ne 'stop services')} | Sort-Object -Property completedOn -Descending
#write-output $inprogressdeployments
$stageurl3 = "https://vsrm.dev.azure.com/{org name}/{project name}/_apis/release/deployments?definitionId={release definition ID}&operationStatus=QueuedForAgent&api-version=6.0"
$stageinfo3 = Invoke-RestMethod -Method Get -ContentType application/json -Uri $stageurl3 -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$queueddeployments = $stageinfo3.value
#write-output $queueddeployments
if($inprogressdeployments) {
Write-output "Deployment In Progress, Waiting for it to finish!"
Write-output "Next attempt in 30 seconds"
Start-sleep -Seconds 30
} else {
Write-Host "No Current Deployment in Progress"
if($queueddeployments) {
write-output "Current Queued deployments"
Write-output "if 2 - Next attempt in 30 seconds"
Start-sleep -Seconds 30
}
else{
write-output "No Queued deployments, starting release"
$success = $true
}
}
}
catch{
Write-output "catch - Next attempt in 30 seconds"
write-output "1"
Start-sleep -Seconds 30
# Put the start-sleep in the catch statemtnt so we
# don't sleep if the condition is true and waste time
}
$count++
}until($count -eq 2000 -or $success)
if(-not($success)){exit}
Result:
Stage1 will continue to check until all previous versions are complete.
We could also try it with demands, we could specify same demands. Use demands to make sure that the capabilities your pipeline needs are present on the agents that run it. It won't run unless one or more demands are met by the agent.
You put the tasks into different jobs, and specify a dependsOn property for jobs that need to wait for particular job to be finished.
If you leave out the dependsOn, it will run synchronounsly.
After reading your prompt more closely, I think you just need a build stage that builds and publishes your artifact.
then a deploy_test stage for each environment. Stages run sequentially by default (unlike jobs)

Azure Devops - How to call one pipeline from another

Could someone help me with how to call one pipeline from another pipeline in Azure DevOps?
I have to run a pipeline and this should trigger another pipeline in different project.
You can try to use Trigger Azure DevOps Pipeline task to trigger another pipeline in different projects.
Depending on your choice in the task it will trigger a build or a release pipeline.
To be able to use the extension an Azure DevOps API endpoint needs to be created.
For the service connection to work as it should you need to configure the following parameters:
Organization Url: The URL of the organization.
(https://dev.azure.com/[organization])
Release API Url: The URL of the Azure DevOps Release API
(https://vsrm.dev.azure.com/[organization])
Personal Access Token: The personal access token.
How you can create a personal access token can be found here: Use personal access tokens to authenticate.
Make sure the personal access token has the following rights:
Triggering a Release: Release – Read, write & execute – Build Read &
Execute
Triggering a Build: Read & Execute
I think resources for Azure Pipelines is what you looking for.
Add a resource in the pipeline that shall be called from another one and name the source pipeline:
# Explicitly set none for repository trigger
trigger:
- none
resources:
pipelines:
- pipeline: myappbuild # Name of the pipeline resource
source: myapp-build-pipeline # Name of the triggering pipeline
trigger:
branches:
- master
You can use API for triggering build. Here is the example that I use to trigger another build pipeline.
- powershell: |
# Write your PowerShell commands here.
Write-Host " ***** Start Script ***** "
$body = '
{
"parameters": "{\"parameter1\": \"value1\"}",
"definition": {"id": "1234"},
"sourceBranch": "git/branch",
"templateParameters": {"templateparameter": "paramvalue"}
}
'
$bodyJson=$body | ConvertFrom-Json
Write-Output $bodyJson
$bodyString=$bodyJson | ConvertTo-Json -Depth 100
Write-Output $bodyString
$user="$(user)"
$token="$(token)"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
$Uri = "https://tfs.com:8443/Organization/_apis/build/builds?api-version=6.1-preview.6"
$buildresponse = Invoke-RestMethod -Method Post -UseDefaultCredentials -ContentType application/json -Uri $Uri -Body $bodyString -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
write-host $buildresponse
$buildID = $buildresponse.id
write-host $buildID
Write-Output "Build ID is $buildID... Sleep for 5 seconds.."
Start-Sleep -Seconds 5
$buildInfo = ( Invoke-RestMethod -Method Get -UseDefaultCredentials -Uri "https://tfs.com:8443/Organization/_apis/build/builds/${buildID}?api-version=6.1-preview.6" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} )
while($buildInfo.status -eq "inProgress" -or $buildInfo.status -eq "notStarted") # keep checking till build completed
{
Write-Output "Build is $($buildInfo.status)... Sleep for 5 seconds.."
Start-Sleep -Seconds 5 # Start sleep for 5 seconds
$buildInfo = ( Invoke-RestMethod -Method Get -UseDefaultCredentials -Uri "https://tfs.com:8443/Organization/_apis/build/builds/${buildID}?api-version=6.1-preview.6" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} )
}
Write-Output "Build Status : $($buildInfo.status)" # print build status
Write-Output "Build Result : $($buildInfo.result)" # print build result
displayName: 'Trigger Another Build Pipeline'
You can install az devops extension in your pipeline agent and then you can call az pipeline CLI commands" to manage other build or release pipelines. Next, you can call az pipeline CLI commands from your main pipeline and for this you can use AzureCLI task or Bash task.
Here is an implementation I use with the following:
PowerShell CmdLet "Invoke-RestMethod" https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-5.1
Azure DevOps REST API https://learn.microsoft.com/en-us/rest/api/azure/devops/build/builds/queue?view=azure-devops-rest-5.0
The $(System.AccessToken) variable from DevOps. This has the
advantage that a PAT is not necessary. More Infomation at https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#systemaccesstoken
Unfortunately the target pipeline is not in another project
I created a stage
######### stage_call_other_pipelines ###################
#########################################################
- stage: stage_call_other_pipelines
displayName: "call other pipelines"
jobs:
#XYZ deployment
- job: job_call_XYZ_deployment
displayName: "execute XYZ deployment"
steps:
- checkout: none
- task: PowerShell#2
displayName: "via REST API"
env:
SYSTEM_ACCESSTOKEN: $(System.AccessToken)
inputs:
targetType: 'inline'
script: |
#url
$url = 'https://dev.azure.com/XYZOrganization/XYZProject/_apis/build/builds?api-version=5.0'
#header
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Content-Type", "application/json")
$headers.Add("Authorization","Bearer $env:SYSTEM_ACCESSTOKEN");
#body
$body = " {
`n `"definition`": {
`n `"id`": 134
`n },
`n `"templateParameters`": {
`n `"ParameterA`": `"ParameterValueA`",
`n `"ParameterB`": `"ParameterValueB`"
`n }
`n }"
#call rest api
$response = Invoke-RestMethod $url -Method 'POST' -Headers $headers -Body $body
#output
$response | ConvertTo-Json
failOnStderr: true
pwsh: true
The token is passed to the agent as an environment variable. The pipeline and its parameters are defined in the body.
Additional
On the pipeline that is to be executed, permissions must be adjusted.
Go to the desired pipeline, click in the right upper corner on the
menu button and select "Manage security"
A form will apear. Choose the Build Service service principal and set "Queue builds" on "Allow"
Since the OP didn't specify how they wanted to accomplish this, I'll share how I'm doing this without YAML pipelines. I use the Edit pipeline option then the meatball menu to select triggers and I can specify which triggering build with branch filters.