Skip to content

Instantly share code, notes, and snippets.

@karlospn
Created November 15, 2019 13:51
Show Gist options
  • Save karlospn/9cc83c71d9e257ae56bf5341ea94cff7 to your computer and use it in GitHub Desktop.
Save karlospn/9cc83c71d9e257ae56bf5341ea94cff7 to your computer and use it in GitHub Desktop.
How to assign a project into a sonarqube qualityprofile using the API
param (
[Parameter(Mandatory=$true)][string]$SonarUrl,
[Parameter(Mandatory=$true)][string]$ProjectName,
[Parameter(Mandatory=$true)][string]$ProjectKey,
[Parameter(Mandatory=$true)][string]$QualityProfile,
[Parameter(Mandatory=$true)][string]$SSMName)
function Get-Credentials{
$secret = (ConvertFrom-Json -InputObject (Get-SECSecretValue -SecretId $SSMName).SecretString)
if($null -eq $secret.user -or $null -eq $secret.password )
{
Throw "User or password cannot be retrieved from SSM"
}
$creds = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($secret.user + ':' + $secret.password))
return $creds
}
function Search-Project($creds) {
$result = Invoke-WebRequest -Method POST -uri "$SonarUrl/api/projects/search?projects=$ProjectKey" -TimeoutSec 20 -Headers @{ 'Authorization' = 'Basic ' + $creds } |
Select-Object -Expand Content |
ConvertFrom-Json
return $result
}
function New-Project($creds) {
$result = Invoke-WebRequest -Method POST -uri "$SonarUrl/api/projects/create?name=$ProjectName&project=$ProjectKey" -TimeoutSec 20 -Headers @{ 'Authorization' = 'Basic ' + $creds }
if($result.StatusCode -ne 200)
{
Throw "Error trying to create the project in Sonarqube"
}
}
function Add-QualityProfile($creds){
$uri = "$SonarUrl/api/qualityprofiles/add_project?project=$ProjectKey&language=cs&qualityProfile=$QualityProfile"
$result = Invoke-WebRequest -Method POST -uri $uri -TimeoutSec 20 -Headers @{ 'Authorization' = 'Basic ' + $creds }
if($result.StatusCode -ne 204)
{
Throw "Error trying to add the project into the quality profile"
}
}
function main()
{
try {
$creds = Get-Credentials
$project = Search-Project $creds
if($project.components.length -eq 0)
{
New-Project $creds
}
Add-QualityProfile $creds
}
catch {
Write-Error $_.Exception
}
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment