Using runtime expressions in azure pipelines yaml script

Viewed 4355

I'm trying to execute script by passing variable from the azure pipeline. Here is my simple test pipeline:

trigger:
- master

pool:
  vmImage: 'windows-latest'

variables:
    major: 1.2
    minor: $[counter(variables['major'], 1)]
    version: $[format('{0}.{1}', variables.major, variables.minor)]

name: $[format('{0} v{1}', 'Yaml Testing', variables['version'])]

steps:

- script: |
    echo variables['version']
    echo $(variables.version)
    echo '$(variables.version)'
    echo "$(variables.version')"
    echo $[ variables['version'] ]
    echo ${{ variables['version'] }}
    echo $(Build.BuildNumber)
  displayName: 'Run a multi-line script'

- script:     $[format('{0} {1}', 'echo', variables['version'])]
  displayName: 'Echo Formatted String'

Outputs of scripts are:

Generating script.
========================== Starting Command Output ===========================
##[command]"C:\windows\system32\cmd.exe" /D /E:ON /V:OFF /S /C "CALL "d:\a\_temp\3cb45b74-f6cd-4d2f-bf65-f635779b9d86.cmd""
variables['version']
$(variables.version)
'$(variables.version)'
"$(variables.version')"
$[ variables['version'] ]
$[format('{0}.{1}', variables.major, variables.minor)]
Yaml Testing v1.2.11
##[section]Finishing: Run a multi-line script

and

Generating script.
Script contents:
$[format('{0} {1}', 'echo', variables['version'])]
========================== Starting Command Output ===========================
##[command]"C:\windows\system32\cmd.exe" /D /E:ON /V:OFF /S /C "CALL "d:\a\_temp\5e42dc54-e027-4b9a-9af4-0db02e879b0f.cmd""
'$[format' is not recognized as an internal or external command,
operable program or batch file.
##[error]Cmd.exe exited with code '1'.
##[section]Finishing: Echo Formatted String

Strangely, code work fine in the name, but not when trying to use in the script.

What am I doing wrong?

1 Answers

$[] is evaluated at runtime, that is why it is not working. You can pass ${{expression}} to script like below:

- script: ${{format('{0} {1}', 'echo', '$(version)')}} 
  displayName: 'Echo Formatted String'

Expression in ${{}} will be evaluated at parse time. Before the -script is actually executed, expression in ${{}} is parsed into a valid command.

You can directly refer to the self-defined variables like this '$(variableName)' instead of $(variables.Name)

Related