如何在TFS构建中设置仅当指定前置任务失败时执行任务?
Great question! TFS (now rebranded as Azure DevOps Server) doesn’t include a built-in condition option for "only when a specific task fails" out of the box—the default "Only when a previous task has failed" triggers if any prior task fails. But don’t worry, there are two solid ways to get the behavior you want:
Option 1: Use Built-in Task Status Variables (Recommended for TFS 2019+)
Starting with TFS 2019, the system automatically tracks the status of every task in a job using a dedicated variable. Here’s how to use it:
- Grab the Task ID of your target predecessor:
In your build pipeline editor, find the task you want to monitor. Click the three-dot menu in its top-right corner and select View task properties. Copy theTask IDvalue (it’ll look like a long string, e.g.,f4d2a1b3-7890-cdef-1234-5678abcdef90). - Set the custom condition on your current task:
Open the task you want to configure, go to Control Options > Run this task, and select Custom condition. Paste this expression, replacing the placeholder Task ID with the one you copied:
This tells the pipeline to run the task only when the specific predecessor you identified has a status ofeq(variables['Agent.Job.Tasks[f4d2a1b3-7890-cdef-1234-5678abcdef90].Status'], 'Failed')Failed.
Option 2: Use Custom Output Variables (Compatible with Older TFS Versions)
If you’re stuck on a TFS version before 2019, you can manually set a flag variable when the target task fails, then check that flag in your current task’s condition:
- Add an intermediate task to set the failure flag:
Right after your target predecessor task, add a PowerShell (or Command Line) task. Configure its Run this task condition to Only when a previous task has failed, and adjust task dependencies so it only depends on your specific target predecessor. In the PowerShell script, add this line to set an output variable:
Give this intermediate task a reference name (e.g.,Write-Host "##vso[task.setvariable variable=TargetTaskFailed;isOutput=true]true"SetFailureFlag) in the General tab—this lets you reference its output variable later. - Check the flag in your current task’s condition:
Open your target task, go to Control Options > Run this task, select Custom condition. Use this expression to check the flag variable:
Now your task will only run if the intermediate task set the flag (i.e., your specific predecessor failed).eq(variables['SetFailureFlag.TargetTaskFailed'], 'true')
Bonus: Combine Conditions for More Control
If you need a more complex rule (e.g., "run this task only if Task A fails and all other tasks succeeded"), you can combine expressions like this:
and(eq(variables['Agent.Job.Tasks[TaskA_ID].Status'], 'Failed'), succeeded())
Valid task status values you can use in expressions include: Succeeded, SucceededWithIssues, Failed, and Canceled.
内容的提问来源于stack exchange,提问作者Mugen

