How can I get last successfully deployed build id of specific artifact in YML based deploy pipeline - azure-devops

I want to get last successfully deployed build id of specific artifact, but I didn't get any solution of it.

How can I get last successfully deployed build id of specific artifact in YML based deploy pipeline
You could use the REST API Releases - Get Release:
GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases/{releaseId}?api-version=6.1-preview.8
My test Inline powershell task scripts:
$url = "GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases/{releaseId}?api-version=6.1-preview.8
"
$ReleasePipeline = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
} -Method Get
$BuildId= $ReleasePipeline.artifacts.definitionReference.version.id
Write-Host This is Build Id: $BuildId
Note: Go to the Agent Phase and select Allow Scripts to Access OAuth Token. See Use the OAuth token to access the REST API

Related

Checking Functions exist on FunctionApp in Azure via DevOps Pipeline

On Azure DevOps I have a build/deploy YAML pipeline which builds my Function App and deploys this to a Linux Function App in Azure (hosted on an app-service plan).
However, recently I noticed an issue where the pipeline was showing the function app was successfully deployed, but when going into the FunctionApp in Azure and clicking on the Functions tab on the left, it shows "No results", but there should be 4 functions in there.
I want to have a step at the end of the deploy pipeline which checks that 4 functions exist in this FunctionApp, and to fail the pipeline run if this is not the case.
I know this will most likely be a task in the pipeline using Azure CLI or Powershell, but not sure how I would go around writing the script. Any help would be immensely appreciated.
Thanks all,
You could use an Azure CLI task and call the Rest API to list the functions withint the FunctionApp. I don't think the native Az CLI and Azure PowerShell functions expose the functions within the FunctionApp/
URI = "https://management.azure.com/subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Web/sites/<functionAppName>/functions?api-version=2015-08-01"
az rest -u $URI --method get | jq '.value[].name'
steps:
- powershell: |
#get token
$TENANTID="xxx"
$APPID="xxx"
$PASSWORD="xxx"
$result=Invoke-RestMethod -Uri https://login.microsoftonline.com/$TENANTID/oauth2/token?api-version=1.0 -Method Post -Body #{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "$APPID"; "client_secret" = "$PASSWORD" }
$token=$result.access_token
##set Header
$Headers=#{
'authorization'="Bearer $token"
'host'="management.azure.com"
}
$functions = Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/<subcription id>/resourceGroups/<resource group name>/providers/Microsoft.Web/sites/<function app name>/functions?api-version=2015-08-01" -Headers $Headers -ContentType "application/json" -Method GET
if($functions.value.Count -eq 4) {
# make pipeline to succeed
Write-Host 'Function deployment success.'
exit 0
}
else {
Write-Host 'Function deployment failed.'
exit 1
}
displayName: 'Check whether the function app deployment completed.'
If you have concerns, let me know.

I want to use a System.AccessToken to a rest api call to deploy one release

In Azure Pipeline Releases, I have one task "Azure PowerShell".
This script will do a deployment of another release. In my code, I use a System.AutenticantionToken: "$AzureDevOpsToken = $env:SYSTEM_ACCESSTOKEN" and my headers for a call rest API is:
$basicAuthValue = "Bearer $AzureDevOpsToken"
$headers = #{
Authorization = $basicAuthValue
}
When I ran this code :
$deploymentBody = #{
status = "inProgress"
} | ConvertTo-Json
$urlDeployment = "https://vsrm.dev.azure.com/$Organization/$ProjectName/_apis/Release/releases/$ReleaseId/environments/$EnvironmentId`?api-version=5.1-preview.6"
$deployment = Invoke-WebRequest -Uri $urlDeployment -Method Patch -ContentType "application/json" -Headers $header -UseBasicParsing -Body $deploymentBody
I received an error:
2022-06-01T14:53:15.4901741Z {"$id":"1","customProperties":{"Descriptor":null,"IdentityDisplayName":null,"Token":null,"RequestedPermissions":0,"NamespaceId":"00000000-0000-0000-0000-000000000000"},"innerException":null,"message":"VS402904: Access denied: User e3b793c5-a512-44b7-a704-878e8adb62e9 does not have manage deployments permission. Contact your release manager.","typeName":"Microsoft.VisualStudio.Services.Security.AccessCheckException, Microsoft.VisualStudio.Services.WebApi","typeKey":"AccessCheckException","errorCode":0,"eventId":3000}
This happened when I use a System.AccessToken.
But when I use a Personal Access Token it goes well. But I don't want to use it because I need to put the password in plain sight in the pipeline. So I want to use a System.AccessToken.
In my pipeline, on the agent pool, I have this check: "Allow scripts to access the OAuth token"
Can you help me?
You do not have to use the password plaintext for the personal access token. You can set a variable lets call it PAT on your pipeline with the value as a secret and then inject this variable on your powershell script.
$connectionToken="$(PAT)"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
Then you have to use as a header
-Headers #{authorization = "Basic $base64AuthInfo"}
VS402904: Access denied: User e3b793c5-a512-44b7-a704-878e8adb62e9 does not have manage deployments permission.
Based on the error message, it means that the service account has no access to manage the deployment.
The variable: $(system.accesstoken) will create a token based on the permissions of the service account: {Project Name} Build Service ({Org Name}).
Refer to this doc: Scoped build identities
To solve this issue, you need to navigate to Piplines -> Release -> Security and grant the Manage Deployments permission to the service account: {Project Name} Build Service ({Org Name}).
For example:

Download latest artifact from Azure Devops using Powershell - get buildId

I try to download the latest Artifact from AzureDevops with PowerShell.
Here is my script to get the latest buildid:
$organisation="aaa"
$project="bbb"
$personalAccessToken="ccc"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($personalAccessToken)"))
$headers = #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$url = "https://dev.azure.com/$organisation/$project/_apis/build/latest/1?branchName=main"
$result = Invoke-RestMethod -Uri $url -Method Get -ContentType application/json -Headers $headers
When I execute this, I get the exception
Build pipeline 1 was not found.
Can someone help me, where I can get the correct definitionId?
Download latest artifact from Azure Devops using Powershell - get buildId
To get the latest artifact from the build, we need to provide the parameter definitions and the $top for the REST API Builds - List:
GET https://dev.azure.com/{organization}/{project}/_apis/build/builds?definitions={definitions}&$top={$top}&branchName={branchName}&api-version=6.0
Note: The branch name parameter should include the refs/heads
As test with postman:
And if you want to know the correct definitionId, you could open the pipeline in the web page, it in the URL:

Retrieving info from Azure Devops with Powershell

I'm trying to automate the deployment of releases in Azure Devops using the Azure Devops API with Powershell. I'm able to retrieve the last release definition, but I'm not able to extract a release for a specific environment.
I'm looking to retrieve the last 'prod' release in order to obtain the 'release ID', and then deploy the release to UAT or DEV using a HTTP 'PATCH' request.
I can hit a URL manually (example below), which gives me the last release for DEV (definitionEnvironmentId=1), and I know I could easily changed the environment ID to '12' for production, but I'd like to get this via an API call.
https://{redacted url}/{redacted}/{redacted}/_apis/release/deployments?api-version=6.0&definitionId=1&definitionEnvironmentId=1&$top=1
Any ideas if this is possible as I can't find any info on it?
You were using the correct Deployments - List Rest api. The reason you didnot get any info from the api call via powershell is because you didnot escape the special character $ for $top parameter in the url.
$ is a special character in powershell. You should escape it by adding a back tick '`' in the url. See below:
#add ` to $top parameter
$url = "https://{redacted url}/_apis/release/deployments?definitionId=3&definitionEnvironmentId=5&`$top=1&api-version=6.0"
$connectionToken="PAT"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$response= Invoke-RestMethod -Uri $url -Headers #{authorization = "Basic $base64AuthInfo"} -Method Get
$releaseId = $response.value[0].release.id

Check previous build information in VSTS (VSTS API)

Are previous build variables accessible during execution of a VSTS build? For example, can I get $(Build.SourceVersion) or $(Build.QueuedBy) of the previous build?
I can get current build information through the build variables like $(Build.SourceVersion) but can I get something like $(Build.Previous.SourceVersion)?
There aren’t the built-in variables for previous build information, the workaround is that you can call Builds REST API (can be filter status, such as completed, inProgress) through PowerShell during this build. (The first item of the result is the newest one)
$base64authinfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $User, $Password)))
$responseFromGet = Invoke-RestMethod -Method Get -ContentType application/json -Uri $Uri -Headers #{Authorization=("Basic {0}" -f $base64authinfo)}
Some articles about calling REST API: Calling VSTS APIs with PowerShell, VSTS/TFS REST API: The basics and working with builds and releases
You can use value of System.AccessToken variable as password (Check Allow scripts to access OAuth token option in Options tab) and username can be anything.
No. "Previous" is a nebulous concept when you're talking about things that can run in parallel. What if you have 3 builds running concurrently?