Search code examples
yamlazure-pipelinesexitazure-pipelines-yaml

Clean Exit from an Azure Pipeline .yaml?


Is there a better/cleaner/more idiomatic way to exit a .yaml-based Azure Pipeline than say having a script throw an error?

e.g., this works but it feels clunky:

- task: PowerShell@2
  displayName: "Exit"
  inputs:
    targetType: 'inline'
    script: |
      throw 'Exiting';

Solution

  • - powershell: |
      write-host "##vso[task.complete result=Failed;]The reason you quit"
    

    Would be neater, but would still fail the job.

    There is no equivalent to skip the rest of the job, unless you work with conditions to skip all future tasks based on a variable value:

    variables:
      skiprest: false
    
    - powershell: |
      write-host "##vso[task.setvariable variable=skiprest]true"
    - powershell:
      condition: and(succeeded(), eq(skiprest, 'false'))
    - powershell:
      condition: and(succeeded(), eq(skiprest, 'false'))
    - powershell:
      condition: and(succeeded(), eq(skiprest, 'false'))
    - powershell:
      condition: and(succeeded(), eq(skiprest, 'false'))
    

    You could use a YAML iterative insertion from a template to apply that condition to all tasks in a job I suppose. I don't have a working sample at hand, but the docs show how to inject a dependsOn:, the trick would be very similar I suppose:

    # job.yml
    parameters:
    - name: 'jobs'
      type: jobList
      default: []
    
    jobs:
    - job: SomeSpecialTool                # Run your special tool in its own job first
      steps:
      - task: RunSpecialTool@1
    - ${{ each job in parameters.jobs }}: # Then do each job
      - ${{ each pair in job }}:          # Insert all properties other than "dependsOn"
          ${{ if ne(pair.key, 'dependsOn') }}:
            ${{ pair.key }}: ${{ pair.value }}
        dependsOn:                        # Inject dependency
        - SomeSpecialTool
        - ${{ if job.dependsOn }}:
          - ${{ job.dependsOn }}