Search code examples
azure-devopsazure-powershell

Dynamic variable name in VSTS (Azure DevOps) pipeline


I have a pipeline variable called TestVariable.

I can easily access this variable from a PS script like so:

write-host $(TestVariable)

But if the name of that variable was dynamic, is there any way I can access the variable value from PS?

For example, the name of the variable would go into a string variable. I've tried these combinations as experiments...they just return the variable name, not the value (not surprisingly):

$varname="TestVariable"

write-host $($varname)
write-host $("$varname")
write-host $"($varname)"
write-host $("($varname)")

I think the answer is no, but I want to be sure. Any help much appreciated!

Edit - note

Both answers answer the question but don't solve my problem. After trying the solutions I realized I missed an additional complication which the answers don't help with unfortunately. Am noting here in case someone tries to do something similar.

The extra complication is, the value of the variable is set during the release (I'm trying to access ARM template output variables).

I thought I may be able to hit the API and get the 'live' variable value but unfortunately the release data does not exist (from the API) until the release completes.

So when I call this during a release:

https://vsrm.dev.azure.com/{company}/{project}/_apis/release/releases/$($releaseId)?api-version=5.0

I get "Release with ID 38 does not exist".


Solution

  • Dynamic variable name in VSTS (Azure DevOps) pipeline

    Agree with Krzysztof Madej. There is no out of box way to achieve this.

    That because the nested variables (like $($varname) are not yet supported in the build pipelines.

    To resolve this issue, you could use the Definitions - Get to get the value of Dynamic variable:

    GET https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.1
    

    Below is my test powershell script:

    $varname="TestVariable"
    
    $url = "https://dev.azure.com/YourOrganizationName/YourtProjectName/_apis/build/definitions/<definitionsId>?api-version=5.0"
    
    Write-Host "URL: $url"
    $pipeline = Invoke-RestMethod -Uri $url -Headers @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }
    
    
    $VFDV= $pipeline.variables.$varname.value
    
    
    Write-Host This is Value For Dynamic Variable: $VFDV
    

    enter image description here

    The output:

    enter image description here

    Hope this helps.