azure-devopsyamlpipeline

Azure pipeline yaml get last element of split function


Likely an easy question, but I'm stuck on it for a while. In an Azure pipeline YAML file, I'm trying to split the content of a variable and take the last item of the split

In the code below for Variable3 I try to solve the easier case of taking the 2nd item of the split. However, for some reason, Variable2 works fine, while Variable3 is not working (empty result). Can someone help explain why my attempt is failing and how I should get the last element of the split in a correct way?

Thanks!

variables:
- name: Variable1
  value: 'abc/def/ghi'
- name: Variable2
  value: $[replace(variables['Variable1'],'/',',')]
- name: Variable3
  value: $[split(variables['Variable1'], '/')[1]]

trigger:
- none

pool:
  vmImage: windows-latest

stages:
- stage: stage1
  jobs:
  - job: job1
    steps:
    - checkout: none
    - script: echo '$(Variable2)'
    - script: echo '$(Variable3)'

Solution

  • In the code below for Variable3 I try to solve the easier case of taking the 2nd item of the split.

    To meet your requirement, you can use the following format to split the variable and get the second value: ${{split(variables['Variable1'], '/')[1]}}

    Here is an example:

    variables:
    - name: Variable1
      value: 'abc/def/ghi'
    - name: Variable2
      value: $[replace(variables.Variable1,'/',',')]
    - name: Variable3
      value: ${{split(variables['Variable1'], '/')[1]}}
    
    trigger:
    - none
    
    pool:
      vmImage: windows-latest
    
    stages:
    - stage: stage1
      jobs:
      - job: job1
        steps:
        - checkout: none
        - script: echo '$(Variable2)'
        - script: echo '$(Variable3)'
    

    Result:

    enter image description here

    To get the last element of split function, we need to manually input the position of the last element. For example: ${{split(variables['Variable1'], '/')[2]}}.

    Azure DevOps doesn't support the format: ${{split(variables['Variable1'], '/')[-1]}} for the time being.

    Update:

    Workaround: we can split the variable in Powershell and get the last value to set the variable

    variables:
    - name: Variable1
      value: abc/def/ghi
    - name: Variable2
      value: $[replace(variables['Variable1'],'/',',')]
    
    
    trigger:
    - none
    
    pool:
      vmImage: windows-latest
    
    stages:
    - stage: stage1
      jobs:
      - job: job1
        steps:
        - checkout: none
        - task: PowerShell@2
          inputs:
            targetType: 'inline'
            script: |
              $b = "$(Variable1)".Split("/")
              $lastvalue= $b[-1]
              echo "##vso[task.setvariable variable=Variable3]$lastvalue"
        - script: echo '$(Variable2)'
        - script: echo '$(Variable3)'