azurecontinuous-integrationazure-pipelinesbitbucket

How to choose ref branch conditionaly in resources block in Azure Pipelines?


I have a problem with adding resources. Code is stored on BitBucket, authoritation through service connection.

resources:
  repositories:
    - repository: componentsPR
      type: bitbucket
      name: <my_project>
      endpoint: '<my_connection>'
      ref: ${{ variables['System.PullRequest.TargetBranch'] }}
    - repository: components
      type: bitbucket
      name: <my_project>
      endpoint: '<my_connection>'
      ref: ${{ variables['Build.SourceBranch'] }}

The problem is - If it's PullRequest, then I don't have a ${{ variables['Build.SourceBranch'] }} branch in my project and pipeline fails.

In resources: repositories, I need to specify *

ref: ${{ variables['System.PullRequest.TargetBranch'] }}* - if Build.Reason is PullRequest,

or

ref: ${{ variables['Build.SourceBranch'] }} - in other cases.

Does someone know how to set if-else for this situation? I will appreciate any idea

I tried checkout, but endpoint was missed; tried $[eq(variables['Build.Reason'], 'PullRequest') ? variables['System.PullRequest.TargetBranch'] : variables['Build.SourceBranch']] - not working.


Solution

  • Expressions for ref are supported, however if you were to write it like this:

    resources:
      repositories:
      - repository: name
        type: bitbucket
        endpoint: <service-connection-name>
        ${{ if ne( variables['Build.BuildReason'], 'PullRequest') }}:
          ref: ${{ variables['Build.SourceBranch'] }}
        ${{ else }}:
          ref: ${{ variables['System.PullRequest.SourceBranch'] }}
    

    ...you'll get an error saying that template expressions aren't supported in this context.

    Fortunately, sprint 248 introduced iif which allows you to specify the if/else statement as a single expression.

    resources:
      repositories:
      - repository: name
        type: bitbucket
        endpoint: <service-connection-name>
        ref: ${{ iif( ne( variables['Build.BuildReason'], 'PullRequest'), variables['Build.SourceBranch'], variables['System.PullRequest.SourceBranch']) }}