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.
Related
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:
I'm learning both Grafana, AND how to interact with APIs in Powershell. I was able to use the Grafana HTTP API to create a dashboard, however I cannot get the same API to create a Datasource. My code is as follows:
$header = #{"Authorization" = "Bearer apikey="}
$createDatasourceUri = "http://localhost:3000/api/datasources"
$createDatasourcejson = #'
{
"datasource": {
"name": "prometheusApiTest",
"type": "prometheus",
"url": "http://localhost:9090",
"access": "proxy",
"basicAuth": false,
"isDefault": true
}
}
'#
$datasourceParameters = #{
Method = "POST"
URI = $createDatasourceUri
Body = $createDatasourcejson
Headers = $header
ContentType = "application/json"
}
Invoke-RestMethod #datasourceParameters
I am presented with the following error:
Invoke-RestMethod : [{"fieldNames":["Name"],"classification":"RequiredError","message":"Required"},{"fieldNames":["Type"],"classification":"RequiredError","message":"Required"},{"fieldNames":["Access"],"classificat
ion":"RequiredError","message":"Required"}]
I do not know what's going on. Anything I can find about this error says I need to specify the ContentType as "application/json", but I've very clearly done so. I do receive data when I do a "GET" on that API endpoint, and even copying the data that gets returned still results in the above error. I'm at a complete loss, as this same code worked to create a dashboard (albeit with the right json payload for a dashboard). Any ideas?
The Grafana docs for the Datasource API only has the datasource element in the response, not the initial call. Line 5 of my code, and the subsequent {} for that element, are not needed, and the script functions with those lines removed.
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 can we create a Azure Pipeline(yaml approach) using Azure Devops rest apis.
Basically I am trying to create a new pipeline programmatically and not through Azure Devops portal
I referred to this link below:
https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/pipelines/create?view=azure-devops-rest-6.0
but this does not provide the exact json body format required to create and configure a new pipline pointing to code repo. Kindly help me here
You can first use the Pipelines - Get rest api to check the definition json of the pipeline, and change the fields accordingly.
You can define the request body json as below, when calling Pipelines - Create rest api:
$body = #{
configuration=#{
variables=#{
customVariable=#{
value="value"
}
};
path="azure-pipelines.yml";
repository=#{
id= "repository-id";
name="repository-name"
type= "azureReposGit"
};
type= "yaml"
};
name= "pipeline-name";
folder= "\\"
}
The variables field define the pipeline Variables in the UI Page:
The path field points to pipeline yaml file in the code repo.
The repository field defines the code repo this pipeline targets to.
The folder field defines which folder the pipeline is placed:
If you use Build Definitions - Create rest api to create the yaml pipeline. You can check below request body json example:
$body='{ "variables": {
"customVariable": {
"value": "customValue",
"allowOverride": true
}
},
"process": {
"yamlFilename": "azure-pipelines.yml",
"type": 2
},
"repository": {
"id": "repo-id",
"type": "TfsGit",
"name": "repo-Nanme",
"defaultBranch": "refs/heads/master",
"clean": null,
"checkoutSubmodules": false
},
"name": "pipeline-name",
"path": "\\",
"type": "build",
"queueStatus": "enabled",
"project": {
"id": "project-id",
"name": "project-name"
}
}'
Update:
If you code repo is Githbub. You will have to create a github service connection in your azure devops project. And then pass the connection id in your api resquest body.
$body = #{
configuration=#{
variables=#{
customVariable=#{
value="value"
}
};
path="azure-pipelines.yml";
repository=#{
FullName="githubAccount/repoName";
type= "gitHub";
Connection= #{
id= "github service connection id"
}
};
type= "yaml"
};
name= "pipeline-name";
folder= "\\"
}
You can get the service connection id in the address bar. See below:
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.