How to trigger Agent Job As per condition using PowerShell in Azure Devops Pipeline

余生颓废 提交于 2020-01-25 09:41:26

问题


I have a PowerShell as below:

echo "Hello-World"
$MyVariable = "Proceed"
echo $MyVariable

What I want to do :

If the MyVariable is "Proceed" Only and only then Agent Job2 Should run

I have used PowerShell task and Given Variable name as MyVariableOutput

I have done below configuration at Agent Job2 level

Can you please let me know how can I put these condition:

Only If the Powershell Script at Agent Job1 Produce the Proceed as the value of MyVariable Agent Job2 will run.

Note: Agent Job1 and Agent Job2 Are the part of the same release pipeline


回答1:


If you prefer to configure your pipeline with GUI, you must run script to add the MyVariable as Variables instead of a temporary variable by calling this api. Because after the agent job1 finished, the variable you just defined with $MyVariable = "Proceed" will not transfer to the next agent job. The agent job1 and agent job2 are independent with each other.


In agent job1:

Configure 2 powershell tasks.

(1) The first one is used to define a variable with value and set it as output variable:

echo "Hello-World"
echo "##vso[task.setvariable variable=MyVariable;isOutput=true]Proceed"
echo $MyVariable

Do not forget specify its reference name MyVariableOutput in this task.

(2) The second job is used to add this output variable into Variables, then the agent job2 could access it:

$connectionToken="{token}"
$urlget = "https://vsrm.dev.azure.com/{org}/{project}/_apis/release/releases/$(Release.ReleaseId)?api-version=5.1"
$base64AuthInfo = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$getdef = Invoke-RestMethod -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method GET -ContentType application/json -Uri $urlget 
##Write-Host Pipeline = $($getdef | ConvertTo-Json -Depth 100)
$MyVariable=@"
    {
      "value": "$(MyVariableOutput.MyVariable)"
    }
"@
$getdef.variables | add-member -Name "MyVariable" -value (Convertfrom-Json $MyVariable) -MemberType NoteProperty -Force -PassThru

$getdef = $getdef | ConvertTo-Json -Depth 100
$getdef | clip
$urlput = "https://vsrm.dev.azure.com/{org}/{project}/_apis/release/releases/$(Release.ReleaseId)?api-version=5.1"
$putdef = Invoke-RestMethod -Uri $urlput -Method PUT -Body $getdef -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

The above script will create a variable MyVariable which its value is Proceed.


In agent job2, configure the condition as the shown below:

eq(variables['MyVariable'],'Proceed')

You can see the agent job2 can be run successfully since it has detect the value of MyVariable is Proceed.



来源:https://stackoverflow.com/questions/59355677/how-to-trigger-agent-job-as-per-condition-using-powershell-in-azure-devops-pipel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!