Skip to content

Instantly share code, notes, and snippets.

@corux
Created July 29, 2016 18:07
Show Gist options
  • Save corux/353b3c9c6ca33d1383a402f418c3b1f9 to your computer and use it in GitHub Desktop.
Save corux/353b3c9c6ca33d1383a402f418c3b1f9 to your computer and use it in GitHub Desktop.
Script to automate the deletion of old projects from SonarQube.
#!/usr/bin/env python
import argparse,collections,json,shlex,urllib,re
from datetime import datetime
from datetime import timedelta
from dateutil.parser import parse
from termcolor import colored
# Command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--dry-run", dest="dryrun", action="store_const", const=True, default=False, help="Do not delete SonarQube projects.")
parser.add_argument("--url", dest="url", required=True, help="URL to the SonarQube server. Use http://user:password@host/ to include authentication.")
parser.add_argument("--days", dest="days", type=int, required=True, help="Number of days since the last analysis to keep the project.")
parser.add_argument("--keep", dest="keep", action="append", nargs="?", help="Regex to filter out projects, which should not be deleted.")
args = parser.parse_args()
# retrieve all SonarQube projects
def get_data():
data = urllib.urlopen(args.url + "/api/resources/index").read()
output = json.loads(data)
return output
def is_excluded(project):
if args.keep:
for pattern in args.keep:
if re.match(pattern, project['name']):
return True
cutoff_date = (datetime.now() - timedelta(days=args.days)).date()
project_date = parse(project['date']).date()
if project_date >= cutoff_date:
return True
return False
def remove_project(project):
params = urllib.urlencode({'id': project['id']})
status = urllib.urlopen(args.url + "/api/projects/destroy", params).read()
# main logic
data = get_data()
for project in data:
if not is_excluded(project):
print colored("removing {}".format(project['name']), 'green')
if not args.dryrun:
remove_project(project)
else:
print colored("exluded {}".format(project['name']), 'yellow')
@prudhvigodithi
Copy link

Hey this script looks good but looks like this is for older version of sonar, currently the api's have changed and they have removed the /api/resources/index api and have added /api/projects/search, can we get the same code working with this change for deleting of old projects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment