Referencing yaml variables in AzurePowerShellV5 inline script

Viewed 2099

I have a Azure DevOps yaml pipeline, that looks (a bit like) like this:

variables:
  MyVar: Test

Steps:
  - task: AzurePowerShell@5
    displayName: 'Test variables from yml file'
    inputs:
      azureSubscription: MyServiceConnection
      ScriptType: InLineScript
      InLine: |
        Write-Host "I really want to see the values from the variables in the yml file here"
        Write-Host "parameters from the yml file would be great too"
        Write-Host "But what would I write to do that?"
        Write-Host "$(MyVar) <- Nothing here"
        Write-Host "$(variables.MyVar) <- Nothing here"
        Write-Host "$DoesThisWork <- Nothing here"
        Write-Host "$OrThis <- Nothing here"
      env:
        DoesThisWork: $(MyVar)
        OrThis: $(variables.MyVar)

How do I use MyVar in the InLine script?

2 Answers

I stripped it down to the simplest possible and it works just fine:

pool: 
  vmImage: 'windows-latest'

variables: 
  myVar: test value

steps:
  - powershell: Write-Host "$(myVar)"

generates:

Run result

I modified your example to remove the env block which did not compile, and remove the incorrect variable references:

pool: 
  vmImage: 'windows-latest'

variables: 
  myVar: test value

steps:
- task: AzurePowerShell@5
  inputs:
    azureSubscription: 'My Service Connection Name'
    ScriptType: 'InlineScript'
    Inline: |
      Write-Host "I really want to see the values from the variables in the yml file here"
            Write-Host "parameters from the yml file would be great too"
            Write-Host "But what would I write to do that?"
            Write-Host "$(MyVar) <- Nothing here"
    azurePowerShellVersion: 'LatestVersion'

and got:

Corrected result

It didn't get past the first one because the syntax $(variables.MyVar) is invalid. The syntax works as follows:

  • Compile time (usable only in the file in which the variable is declared and not to nested files like templates): ${{ variables.MyVar }}
  • Runtime (before task execution): $(MyVar) - expands to "$(MyVar)" if empty
  • Runtime (designed for conditions, or where the default value causes problems): $[variables.MyVar] - expands to empty string if empty

I'm wondering if the lack of an Azure Powershell version was part of your problem?

When you specify an env block, it creates the variables as environment variables.

In PowerShell, you reference environment variables with $env:VariableName. So in your case, $env:DoesThisWork.

Related