Search code examples
azure-devopsazure-pipelinesazure-pipelines-yaml

Azure DevOps pipeline task condition checking for empty string


I have this template :

parameters:
  gitTag: ' '

stages:
- stage: CreationTag

  jobs:
  - job: Tag
    pool:
      name: Default

    steps:

    - task: PowerShell@2
      displayName: 'gitTag parameter trim'
      inputs:
        targetType: 'inline'
        script: | 
          $trimmedGitTag = "${{parameters.gitTag}}".Trim()
          Write-Host "##vso[task.setvariable variable=trimmedGitTag]$trimmedGitTag"
          Write-Output "Trimed parameter = '$trimmedGitTag'"
      
    - task: PowerShell@2
      displayName: 'Creation du tag Git'      
      inputs:
        targetType: 'inline'
        script: |
          Write-Output "Trimed parameter = '$(trimmedGitTag)'"
      condition: and(succeeded(), ne('$(trimmedGitTag)', ''))

I receive a parameter from the main stage but it can be empty ou contains only whistespaces. So in the first task, I trim the parameter in a variable. In the second task, I added a condition so the precedent task mut have succeeded and the trimed parameter value must not be equal to ''.

The first step executes and outputs "Trimed parameter = ''" in the console.

My problem is that the second task still executes, while it shouldn't. And it also display the same value ("Trimed parameter = ''") with the Write-Output.

What would be the problem here? Or is it anither way to ensure taht a task is only performed when a parameter has a value other than empty or whitespaces?

EDIT

I changed the default value of the parameter to a blank space as a workaround for an optional parameter. In the original post, I have used an empty string ''. I want to be able to manage the cases where :

  • the user dont input anything
  • the user inputs only whitespaces (any lenght so ' ' shouldn't run the task
  • the user inputs a valid value but begins or ends with whitespaces that will crash my tasks. That's why I need a Trim()

Solution

  • Instead of:

    condition: and(succeeded(), ne('$(trimmedGitTag)', ''))
    

    Try:

    condition: and(succeeded(), ne(variables['trimmedGitTag'], ''))
    

    Or, as an alternative:

    - ${{ if replace(parameters.gitTag, ' ') }}:
      - task: PowerShell@2
        displayName: 'Do something with the tag'
        inputs:
          targetType: 'inline'
          script: |
            $trimmedGitTag="${{ parameters.gitTag }}".Trim()
            Write-Output "Trimed parameter = '$trimmedGitTag'"