Search code examples
azure-devopsyamlcicd

Azure DevOps YAML - How to get branch name from repository ref?


Context: In Azure DevOps I'm building YAML pipeline to run Checkmarx scan. I need to pass branch name. I would like to get branch name from resources.repositories.source.ref. My requirement is to get branch name without part refs/heads/, for example if branch name is development, as a ref I pass refs/heads/development. I'm expecting to get only development part.

I tried to use replace expression. It looks like it works different with resources.repositories Below I provide minimum reproducible example

name: Full Scan $(date:ddMMyyyy)$(rev:.r)
appendCommitMessageToRunName: false

resources:
  repositories:
    - repository: source
      type: git
      name: DemoProject/DemoRepo
      ref: refs/heads/development

trigger: none

variables:
  - name: repoName
    value: $[ resources.repositories.source.name ]

  - name: ref
    value: $[ resources.repositories.source.ref ]

pool:
  vmImage: "ubuntu-latest"

steps:
  - checkout: source

  - task: PowerShell@2
    env:
      rawRef: $(ref)
      replacedRef: $[ replace(variables['ref'], 'refs/heads/', '') ]
    inputs:
      targetType: inline
      script: |
        Write-Host $env:rawRef
        Write-Host $env:replacedRef

  - task: PowerShell@2
    env:
      rawRef: $(ref)
      replacedRef: ${{ replace(variables['ref'], 'refs/heads/', '') }}
    inputs:
      targetType: inline
      script: |
        Write-Host $env:rawRef
        Write-Host $env:replacedRef

Output from first PowerShell script

refs/heads/development
$[ replace(variables['ref'], 'refs/heads/', '') ]

Output from second PowerShell script

refs/heads/development
$[ resources.repositories.source.ref ]

I can use PowerShell script to modify branch name, but I would like to avoid it and use built-in expression.


Solution

  • This worked for me:

    name: test-01-$(date:yyyyMMdd-HHmmss)
    
    resources:
      repositories:
        - repository: source
          type: git
          name: my-project/my-repository
          ref: main
    
    variables:
      branchRef: $[ resources.repositories.source.ref ]
    
    jobs:
    - job: test
      displayName: 'Test job'
      variables:
        - name: branchName
          value: $[replace(variables.branchRef, 'refs/heads/', '')]
      steps:
        - checkout: source
        - script: |
            echo "branchRef: $(branchRef)"
            echo "branchName: $(branchName)"
          displayName: 'Display variables'
    

    Output:

    branchRef: refs/heads/main
    branchName: main