Search code examples
conditional-statementsazure-pipelinesazure-devops-self-hosted-agent

Can I set a condition in my YAML script, to have the pipeline choose an agent depending which agent is available but to only run the job defined?


Basically, I want to build a project that can be built both on windows and Linux. I want to define two jobs, windowsBuild and linuxBuild. I want the pipeline only ran the windows build if the agent chosen is a windows agent and to only run the Linux build if the agent chosen is a Linux agent. Also, I want the default agent to be the windows one, I want it to only run on the Linux if the windows one is unavailable, and in the scenario that both are unavailable it should wait for the windows agent.

p.s I am using self-hosted agents; fun fact, I accidently deleted Microsoft hosted agents and don't know how to replace them :)

Anyone know how I can do this? Would really appreciate the help, thank you.


Solution

  • You need to add one job named Check. Then add powershell task.

    Create script to check agent status.

    Use rest api Agents - Get to get windows and linux agent status. And exit based on the agnet status.

    Set job condition.

    E.g. if windows agent is unavailable and linux agent is available, powershell task exit 1 (Job check failed) and will trigger job B.

    - job: buildA
      displayName: buildA
      dependsOn: Check
      condition: succeeded()
      pool: 
        vmImage: windows-latest
      
      steps:
      - script: echo "windows-latest"
    
    - job: buildB
      displayName: buildB
      dependsOn: Check
      pool: 
        vmImage:  ubuntu-latest
      condition: failed()
      steps:
      - script: echo "ubuntu-latest"