AzurePipeline Build.Repository.Name replace unwanted prefix

Viewed 1833

In Azure Pipleine YAML version the Build.Repository.Name predefined variable contains workspace/reponame value in my case.

I wanted to remove the workspace/ prefix and use the result in a following step.

I tried many ways but without success, but it seems the replace expression maybe be good for me.

One tried solution:

variables:
  myVariable: $[replace(variables['Build.Repository.Name'], 'workspace/', '')]

  steps:
    - bash: echo $(myVariable) # show nothing

As i read in documentation the Build.Repository.Name does not accessible in this phase The following runtime call show the correct value

steps:
  - bash: echo $(Build.Repository.Name) # shows: workspace/reponame

Can I do something similar, and what is the correct way?

- bash: echo $(replace('$(Build.Repository.Name)', 'workspace/', ''))
1 Answers

Based on my test, the replace expression could work fine.

Since my repo name does not contain /, I switched to another predefined variable($(build.sourcebranch) (e.g. refs/heads/master)) for testing.

Here are two methods:

1.Replace expression:

variables:
  myVariable: $[replace(variables['BUILD.SOURCEBRANCH'], 'refs/heads/', '')]

steps:
  - bash: echo $(myVariable) 

2.Bash script:

steps:
  - task: Bash@3
    inputs:
      targetType: 'inline'
      script: |
        SUBSTRING=$(echo $(BUILD.SOURCEBRANCH)| cut -d'/' -f 3)
        echo $SUBSTRING
        echo "##vso[task.setvariable variable=myvalue]$SUBSTRING"
  - task: Bash@3
    inputs:
      targetType: 'inline'
      script: |
       echo $(myvalue)

Result:

enter image description here

In your case, you could try the following bash script:

steps:
  - task: Bash@3
    inputs:
      targetType: 'inline'
      script: |
        SUBSTRING=$(echo $(Build.Repository.Name)| cut -d'/' -f 2)
        echo $SUBSTRING
        echo "##vso[task.setvariable variable=myvalue]$SUBSTRING"
  - task: Bash@3
    inputs:
      targetType: 'inline'
      script: |
       echo $(myvalue)
Related