Azure Devops - not able to set variable in Powershell - azure-devops

I have an Azure Devops release pipeline (using the Classic Editor rather than yaml) and am having trouble setting a variable in an inline powershell script. The relevant part of the script is this:
Write-Host "Web is $web"
Write-Host "App is $app"
Write-Host "##vso[task.setvariable variable=MyWebEnv;]$web"
Write-Host "Set Web to $($MyWebEnv)"
Write-Host "##vso[task.setvariable variable=MyAppEnv;]$app"
Write-Host "Set App to $(MyAppEnv)"
The log files indicate that my $web and $app variables hold the correct values, however the setting is not working.
I've tried writing out the value in both the $($env:MyWebEnv) and $(MyWebEnv) formats and both formats indicate that the ADO variable has not been set correctly.
My variable is defined in the variables tab on the pipeline. It is set to Settable at queue time. I have tried with no value set in the definition and an initial value and I can see that the initial value does not get overwritten.
I've tried running this on both a self-hosted agent and an Azure Pipelines Hosted agent - same results. I have another release pipeline that does something similar without issues.
I'm trying to use the variable in a subsequent Stage.
I don't want to write the variable to a file or anything as I want to use the variable to control whether the stage even runs.
Edit:
Based on Levi's comment I tried adding isOutput=true and inspecting the variable in a subsequent step in the same stage - it's not visible even within a subsequent step:
=========================================================================
Edit 2:
I must have had a non visible character somewhere. I was composing the powershell in an external editor (just so I had more space) and pasting into the inline textbox in ADO - when I typed in the exact same thing I had into the editor it started working - sort of.
I can set the variable now and it's appearing in the task below, but what I really want is to use it in the next stages - in the IIS deployment group to control that IIS server A runs, but IIS server B doesn't. I'm attempting to do this in the Additional Options Run Expression.
I've tried
and(succeeded(), eq(variables['MyWebEnv'], 'myvalue')
or (where MyOutput. is the name given to my output reference when setting the variable)
and(succeeded(), eq(variables['MyOutpub.MyWebEnv'], 'myvalue')
or
and(succeeded(), eq(variables['MyOutpub_MyWebEnv'], 'myvalue')
To clarify, I'm doing this on the IIS Deployment Group itself, and not on any of the tasks within that group.
I keep seeing that the deployment is skipped due to:
Evaluating: eq(variables['MyOutput,MyWebEnv'], 'myvalue') Expanded: eq(Null, 'myvalue') Result: False

The variable you were trying to set in the powershell task will only take effect in the following tasks, which means if you echo out the variable in its own powershell task, it will not output the overriden value. See here.
To set a variable from a script, you use the task.setvariable logging command. This doesn't update the environment variables, but it does make the new variable available to downstream steps within the same job.
So you can only refer to it in the downstream tasks by wrapping it around $(). See below:
steps:
- powershell: |
Write-Host "##vso[task.setvariable variable=MyWebEnv]$web"
- powershell: |
Write-Host "Set Web to $(MyWebEnv)"
If you want to use it in a subsequent stage. You will have to make the variable to be an output variable by using isOutput=true. See here
- powershell: |
Write-Host "##vso[task.setvariable variable=MyWebEnv;isOutput=true]$web"
name: MyVariable
- powershell: echo "$(MyVariable.MyWebEnv)"
You should also give this powershell task a name in order to refer to it in the following stages. See here to learn how to refer to multiple stage output variables.
variables:
web: $[stageDependencies.stageName.jobName.outputs['stepName.variableName']]
You also need add dependency on this stage for the following stages.
See below example:
stages:
- stage: VariableStage
jobs:
- job: VariableJob
steps:
- powershell: |
$web = "---"
Write-Host "##vso[task.setvariable variable=MyWebEnv;isOutput=true]$web"
name: MyVariable
- stage:
dependsOn: VariableStage
variables:
web: $[stageDependencies.VariableStage.VariableJob.outputs['MyVariable.MyWebEnv']]
jobs:
- job:
steps:
- powershell: echo "$(web)"

As Levi Lu mentioned you can access pipeline variables in the next step. So if you set variables like this here:
$web ="some-web"
$app ="some-app"
Write-Host "##vso[task.setvariable variable=MyWebEnv;]$web"
Write-Host "##vso[task.setvariable variable=MyAppEnv;]$app"
then you can read them in this way:
Write-Host "Set Web to $(MyWebEnv)"
Write-Host "Set App to $(MyAppEnv)"
And if you want to access them via env variables you should use this syntax:
Write-Host "Set Web to $($env:MYWEBENV)"
Write-Host "Set App to $($env:MYAPPENV)"
Answer for EDIT 2:
What you actually need is output cross stage variables which is supported in YAML but not in classic pipelines. Please check this topics. You can overcome this but it requires an extra effort as it shown here. However, please remember that you can't publish an artifact from release pipeline.
Here you have docs for cross stage variables but as above, it works on YAML.

Related

Azure DevOps: How to set a Pipeline Variable on a Release?

I am trying to create a simple Release Pipeline that:
sets a value via a script
asks a user to manually check the value, and modify it if needed
goes on with the pipeline, using the value
What is the easiest way to achieve this functionality in Azure DevOps?
I have tried to define a Pipeline Variable called TestVariable, with initial value of 1, where I will store the value.
A Pipeline Variable seems a good option to me, because its value can be easily modified by the user, during manual check.
The problem is, I cannot set its value via a script (as per point 1. above).
I have tried to set its value to 2 via a Bash Script, but it does not work as you can see.
Here is the code, if you want to try yourself:
echo $(TestVariable)
echo "##vso[task.setvariable variable=TestVariable;]2"
echo $(TestVariable)
I searched thoroughly the Azure documentation but I could not find any solution. Is there any way to set a Pipeline Variable through a script, or to achieve the 3 above mentioned points with another strategy?
The method you used to update the value is correct.
Refer to this doc: Set variables in scripts
A script in your pipeline can define a variable so that it can be consumed by one of the subsequent steps in the pipeline.
It will not work on the current task, but the updated value can be used in the next tasks.
Here is an example:
steps:
- bash: |
echo $(TestVariable)
echo "##vso[task.setvariable variable=TestVariable;]2"
displayName: 'Bash Script'
- bash: |
echo $(TestVariable)
Result:

my PowerShell script task successful in azure devops pipeline but set variable is not created

I am trying to create a dynamic variable on Azure Devops pipeline and I cannot use it on further tasks although the task with the variable creation is successfully completed.
Write-Host "##vso[task.setvariable variable=mytitle;isOutput=true]$content
How can I use the variable that is created dynamically with setvariable
Please note that the first task can set a variable, and following tasks are able to use the variable using macro syntax $(myVar). We are not able to use it in the first task. The variable will only be available to tasks in the same job by default, and the variable is exposed to the following tasks as an environment variable.
For example:
jobs:
- job: A
steps:
- powershell: |
Write-Host "##vso[task.setvariable variable=mytitle]$content"
name: setVariable
- powershell: |
Write-Host "You can use macro syntax for variables: $(mytitle)"
name: PrintVariable
If you add the parameter isoutput, the syntax to call your variable changes. See Set an output variable for use in the same job and Set an output variable for use in future jobs for details.
More information please refer to Logging commands.

Azure DevOps Pipeline - Using YAML, how can I have the build number set to dynamically change, based on the version defined in a different file? [duplicate]

In Azure DevOps, I created a Build. In that Build I created a ProjectBuildNumber Pipeline variable that is Settable at queue time. That variable is then used under Options -> Build number format to set my build number displayed in Azure.
However, I am trying to make that ProjectBuildNumber variable settable in the code I am building/deploying. Is there a way I can have a Task in my Build to update that ProjectBuildNumber and update the Build number in Azure DevOps?
Is there a way I can have a Task in my Build to update that ProjectBuildNumber and update the Build number in Azure DevOps?
The answer is yes.
You could add a Inline Power-Shell task in your build definition to update the value of ProjectBuildNumber and then update the build number base on the it:
Write-Host "##vso[task.setvariable variable=ProjectBuildNumber;]YourUpdateValue"
Write-Host "##vso[build.updatebuildnumber]xxx.$(ProjectBuildNumber).xxx.xxx"
Check the Logging Command during the build for some more details:
Besides, if you want to update the value of a Pipeline Variable on the UI/web portal, you need the REST API (Definitions - Update) to update the value of the build pipeline definition variable from a build task.
There is a very similar thread, you can check the answer for the details:
How to modify Azure DevOps release definition variable from a release task?
Note:Change the API to the build definitions:
PUT https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.0
Hope this helps.
We can update Build Number in Azure Devops via two ways .
One from Option Section/Tab and 2nd Via PowerShell Scripts.
To update the build number from Power shell Script.. We need to add following script..
Write-Host "##vso[build.updatebuildnumber]$(VersionNumber).$(VersionRevision)"
Here we have used 2 variables : VersionNumber and VersionRevision.
We need to add 2 variables in PipeLine Configurations..
VersionNumber will be the desired number and VersionRevision is the counter number that will be updated every time, when ever we will create a new build.
Please check the complete demonstration from You tube video
https://youtu.be/WBmFTmzopiQ
Have created power shell task for that
# replace existing Build.BuildNumber with
# NAME_2.1.2.54_20211220.16_345
- task: PowerShell#2
displayName: 'Update Version Number'
inputs:
targetType: 'inline'
script: |
$lines = Get-ChildItem ".\Project\My Project\AssemblyInfo.vb"
$match = $lines | Select-String -Pattern "\<Assembly\:\s+AssemblyVersion\(""(\d+\.\d+\.\d+\.\d+)""\)\>"
$version = $match.Matches[0].Groups[1].Value
[Version]::Parse($version) # validate
$tag = "NAME_$($version)_$(Build.BuildNumber)_$(Build.BuildId)"
Write-Host "##vso[build.updatebuildnumber]$tag"
Check out the Microsoft documentation on this: Variables
Depending on your operating system you can add a Powershell/Batch/Bash Task and change the variable.
Edit: After some research it appears that the change of the variable will show up in the following task. Take a look at this issue Update environment variables using task.setvariable in a bash script does not work

Azure DevOps pass InputObject from One step to another step

I am trying to pass a variable "$a" from one step to another step in Azure DevOps. The $hash contains Name,IsReadOnly and Length as NoteProperty. I was successful in passing the variable from one step to next step as $b, but when i try to access NoteProperty of $b variable i am not able to access it
1.My question is it possible pass variable from one step to another step, How do i access the variables NoteProperty ??
2. Does Azure DevOps support passing complex objects from one step to another step ??
For your first question:
is it possible pass variable from one step to another step, How do i access the variables NoteProperty ??
Sure, you can pass variables from a step to the subsequent steps in the same job, and you even can pass the variables to the steps in the subsequent jobs.
To pass a variable value generated in a step to other subsequent steps, you can use the 'SetVariable' command in the step that generates the value.
If you want to share the variable value only to the subsequent steps in the same job, you can just set it as a general job-level variable using the following command.
Bash
echo "##vso[task.setvariable variable=<var_name>;]<var_value>"
or PowerShell
Write-Host "##vso[task.setvariable variable=<var_name>;]<var_value>"
With this way, in the subsequent steps, you can use the expression '$(var_name)' to access this variable.
After executing above command to set up the variable, like as other general pipeline variables, this variable will be automatically mapped as an environment variable. So, you also can use the expression '%VAR_NAME%' (CMD), '$env:VAR_NAME' (PowerShell) or '$VAR_NAME' (Bash) to access the variable.
If you want to share the variable value to the subsequent steps in the same job and the steps in the subsequent jobs, you can set it as an output variable using the following command.
Bash
echo "##vso[task.setvariable variable=<var_name>;isoutput=true]<var_value>"
or PowerShell
Write-Host "##vso[task.setvariable variable=<var_name>;isoutput=true]<var_value>"
With this way, to access this output variable in the subsequent steps of the same job, you can use the expression '$(step_name.var_name)'.
To access this output variable in the steps of the subsequent jobs, the subsequent jobs need to depend on (dependsOn) the job that contains the step to set up the output variable. And you also need to map this output variable as a job-level variable on each subsequent job, and then use this job-level variable to access the output value.
To view more details about variables in Azure Pipelines, you can see "Define variables".
A simple example as reference.
azure-pipelines.yml
jobs:
- job: JobA
displayName: 'Job A'
steps:
- bash: echo "##vso[task.setvariable variable=MyVar;isoutput=true]This is an output variable!"
name: set_output
displayName: 'Set up the output variable'
- bash: echo "set_output.MyVar = $(set_output.MyVar)"
displayName: 'Show the value of output variable'
- job: JobB
displayName: 'Job B'
dependsOn: JobA
variables:
output_from_JobA: $[ dependencies.JobA.outputs['set_output.MyVar'] ]
steps:
- bash: echo "output_from_JobA = $(output_from_JobA)"
displayName: 'Show the value of output variable from JobA'
Result:
For your second question:
Does Azure DevOps support passing complex objects from one step to another step ??
Normally, the value of the variable in Azure Pipelines should be string. To pass the content of an object as a variable in the pipeline, you can try to convert the object (such as JSON node, XML node, etc.) to be a string, then like as above example, pass this string as a variable. In the subsequent steps that need to access this object, after receiving the string variable, you can try to convert the string back to the object. This is the most common method I can think of.

How to get URL of Pipeline Build

From within a run of Azure Pipeline build, is there any way to get the URL of the build that is running?
Something like:
https://dev.azure.com/{organization}/{project}/_build/results?buildId={build_number}
I would have assumed that it would have been available as one of the environment variables, but it doesn't seem to be.
This one will work using all predefined variables
$buildUrl="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)"
Write-Host $buildUrl
There is no pre-defined variable of the build URL, but you can get it easily because you have a variable for the build id:
steps:
- powershell: |
$buildUrl = "https://dev.azure.com/$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)"
Write-Host "##vso[task.setvariable variable=buildUrl;]$buildUrl"
displayName: 'Set build url variable'
In the next step I print the $(buildUrl) variable:
Here is alternative using System.CollectionUri variable which name is more generic, not specific to TFS. There is no equivalent with project name, so System.TeamProject has to be used, which will also work for GitHub repository.
The composed URL can be cached in Azure Pipelines variable in pipeline or job scope:
variables:
MyResultsUrl: '$(System.CollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)'
Adding query parameter ?view=logs you can make the URL jump straights to the logs.