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

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:

Related

create branch based on another branch api az devops

I want to know how to create several repos with their respective branches, but the branches created do not respect the hierarchy example:
DEV based on PRD(master)
FTR based on DEV
DEV-based REL
EXCUSE THE ENGLISH, USE A TRANSLATOR
$repository = "ECOMP_CORE_LG"
$newBranch = "REL/ECOMP_CORE_PDF/ECOMP_CORE_PDF-4080-re"
$baseBranch = "DEV/ECOMP_CORE_PDF/ECOMP_CORE_PDF-dev"
$organization = "XXXXXXX"
$project = "XXXXXX"
$pat = "TOKEN"
$base64AuthInfo =
[System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$pat"))
$headers = #{ Authorization = "Basic $base64AuthInfo" }
# Get ID of the base branch
$url = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/refs?
filter=heads/$baseBranch&api-version=5.1"
$baseBranchResponse = Invoke-RestMethod -Uri $url -ContentType "application/json" -headers
$headers -Method GET
# Create a new branch
$url = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/refs?
api-version=5.1"
$body = ConvertTo-Json #(
#{
name = "refs/heads/$newBranch"
newObjectId = $baseBranchResponse.value.objectId
oldObjectId = "0000000000000000000000000000000000000000"
})
$response = Invoke-RestMethod -Uri $url -ContentType "application/json" -Body $body -headers
$headers -Method POST

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
}

Filter Azure DevOps releases with RestAPIs

I have been working on a requirement with a release API to retain all the production releases.
Code -
param (
[string]$token="",
[string]$collection="",
[string]$projectName =""
)
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $token)))
$response = Invoke-RestMethod "https://vsrm.dev.azure.com/$collection/$projectName/_apis/release/definitions?`$expand=Environments&`$top=1000&api-version=6.0" -Method 'GET' -Headers #{Authorization = ("Basic {0}" -f $base64AuthInfo)}
foreach ($releaseDefinition in $response.value){
write-host $releaseDefinition.name
write-host $releaseDefinition.id
$releaseDefinitionid = [convert]::ToInt32($releaseDefinition.id)
write-host "--------------------------------------------------"
[string] $releases = "https://vsrm.dev.azure.com/$collection/$projectName/_apis/release/releases?definitonid="
[string] $defid = $releaseDefinitionid
[string] $geturl = $releases + $defid + "&api-version=6.0"
$releaseresult = Invoke-RestMethod $geturl -Method 'GET' -Headers #{Authorization = ("Basic {0}" -f $base64AuthInfo)}
#Write-Host $releaseresult.value
#Write-host $releaseresult.keepForever
foreach ($retain in $releaseresult.value)
{
Write-host $retain.id
$temp = $retain.id.ToString()
$id = "https://vsrm.dev.azure.com/$collection/$projectName/_apis/release/releases/$temp/?api-version=6.0"
$retainrelease = Invoke-RestMethod $id -Method 'GET' -Headers #{Authorization = ("Basic {0}" -f $base64AuthInfo)}
if( $retainrelease.environments.name -eq 'PRD' -and $retainrelease.environments.status -eq 'succeeded')
{
if([string]$retainrelease.keepForever -eq 'False')
{
$keepforever = #{
keepforever='true'}
$jsonKeepForever = $keepforever | ConvertTo-Json -Depth 100
$uriForBuildUpdate = "https://vsrm.dev.azure.com/$collection/$projectName/_apis/release/releases/$temp/?api-version=6.0"
$patchreq = Invoke-RestMethod -Uri $uriForBuildUpdate -Method Patch -Body $jsonKeepForever -ContentType "application/json" -Headers #{Authorization = ("Basic {0}" -f $base64AuthInfo)}
Write-Verbose "Result: $patchreq" -Verbose
}
}
else
{
}
}
}
It retains the releases, but the requirement is to retain only release definitions created in the last 60 days (or a particular date) and retain only releases happened in last 10 days to prod.
I couldn't find any querystring param to filter it by. How can I do this?
I found that you can get a list of associated environments like prod/stage/dev (for each definition) by adding the $expand=environments to query string.
https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/deployments?$expand=environments&api-version=6.0
So you'll get the list of all environments and their ids for each definition. The ids can be used as definitionEnvironmentId for the other endpoints that seem to have what you're looking for (e.g.: maxCreatedTime or minCreatedTime) like this one for Releases:
https://learn.microsoft.com/en-us/rest/api/azure/devops/release/releases/list?view=azure-devops-rest-6.0#uri-parameters
Reference:
List of properties that can be expanded - https://learn.microsoft.com/en-us/rest/api/azure/devops/release/definitions/list?view=azure-devops-rest-6.0#releasedefinitionexpands

How to import/upload multiple json files to Azure Devops Pipeline Release and Builds?

I have multiple Azure DevOps release and build (.json) files saved on my desktop. The script below is to add one json file. I am trying to import multiple build or release json files from my desktop to Azure DevOps?
Can someone please help?
$token = "PAT token"
$url = "https://dev.azure.com/{organization}/{Project}/_apis/build/definitions?api-version=6.0-preview.2"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$JSON = #'
request body
'#
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Post -ContentType application/json -body $JSON
How to import/upload multiple json files to Azure Devops Pipeline Release and Builds?
We could use powershell scripts to parse the names of these json files from your desktop folder:
$JsonNames = Get-ChildItem C:\Users\<UserName>\Desktop\*.json | Select-Object -ExpandProperty Name
Then we could loop this JsonNames to import to Azure Devops Pipeline Release and Builds:
ForEach ($JN in $JsonNames)
{
$token = "PAT token"
$url = "https://dev.azure.com/{organization}/{Project}/_apis/build/definitions?api-version=6.0-preview.2"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$JSON= Get-Content "C:\Users\<UserName>\Desktop\$($JN).json"
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Post -ContentType application/json -body $JSON
}

Function Level Authorization Authorize keys in Azure can we manage these keys through CICD

Can we managae keys through CICD?
Means i need to manage these through CICD not portal or Rest Srevice is it possible?
everything is being managed through rest api (ultimately) so this ask makes very little sense. you can manage those only using the rest calls (as far as I know).
function Add-AzureFunctionKey {
Param(
[string]$appName,
[string]$resourceGroup,
[string]$funcKeyName,
[string]$funcKeyValue
)
$AzureContext = Get-AzureRmContext
if(!$AzureContext){
Write-Output "Please login to your Azure Account"
Login-AzureRmAccount
}
$SubscriptionId = (Get-AzureRmSubscription | select Name, State, SubscriptionId, TenantId | Out-GridView -Title "Azure Subscription Selector" -PassThru).SubscriptionId
Get-AzureRmSubscription -SubscriptionId $SubscriptionId | Select-AzureRmSubscription
$PublishingProfile = (Get-AzureRmWebAppPublishingProfile -ResourceGroupName $resourceGroup -Name $appName)
$user = (Select-Xml -Xml $PublishingProfile -XPath "//publishData/publishProfile[contains(#profileName,'Web Deploy')]/#userName").Node.Value
$pass = (Select-Xml -Xml $PublishingProfile -XPath "//publishData/publishProfile[contains(#profileName,'Web Deploy')]/#userPWD").Node.Value
$pair = "$($user):$($pass)"
$kuduCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$authToken = Invoke-RestMethod -Uri "https://$appName.scm.azurewebsites.net/api/functions/admin/token" -Headers #{Authorization = ("Basic {0}" -f $kuduCredentials)} -Method GET
$Functions = Invoke-RestMethod -Method GET -Headers #{Authorization = ("Bearer {0}" -f $authToken)} -Uri "https://$appName.azurewebsites.net/admin/functions"
$Functions = $Functions.Name
ForEach ($functionName in $Functions) {
$data = #{
"name" = "$funcKeyName"
"value" = "$funcKeyValue"
}
$json = $data | ConvertTo-Json;
$keys = Invoke-RestMethod -Method PUT -Headers #{Authorization = ("Bearer {0}" -f $authToken)} -ContentType "application/json" -Uri "https://$appName.azurewebsites.net/admin/functions/$functionName/keys/$funcKeyName" -body $json
Write-Output "Function $FunctionName Key updated $keys"
}
}
here's a sample found online, i didnt test it. there are a few examples online more or less like the one above.
Source: https://www.powershellbros.com/add-azure-function-key/

Resources