Output variables in Azure DevOps release pipeline gates - azure

How do I use output variables in Azure DevOps release pipeline gates?
I would like to output a variable equal to the value of something in the response of the HTTP request.
e.g. The http request will return { success: true, userId: 12345 }. I would like to set a variable for userId which I can use in the next HTTP request gate.

As of this time, however, outputting variables in Invoke REST API in gates is not supported.
The output variables section cannot output the custom defined variables, but only the variables defined by the task.
Unfortunately, this task does not define an output variable. You can see it in the screenshot:
There are no output variables associated with this task.

Maybe this isn't what you are looking for, but you can use Azure Powershell to invoke HTTP Request and output the value of response that way to a pipeline variable for use in subsequent steps.
Refer to this Stack Overflow Post: How to access the response of the InvokeRestAPI task from another job in an Azure DevOps pipeline?
$url = "https://vsrm.dev.azure.com/thecodemanual/$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0"
$pipeline = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Bearer
$env:SYSTEM_ACCESSTOKEN"}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
$buildNumber = $env:BUILD_BUILDNUMBER
$pipeline.variables.ReleaseVersion.value = $buildNumber
####****************** update the modified object **************************
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}

Related

Azure devops release edit bulk 110

Hello I have 145 releases
And I have to do an equal action for everyone for example add a certain variable and edit a certain line.
Is there a way to control everyone with a script?
I checked for a template, but it creates the release from 0 and does not edit it.
Can a script in PS or Python be a solution? I did not find any information on Google about it, other than an export release template.
Azure devops release edit bulk 110
You could use the REST API Definitions - Update to update the release pipeline:
PUT https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions/{DefinitionsId}?api-version=6.0
And if we want to batch modify the release pipeline, we need to get each ID of the release pipeline with REST API Definitions - List:
GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions?api-version=6.0
Then we could iterate through each Rlease ID obtained.
I provide a rough code for your better reading:
$connectionToken="PAT"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$ReleasePipelineUrl = "https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions?api-version=6.0"
Write-Host "URL: $ReleasePipelineUrl"
$ReleasePipelines = (Invoke-RestMethod -Uri $PipelineUrl -Method Get -UseDefaultCredential -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)})
$ReleasePipelinesId = $ReleasePipelines.value.id
Write-Host "ReleasePipelinesId = $ReleasePipelinesId"
ForEach ($Pt in $ReleasePipelinesId)
{
$baseUrl = "https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions/$($Pt)?api-version=6.0"
$pipeline = (Invoke-RestMethod -Uri $baseUrl -Method Get -UseDefaultCredential -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)})
Write-Host "URL: $baseUrl"
$pipeline.variables.TestValue.value = "$buildNumber"
####****************** update the modified object **************************
$json = #($pipeline) | ConvertTo-Json -Depth 99
Write-Host "URL: $json "
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
write-host "=========================================================="
Write-host "The value of Varialbe 'TestValue' is updated to" $updatedef.variables.TestValue.value
}

Powershell invoke-restmethod variable in url

I am new to powershell, and I am trying to create a simple script that will allow me to turn on several Azure VMs using the invoke-restmethod.
My code works when instead of using a variable I directly write the VM name into the url, but I want to use a variable, since eventually this must work for more than one VM.
Relevant part of code:
$body = #{
"$virtualMachines" = "VM1"
} | ConvertTo=Json
$url= "https://management.azure.com/subscriptions/mySubscriptionId/resourceGroups/myResourceGroupName/providers/Microsoft.DevTestLab/labs/myLabName/virtualmachines/" + $virtualMachines + "/start?api-version=2018-09-15"
$response = Invoke-RestMethod -uri $url -Method 'POST' -Headers $headers -Body $body
$response | ConvertTo-Json
If you had a number of VMs, you could put them all into a PowerShell variable like this, an array of strings.
$VMs = "myVm1", "myVm2", "myVm3"
PowerShell has a number of flow control statements, the one you want to use is ForEach, which will step through an array one at a time. We just modify the way you're setting up the URL to be friendlier and easier to read and this should work just fine.
$baseUrl = "https://management.azure.com/subscriptions/mySubscriptionId/resourceGroups/myResourceGroupName/providers/Microsoft.DevTestLab/labs/myLabName/virtualmachines/"
ForEach ($vm in $VMs){
$url = $baseurl + $vm + "/start?api-version=2018-09-15"
Write-host "About to start [$Vm]"
$response = Invoke-RestMethod -uri $url -Method 'POST' -Headers $headers
$response | ConvertTo-Json
}
I checked the API documentation for the start? REST API endpoint, and it doesn't look like you need the -Body parameter for this endpoint.

the property 'value' cannot be found on this object azure release pipeline

I'm using below code to update the Release definition in Powershell,
PowerShell_1:
Write-Host ">>>>>>>>>Start in Task 1: "$(pos)
Write-Host "##vso[task.setvariable variable=pos;]Yes"
PowerShell_2
$url = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0-preview.3"
$pipeline = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
$pipeline.variables.pos.value = "$(pos)"
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
Write-Host "After in Task 2: "$(pos)
But issue is, i'm using the above code in two Tasks in a Release Pipeline,
The above code is passes in Task 1, but the same code throws below error on Task 2,
Release Variable:
Please Help me to get out of this.
Thanks in advance.
Something must have changed here 2021, reference to this developer community article.
I am trying to update my Azure DevOps Pipeline Variable via PowerShell task in YAML.
All authorizations are present. Here is my PowerShell task:
$url = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0"
Write-Host "URL: $url"
$pipeline = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
$pipeline.variables.test.value = "0"
####****************** update the modified object **************************
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
write-host "=========================================================="
Write-host "The value of Varialbe 'test' is updated to" $updatedef.variables.test.value
write-host "=========================================================="
Unfortunately I get the following error: The property 'value' cannot be found on this object. Verify that the property exists and can be set.
Any ideas?
I have found a solution for myself.
#Azure DevOps Personal Access Token
$MyPat = '*****';
$B64Pat = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$MyPat"));
#DevOps API
$url = 'https://dev.azure.com/<Organisation>/<Project>/_apis/distributedtask/variablegroups?api-version=6.0-preview.2';
$pipeline = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Basic $B64Pat"
}
#complete output as JSON
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)";
#my value in JSON
$variable = $pipeline.value.variables.MyVariable.value;
Because your answer in the $pipeline variable contains the source code of the error page.
I think, you use the wrong URL:
$url = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0-preview.3"
You may try to use of the following for inline script:
$url = "$(System.TeamFoundationServerUri)/$(System.TeamProjectId)/_apis/Release/definitions/$(Release.DefinitionId)?api-version=5.0-preview.3"
or for PS file:
$serverUrl = $env:SYSTEM_TEAMFOUNDATIONSERVERURI
$teamProjectID = $env:SYSTEM_TEAMPROJECTID
$releaseID = $env:RELEASE_DEFINITIONID
$url = "$serverUrl/$teamProjectID/_apis/Release/definitions/$releaseID?api-version=5.0-preview.3"
I have tested it with the code you shared and the details steps as below.
Create a new release definition->add variable pos and set the value to No
Add task power shell to set variable as env variable.
Write-Host ">>>>>>>>>Start in Task 1: "$(pos)
Write-Host "##vso[task.setvariable variable=pos;]Yes"
Result:
Add task bash and enter the script printenv to print all env variable to check it.
Add task power shell and enter below script to update the release variable.
$url = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0-preview.3"
$pipeline = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
$pipeline.variables.pos.value = $($env:POS)
Write-Host "The variable pos value is" $pipeline.variables.pos.value
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
Write-Host "After in Task 2: "$(pos)
Result:

Update defaultBranch of build definition via Azure DevOps API

I need to update the defaultBranch of build definition via Azure API.
The is the documentation for PUT request:
https://learn.microsoft.com/en-us/rest/api/azure/devops/build/definitions/update?view=azure-devops-rest-5.1
The problem is that I don't know the minimum list pf params I need to send in order to create a working request.
I tried to export the actual request from the browser and modify only this field - status code is 200 but nothing was changed. I don't want to pass all filed I just want to modify the defaultBranch.
In the link you provided you have Request Body section, you can see there what you need to pass. I like to get the definition first (with Get API), change what I want, and then perform the update.
In PowerShell:
$pat = "YOUR-PAT"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,"$pat")))
$headers = #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$url = "https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.1"
$build = Invoke-RestMethod -Uri $url -Method Get -ContentType application/json -Headers $headers
$newDefaultBranch = "test-branch"
$build.repository.defaultBranch = $newDefaultBranch
$json = $build | ConvertTo-Json -Depth 10
$response = Invoke-RestMethod -Uri $url -Method Put -ContentType application/json -Headers $headers -Body $json

Updating Azure DevOps Release Pipeline Variable During Release

I have a classic Release Pipeline that has a few custom variables set that are used periodically throughout the release.
The first two steps in the release are two PowerShell scripts. In the first one, I basically take one of the variables, and assign a value to it. I then output what the variable was updated to so I can make sure it is correct (it always is). The second script does basically the same thing but to a different variable, and when I output the value, it is always correct.
Now, as the release is going, if I switch to the Variables tab, I can see the variable was never updated. It is still set at the value from the previous release. This is a major issue for me because about half way down the release, I have a "Copy Files" step, where it copies files to a folder path that is created from those variables. Since the variables are from the previous release, they are put into an improperly named folder path.
After the release pipeline is completed finished and succeeds, the Pipeline Variables are then correctly updated on the Variables tab.
Is there a way that I can update these variables DURING the release, instead of them updating after the release has completed? I would prefer to update them properly in my PowerShell scripts, or as a setting in the pipeline.
This is basically what my scripts looks like:
$url = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0-preview.3"
$pipeline = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
$buildNumber = $env:BUILD_BUILDNUMBER
$pipeline.variables.ReleaseVersion.value = $buildNumber
####****************** update the modified object **************************
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
write-host "================================="
write-host "The value of ReleaseVersion updated to " $updatedef.variables.ReleaseVersion.value
write-host "================================="
My variable (ReleaseVersion in the script above) is set in the Variables tab, it's scope is 'Release', and 'Settable at release time' is checked. I have also tried using Write-Host '##vso[task.setvariable variable=ReleaseVersion]$(Build.BuildNumber)' to set my variable, but I get the same outcome.
UPDATE
ADDING NEW SCRIPT AND LOG DESCRIPTION
So I just pushed new code through my pipeline. The build was numbered v2.1.0.16 (which is correct). I have the build number set to the branch name, plus a (:.rev) variable at the end.
The first script in the pipeline sets a custom pipeline variable called ReleaseVersion. It is set to the build number. This is the script:
$url = "https://vsrm.dev.azure.com/{organization}/$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0-preview.3"
$pipeline = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
$buildNumber = $env:BUILD_BUILDNUMBER
$pipeline.variables.ReleaseVersion.value = $buildNumber
####****************** update the modified object **************************
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
write-host "================================="
write-host "The value of ReleaseVersion updated to " $updatedef.variables.ReleaseVersion.value
write-host "================================="
and my output:
2020-05-11T03:02:21.5631557Z "id": #,
2020-05-11T03:02:21.5632209Z "name": "#",
2020-05-11T03:02:21.5632816Z "path": "#",
2020-05-11T03:02:21.5633410Z "projectReference": null,
2020-05-11T03:02:21.5634223Z "url": "https://vsrm.dev.azure.com/{organization}/{project}/_apis/Release/definitions/{definitionId}",
2020-05-11T03:02:21.5635058Z "_links": {
2020-05-11T03:02:21.5635643Z "self": {
2020-05-11T03:02:21.5636500Z "href": "https://vsrm.dev.azure.com/{organization}/{project}/_apis/Release/definitions/{definitionId}"
2020-05-11T03:02:21.5637445Z },
2020-05-11T03:02:21.5641618Z "web": {
2020-05-11T03:02:21.5643197Z "href": "https://vsrm.dev.azure.com/{organization}/{project}/_apis/Release/definitions/{definitionId}"
2020-05-11T03:02:21.5644085Z }
2020-05-11T03:02:21.5647518Z }
2020-05-11T03:02:21.5648322Z }
2020-05-11T03:02:22.4291104Z =================================
2020-05-11T03:02:22.4456531Z The value of ReleaseVersion updated to v2.1.0.15
2020-05-11T03:02:22.4483349Z =================================
2020-05-11T03:02:23.0643676Z ##[section]Finishing: Update Release Version
It says the value has been updated to v2.1.0.15, which is one revision behind the current build. I then have a script to make a folder path based on the above variable. It checks for a folder with that name (v2.1.0.15 for example), and will attach a -1 if it was already found, and a -2 if the -1 was already found, and so-on. It sets that folder name to a custom pipeline variable called RootDirectory. This is the script:
$url = "https://vsrm.dev.azure.com/{organization}/$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0-preview.3"
$pipeline = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
write-host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
$rootDirectory = $pipeline.variables.BuildDirectory.value + "\" + $pipeline.variables.ReleaseVersion.value
if (test-path $rootDirectory) {
$newDirectory=$rootDirectory
$index=0
while (test-path $newDirectory) {
$index += 1
$newDirectory=$rootDirectory + "-" + $index
}
}
$pipeline.variables.RootDirectory.value = $newDirectory
####****************** update the modified object **************************
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
write-host "================================="
write-host "The value of Root Directory updated to " $updatedef.variables.RootDirectory.value
write-host "================================="
The BuildDirectory variable is a hardcoded variable that never changes. And it's output:
2020-05-11T15:32:45.7255688Z "id": #,
2020-05-11T15:32:45.7255852Z "name": "#",
2020-05-11T15:32:45.7256001Z "path": "#",
2020-05-11T15:32:45.7256166Z "projectReference": null,
2020-05-11T15:32:45.7256379Z "url": "https://vsrm.dev.azure.com/{organization}/{project}/_apis/Release/definitions/{definitionId}",
2020-05-11T15:32:45.7256556Z "_links": {
2020-05-11T15:32:45.7256698Z "self": {
2020-05-11T15:32:45.7256903Z "href": "https://vsrm.dev.azure.com/{organization}/{project}/_apis/Release/definitions/{definitionId}"
2020-05-11T15:32:45.7257174Z },
2020-05-11T15:32:45.7257331Z "web": {
2020-05-11T15:32:45.7257537Z "href": "https://vsrm.dev.azure.com/{organization}/{project}/_apis/Release/definitions/{definitionId}"
2020-05-11T15:32:45.7257721Z }
2020-05-11T15:32:45.7257862Z }
2020-05-11T15:32:45.7258016Z }
2020-05-11T15:32:46.6474274Z =================================
2020-05-11T15:32:46.6481861Z The value of Root Directory updated to
2020-05-11T15:32:46.6491120Z =================================
2020-05-11T15:32:46.7209281Z ##[section]Finishing: Create Root Directory
Notice how the output of that script is blank, it does not show what the variable was updated to.
A few steps later in my pipeline, is where I actually use those variables. It is in a "Copy files" pipeline task. The target folder is set to $(RootDirectory)/Debug, but since the RootDirectory variable isn't updated, it just copies the files to the root c: drive.
When I used code above with REST API ReleaseVersion remained the same as it was. However, I used logging command Write-Host '##vso[task.setvariable variable=ReleaseVersion]$(Build.BuildNumber)' and ReleaseVersion was updated but a new value was available in next step. So the new value should be available in Copy Files as it is a next step.
Updating Azure DevOps Release Pipeline Variable During Release
First, the reason why the logging command not work for you is that:
The variable set by the logging command can only be used inside the current agent, and will not modify the value of the web potral variable.
So, we could use the set variable in the next task, but if you want to update the variable on the Variables tab, you could use the REST API (Definitions - Update) to update the value of the release definition variable from a release pipeline:
PUT https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions/{definitionId}?api-version=5.0
Then, I have checked your scripts, it is close to the correct answer. The reason why it doesn't work for you is that you use variable $($env:SYSTEM_TEAMFOUNDATIONSERVERURI) in your url.
The default value of that variable is https://dev.azure.com/YourOrganization/. However, the API we use is that https://vsrm.dev.azure.com/{organization}, missing vsrm in the Url.
You could check my previous thread for some more details.
Hope this helps.

Resources