I'm attempting to set tags via the SonarQube REST API, however, the REST API doesn't come with a lot of examples for different scenarios.
In my case I'm attempting to set the tags for a given projectKey with an API Key. I want to use Invoke-RestMethod instead of Curl, since I'll be running the script in powershell.
Solution - tested on SonarQube 9.2.4 The biggest hassle is to figure out how the authentication works. This script is inteded to be used in f.ex. a build agent. The API for SonarQube is weird and not necessarily easy to use.
$sonarQubeUrl = "https://YOURSONARQUBEINSTANCE"
$apiUrl = "/api/project_tags/set"
$projectKey = "YourProjectKey"
$tagsUrl="&tags="
$tags="your,own,tags"
$sonarKey = "YOURAPIKEY" + ":"
function SetTagsForProjectKey(){
$EncodedText =[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($sonarKey))
$Headers = @{
"Authorization" = "Basic $EncodedText"
"Accept" = "application/json"
}
$Body= @{
grant_type = "client_credentials"
project = $projectKey
tags = $tags
}
$url = $sonarQubeUrl + $apiUrl
write-host "Url is set to $url"
try {
Invoke-RestMethod –Method POST –Uri $url –Headers $Headers –ContentType "application/x-www-form-urlencoded" –Body $Body
}
catch {
write-host "Error when uploading new data for $name : $_ "
}
}