azureazure-devopsazure-pipelinesazure-pipelines-yaml

How to skip the template if the variable is not equal expected value in azure pipeline yaml?


I have a .yaml file

variables:
- name: command1
  value: none 

- scripts: |
  echo '##vso[task.setvariable variable=command1]new_value'

- ${{ if ne(variables['command1'], 'none') }}: 
  - template: templates/run.yml@temp1  # Template reference  
    parameters:
      COMMAND: '$(command1)'

I have created the variable for two reason ,

  1. to be global
  2. I dont want it to be displayed in the variable list for the users

I want the template only to be executed if variable value of 'command1' is not 'none'

Currently it is not skipping , it keeps executing it even if the value inside the variable is not none.

The other if conditions format I have used is

- ${{ if ne(variables['taskName.command1'], 'none') }}: 
- ${{ if ne('$(command1)', 'none') }}: 

None of the above worked

Please help in resolving this issue.


Solution

  • As it is written here:

    The difference between runtime and compile time expression syntaxes is primarily what context is available. In a compile-time expression (${{ }}), you have access to parameters and statically defined variables. In a runtime expression ($[ ]), you have access to more variables but no parameters.

    variables:
      staticVar: 'my value' # static variable
      compileVar: ${{ variables.staticVar }} # compile time expression
      isMain: $[eq(variables['Build.SourceBranch'], 'refs/heads/main')] # runtime expression
    
    steps:
      - script: |
          echo ${{variables.staticVar}} # outputs my value
          echo $(compileVar) # outputs my value
          echo $(isMain) # outputs True
    

    So it could work for your YAML value:

    variables:
    - name: command1
      value: none     
    
    steps:
    - scripts: |
      echo '##vso[task.setvariable variable=command1]new_value'
    
    - ${{ if ne(variables.command1, 'none') }}: 
      - template: templates/run.yml@temp1  # Template reference  
        parameters:
          COMMAND: '$(command1)'
    

    However, it will pick this value:

    variables:
    - name: command1
      value: none     
    

    There is no chance that it will take this:

    - scripts: |
      echo '##vso[task.setvariable variable=command1]new_value'
    

    It is because ${{}} expressions are compile time and echo '##vso[task.setvariable variable=command1]new_value' is runtime.