Dubl1n Dubl1n - 1 month ago 15
Groovy Question

Jenkins - choice parameter - mysql database query return list

A new user to Jenkins. I am attempting to replace an old build system that used a website in which part of it has a drop down menus that gives a list of old builds using a SELECT query in mysql. This allows the user to deploy or delete the build as needed.

The goal is to setup a choice parameter in Jenkins (there are many difference choice plugins -Dynamice, Active, Extended, etc., I am not sure which one to use) so that the user can select the build from a list.

Working with the Scriptler plugin, I am able to run the following code (edited) and it returns a list of the builds, which is what I want:

import groovy.sql.Sql
def sql = Sql.newInstance('jdbc:mysql://localhost:3306/test', 'root', '', 'com.mysql.jdbc.Driver')
String sqlString = "SELECT BVersion FROM BuildTable WHERE Branch = '${BUILD_NAME} ORDER BY BuildDate DESC Limit 10;"
sql.eachRow(sqlString){ row ->
println row[0]
}


I want to do variable replacement as well, so that the user choose a ${BUILD_NAME} in the choice above and this will dynamically return the build list based on that choice.

However when I add the code either as scriptler code or groovy script, I find that neither works and I get a blank field. What am I missing to get this to return a choice, single choice per line??

Thanks for any assistance you may offer.
D

Answer

Instead of printing out the results, you need to put them into an array.

code re-write:

import groovy.sql.Sql

def output = []

def sql = Sql.newInstance('jdbc:mysql://localhost:3306/test', 'root', '', 'com.mysql.jdbc.Driver')
String sqlString = "SELECT BVersion FROM BuildTable WHERE Branch = '${BUILD_NAME} ORDER BY BuildDate DESC Limit 10;"
sql.eachRow(sqlString){ row ->  
    output.push(row[0])
}

return output

If you want to order your output, just do:

return output.sort()

Cheers.