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".
Late to the party, but figure I'd share.
As mentioned in the Defined Variables doc, pipeline variables are accessible through
the environment variables. While $(varname) gets processed before the task starts, $env:varname can be invoked mid-run. So you can cheat by using:
Write-Host ('$env:'+"$(varname)" | Invoke-Expression)
The task will resolve $(varname) into its value before the task begins. So the script reads as
Write-Host ("$env:TestVariable" | Invoke-Expression)
And it'll spit out the same as calling $(TestVariable).
Though you do need to respect the rules, such as " " and "." -> "_".
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
The output:
Hope this helps.
This is not possible directly in YAML but you can use for instance az cli. With this you can set programatically a variable name a get value of it
$variableName = "some"
az pipelines variable list --org "https://dev.azure.com/thecodemanual" --project "DevOps Manual" --pipeline-name "DevOps Manual-CI" --query ($variableName + '.value')
$variableName = "test"
az pipelines variable list --org "https://dev.azure.com/thecodemanual" --project "DevOps Manual" --pipeline-name "DevOps Manual-CI" --query ($variableName + '.value')
Now you can use this code in a powershell task to fetch value of variable.
Here you have info how to install extension.
I know its too late but I can tell you a perfect solution. as we know all the pipeline variables are available as environment variables so we can access the values as below
var=$(TestVariable)
upper= ${var^^} //convert the variable to uppercase as env variables are upper
echo ${!upper}
Please note the above solution is tested and works in bash only. I haven't written for PS
Related
I have to send buildId value from powershell script to the jenkinsfile pipeline. I am trying something like below. Is this right approach?
powershell script
if($out -match "buildId-") {
$splitline = $out.Split("-")
echo "splitline: " $splitline
$buildId= $splitline[1]
echo "buildId: " $buildId
$buildIds= $env:$buildId.Value
}
then want to use that build to pass as a parameter to trigger the build job.
Jenkinsfile
build job: 'build_Test', parameters: [validatingString(name: 'buildId', value: '$buildIds'), string(name: 'TASK', value: 'build')]
You can give it a shot, but I'm not sure simply adding it to an environment variable will allow you to access the value from the Jenkinsfile. You can find more about this problem in this question. However, you maybe able to achieve your goal via the EnvInject plugin, or simply store the value in a file in your workspace and access it via Jenkins later.
My Azure DevOps pipeline has a "AWS SSM Get Parameter" task that reads the parameters into build variables. I can reference these variables successfully using "$(BuildVariableName)" syntax, as long as they are not secret parameters, but for any parameter where "is secret = true", the value of the variable is "***". What do I need to do to be able to read the secret parameters as build variables?
This might not be the most desirable solution, but I was able to partially get this to work by using a Powershell task to copy the secure variable to a non-secure variable.
Write-Host "##vso[task.setvariable variable=NonSecureVariable;]$(SecureVariable)"
However, if $(SecureVariable) contains "$", then all of the characters after the "$" are truncated. Is there a way to get access to the secure variable other than Powershell, or is there a way to get Powershell to work with special characters?
I am finding using AZDO Release pipeline variables maddening in Powershell steps.
I am running an Azure PowerShell step to return a primary key value. It is 2 lines…
$primarykey = (Get-AzRelayKey -ResourceGroupName ${env:az-resourcegroupname} -Namespace ${env:az-relaynamespace} -HybridConnection ${env:serviceBus.primaryRelay.ConnectionName} -Name ${env:serviceBus.primaryRelay.KeyName} | Select-Object -ExpandProperty PrimaryKey)
Write-Host "##vso[task.setvariable variable=serviceBus.primaryRelay.Key]$primarykey"
In my pipeline I have a mix of variable names, some I have complete control over (the az- prefixed ones) and others I don’t (the ones starting serviceBus.)
The reason I have no control over the latter is that they are used for a later File Transform step that navigates an appsettings.json file to find/replace values, and its unable to be changed (for example serviceBus.primaryRelay.ConnectionName is a value that is changed in the JSON and the file transform step specifies to navigate the JSON structure, it has to be separated with a period . )
When this script runs it always complains about the -HybridConnection value being empty. This is because the variable has a period in it.
I’ve tried everything I can think of to retrieve that value in the code.
Are they suggesting here that a variable with a period isn’t workable in Powershell in AZDO release pipelines? I’m completely lost.
I have found the answer by looking under the Release Pipelines "Initialize Job" log. It appears to substitute the period . with a dash -
The log revealed this...
[SERVICEBUS_PRIMARYRELAY_CONNECTIONNAME] --> [dev-sbrelay]
I have a complete CI/CD pipeline in Azure DevOps and its working perfectly. now i have a JSON file including the version number for the release.
I need to get this version number as a global variable. How to assign file value to a global variable. I need to use this release no as my build pipeline id, docker tag and release pipeline id.
The way to set a global variable is:
##vso[task.setvariable variable=name;]value
So you can write a PowerShell script that read the release version from the JSON file and set the variable, for example:
$jsonFile = Get-Content path/to/json
$json = $jsonFile | ConvertFrom-Json
$version = $json.release.version
Write-Host "##vso[task.setvariable variable=releaseVersion;]$version"
Now you can use the variable $(version) in your docker tag, etc.
just to add to existing answer, here's how you set build id to the calculater value (because you cannot set it before the build starts, as it is only calculated during the build):
- pwsh: Write-Host "##vso[build.updatebuildnumber]${env:VERSION}"
assuming version is how you called your variable.
I want to use a variable which is composed of another vsts variable and text, for instance:
vnetname = $vnet_prefix + "vnetid"
However i get an error saying that "A positional parameter cannot be found that accepts argument +.
Anyone advise?
If you mean use the variable in build/release processes, then you can add a variable like this (reference below screenshot):
vnetname = $(vnet_prefix)_vnetid
Then you can use the variable $vnetname or $(vnetname) directly, see Build variables-Format for how to use the variables in different tools.
Alternatively you can pass the value with Logging Commands:
Copy and paste below strings then save as *.ps1 file:
$value = $env:vnet_prefix + "vnetid"
Write-Host "##vso[task.setvariable variable=vnetname]$value"
Check in the PS file
Add a PowerShell task to run the PS file
Use the variable $vnetname in later steps