How to get projects where a sonar group is being used for permissions

Welcome :slight_smile:

here’s a solution using Groovy and Sonarqube web api.
Use GroovyConsole and edit <yoursonarhost>, <yourapitoken> and the <groupToSearchFor>
for your needs.
(I’m using the rather old Groovy 2.5.7 as Jenkins still ships with 2.4.21)

uses web api
/api/projects/search
/api/permissions/groups

import groovy.json.*

// method GET or POST
def sqRest(url,method, apitoken) {
  jsonSlurper = new JsonSlurper()
  bauth = 'Basic ' + (apitoken + ':').bytes.encodeBase64().toString()
  conn = url.toURL().openConnection()
  conn.setRequestMethod(method)
  conn.setRequestProperty("Authorization", bauth)
  if(method == 'GET') {
    object = jsonSlurper.parseText(conn.content.text)
  }
}

def map = [:].withDefault { [] }

getproj = sqRest('https://<yoursonarhost>/api/projects/search?ps=500', 'GET', '<yourapitoken>')
  println 'project count => ' + getproj.paging.total
  foo = getproj.paging.total.toFloat()/500
  counter = 1
  while(counter <= foo.round()) {
    sqRest("https://<yoursonarhost>/api/projects/search?ps=500&p=$counter", 'GET', '<yourapitoken>').components.key.each { it ->
      sqRest(" https://<yoursonarhost>/api/permissions/groups?projectKey=$it&permission=codeviewer", 'GET', '<yourapitoken>').groups.name.each { iit ->    
           map["$it"] << iit
        }
      }
    counter++  
  }
 
def projectKeys = map.findAll { entry -> entry.value.contains('<groupToSearchFor>') }.keySet().toList()
/*
 the list has all projects where <groupToSearchFor> has codeviewer permission
 in case of searching for other permissions you need to edit
 /api/permissions/groups?projectKey=$it&permission=<xxx>
 see api docs https://<yoursonarhost>/web_api/api/permissions?internal=true
*/
println projectKeys

The web api is pageinated with a max. pagesize of 500. In case of more than 500 projects
you need to compute the total and loop over as shown above.

Gilbert

2 Likes