How to add branch policies using powershell Invoke RestMethod - powershell

We have PowerShell script that will automate creating branch.
Now we are trying to automate branch policies using api using PowerShell Invoke-RestMethod.
We have option to manually add policies using cross repository policies, but we have build validation enabled for repositories which is different for each repo.
I'm able to get the policy configurations using GET https://dev.azure.com/$organization/$project/_apis/policy/configurations/repo=$repoName&api-version=6.0
But don't know how to get the get the particular value and add policies.

You can use the Configurations - Create Rest API:
POST https://dev.azure.com/{organization}/{project}/_apis/policy/configurations/{configurationId}?api-version=6.1-preview.1
In the body you specify the branch policy you want to add, for example - build policy:
{
"isEnabled": true,
"isBlocking": false,
"type": {
"id": "0609b952-1397-4640-95ec-e00a01b2c241"
},
"settings": {
"buildDefinitionId": 5,
"scope": [
{
"repositoryId": null,
"refName": "refs/heads/feature",
"matchKind": "prefix"
}
]
}
}
In the above body you add branch (build) policy to branch feature that requires build 5 to pass.
You cans see all the available policy types in the Types - List api.

To add the Build validation in Branch Policy, you could refer to the following PowerShell Sample:
$token = "PAT"
$url="https://dev.azure.com/{OrganizationName}/{ProjectName}/_apis/policy/configurations?api-version=6.1-preview.1"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$JSON = #'
{
"type":{
"id":"0609b952-1397-4640-95ec-e00a01b2c241"
},
"revision":1,
"isDeleted":false,
"isBlocking":true,
"isEnabled":true,
"settings":{
"buildDefinitionId":592,
"displayName":null,
"manualQueueOnly":false,
"queueOnSourceUpdateOnly":true,
"validDuration":720,
"scope":[
{
"repositoryId":"RepoID",
"refName":"refs/heads/BranchName",
"matchKind":"Exact"
}
]
}
}
'#
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method POST -Body $JSON -ContentType application/json
You could refer to this doc about Configurations - Create and Repositories - List
Result:

Related

Pass Azure Automation Runbook Webhook Body to Logic Apps

I have created a webhook in Azure Automation. I am looking to pass the body when the webhook is called to a logic app. Please see the powershell code designed of runbook.
param
(
[Parameter(Mandatory=$false)]
[object] $WebhookData
#[string] $jobId
)
if ($WebhookData.RequestBody) {
$names = (ConvertFrom-Json -InputObject $WebhookData.RequestBody)
Write-Output $names
$webhookName = $WebhookData.WebhookName
$logicappURI = "https://logicapp/api/test/triggers/manual/invoke/properties/"+$webhookName+"?api-version=2022-05-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig={signature_certificate"
$response = Invoke-WebRequest -Method GET -Uri $logicappURI
}
else {
Write-Output "Hello World!"
}
Currently I am able to call the logic app and pass the webhook name, but the i would like to pass the complete request body. Below is the request body for webhook.
{
"WebhookName": "wh-test-webhook-ext-cus-001",
"RequestBody": "[{\"Name\": \"Hawaii\" },{\"Name\": \"Seattle\"},{ \"Name\": \"Florida\"}]",
"RequestHeader": {
"Connection": "Keep-Alive",
"Host": "14304127-e302-4499-b819-8ac4493555e9.webhook.cus.azure-automation.net",
"User-Agent": "Mozilla/5.0",
"x-ms-request-id": "47ca3f1a-2418-4553-94c4-9f20c2095c80"
}
}
The logic app is designed to trigger when an HTTP request is recieved. As shown in the image I am passing passing webhook name. Similarly is there a way I can pass the complete ReuqestBody.
Thanks in advance.
Logic App Design

Azure DevOps REST API Broken Importing Private Git Repository

Trying to import a private GitHub repository into Azure DevOps using the REST API:
https://learn.microsoft.com/en-us/rest/api/azure/devops/git/import%20requests/create?view=azure-devops-rest-6.0
Unsurprisingly, the documentation doesn't work.
I have a PAT based service endpoint in the DevOps project that has access to the GitHub repository I'm trying to import.
I have the following PowerShell snippet that reproduces the problem
$headers = #{
Authorization = "Bearer ****"
}
$org = '***'
$project = '***'
$targetRepositoryId = '***'
$sourceRepositoryUrl = '***'
$gitHubServiceEndpointId = '***'
irm https://dev.azure.com/$org/$project/_apis/git/repositories/$targetRepositoryId/importRequests?api-version=6.0-preview.1 -Method Post -Headers $headers -ContentType application/json -Body #"
{
"parameters": {
"gitSource": {
"overwrite": false,
"url": "$sourceRepositoryUrl"
},
"serviceEndpointId": "$gitHubServiceEndpointId",
"deleteServiceEndpointAfterImportIsDone": false
}
}
"#
Throws a 400 error (Bad Request) with no additional information.
If I make the GitHub repository public, the exact same API request and the exact same code above works fine.
I am also 100% certain that the service endpoint has access to the repository in question because I have pipelines in Azure DevOps that use this service endpoint to clone said repository from GitHub.
I was able to get the import to work using a GitHub service connection ONLY if you create the service connection using UsernamePassword authorization scheme -- which you can't do from DevOps itself you have to do from the API:
irm "https://dev.azure.com/org/project/_apis/serviceendpoint/endpoints?api-version=6.0-preview.1" -Method Post -Headers $headers -ContentType application/json -Body #"
{
"authorization": {
"scheme": "UsernamePassword",
"parameters": {
"username": "foo",
"password": "github access token"
}
},
"name": "Test-5",
"serviceEndpointProjectReferences": [
{
"description": "",
"name": "Test-5",
"projectReference": {
"id": "project id",
"name": "projectName"
}
}
],
"type": "github",
"url": "https://github.com",
"isShared": false,
"owner": "library"
}
"#
According to captured network log, the service connection type needs to be "Other Git" when create the service connection, then input Git repository URL and Personal access tokens created in GitHub:
With this service connection ID, it's supposed to be able to get a successful import.

Unable to link a work item to the test results based on the document

When I was following this document Publish Test Results task
I didn't find any field to link a work item to a test case. Do I need to call an api to do this? Or is there any field that isn't in the document?
Thanks!
We could add the work item in the test run result summary page.
In the build summary page->click the tab test->select the test result, we could see the run id and resultId in the URL
Open Test Plans->click the tab Runs->select the test run and open it->click the tab Test results and open it->we could see the button Bug->click it, then we could select create new bug or add existing bug. You could check the pic below.
Update1
We could do this via REST API to add work item.
Sample:
PATCH https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/results?api-version=6.0
Request Body:
[
{
"id": {Result ID},
"state": "Completed",
"comment": "{Comment}",
"associatedBugs": [
{
"id": {Bug ID}
}
]
}
]
Then we could check it in the UI or this REST API
Sample:
GET https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/results/{testCaseResultId}?detailsToInclude=workItems&api-version=6.0-preview
Note: We could get test run ID in the task publish test result log. We could add power shell task and enter the script to add the work item in the pipeline.
Power shell script sample:
$connectionToken="{PAT}"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$Url = "https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/results?api-version=6.0"
$Body = #"
[
{
"id": {Result ID},
"state": "Completed",
"comment": "{Comment}",
"associatedBugs": [
{
"id": {Bug ID}
}
]
}
]
"#
$Result = Invoke-RestMethod -Uri $Url -ContentType "application/json-patch+json" -Body $Body -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method PATCH

How to create work item on failure in azure Release pipeline not Build pipeline

I'm not seeing Create work item on failure option on the Options tab. I'm using this as a reference https://developercommunity.visualstudio.com/content/problem/343557/create-work-item-on-build-failure-lost-work-item-t.html.
Actually I have to create a bug work item when there is a failure in my pipeline in azure devops. I saw couple of post few of them saying use API or few say there is an option in Azure itself but I'm not able to see please have a look in attached image.
Any help will appreciate.
In Azure Devops, the option Create work item on failure indeed exists, but it only exists in build pipeline for the time being.
From your screenshot, you are using the Releases Pipeline. So you couldn't find it.
In Release Pipeline, you need to use API to create a work item.
Here is an example:
You could Use Powershell Task to run Rest API to create a work.
Set the condition
Or you could directly use this Extension- Create Bug on Release failure.
Powershell script update:
$witType="task"
$token = "PAT Token"
$url="$(SYSTEM.TEAMFOUNDATIONCOLLECTIONURI)/$(SYSTEM.TEAMPROJECT)/_apis/wit/workitems/`$$($witType)?api-version=6.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$body="[
{
`"op`": `"add`",
`"path`": `"/fields/System.Title`",
`"value`": `"titlename`"
},
{
`"op`": `"add`",
`"path`": `"/fields/System.AssignedTo`",
`"value`": `"e-mail address`"
},
{
`"op`": `"add`",
`"path`": `"/fields/Microsoft.VSTS.Common.Priority`",
`"value`": `"4`"
},
{
`"op`": `"add`",
`"path`": `"/fields/System.Tags`",
`"value`": `"Tag1; Tag2`"
},
{
`"op`": `"add`",
`"path`": `"/fields/System.History`",
`"value`": `"<div>$(SYSTEM.STAGEDISPLAYNAME)</div>`"
}
]"
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Post -Body $body -ContentType application/json-patch+json
Explanation:
This API could add Priority, tag, assign to and set the stage name as the discussion.
Since this task is created when it fails, it can directly output the stage name variable to the discussion.
Result:
Note: You could refer to this doc to create a PAT (personal access tokens).

Skip stages is not working using azure devops rest api

I have a very basic pipeline with 4 stages, for prod stage i want to run from separate pipeline . I was trying to use build queue rest api as per documentation and using below payload
{
"stagesToSkip": [
"Build"
],
"definition":
{
"id": "24"
},
"resources": {
"repositories": {
"self": {
"refName": "refs/heads/master"
}
}
},
"variables": {}
}
I got this payload when i manually run the build by selecting only one stage and run it works as expected as highlighted but whn i use the rest api with the same request payload , it runs both the stages.
any pointers what i'm doing wrong??
You can use Run Pipeline rest api to skip stages.
POST https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipelineId}/runs?api-version=6.0-preview.1
See below example in powershell script:
$url="https://dev.azure.com/{org}/{proj}/_apis/pipelines/{pipelineId}/runs?api-version=6.0-preview.1"
$PAT='personal access token'
$body='{
"stagesToSkip":[ "Test" ]
}'
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$result1 = Invoke-RestMethod -Uri $url -Headers #{authorization = "Basic $base64AuthInfo"} -Method post -Body $body -ContentType "application/json"
See below test result. The stage was successfully skipped.