Make Active Choice Dependent on Jenkins User with Groovy

This code example shows how to change the contents of an Active Choices parameter depending on the user who is running the build job.

Get the user ID from the currentBuild class:

def userId = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')[0].userId

The Active Choices parameter returns a list from inside the script object. In order to capture the userId, I use the sprintf function to generate the script code, so I can use the userId variable.
To make this more interesting, I check whether the user is in a particular list. So if the userID is in the list of fruit_fans, the list of fruits is returned, else the list of vegetables is returned.

fruit_fans = '["ann","bob","zoe"]'
def code = sprintf("""
if ( "%s" in %s) {
    choices = ["Apple","Banana","Cherry"]
} else {
    choices = ["Amaranth","Beet","Cabbage"]
}

return choices
""",userId,fruit_fans)

The stage step simply prints out the username and the food selection made.

Complete Code (copy & paste into the Pipeline Script section of your project):

def userId = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')[0].userId
fruit_fans = '["ann","bob","zoe"]'
def code = sprintf("""
if ( "%s" in %s) {
    choices = ["Apple","Banana","Cherry"]
} else {
    choices = ["Amaranth","Beet","Cabbage"]
}

return choices
""",userId,fruit_fans)

properties([
    parameters([
        [
            $class: 'ChoiceParameter',
            choiceType: 'PT_MULTI_SELECT',
            description: 'Active Choices Reactive parameter',
            filterLength: 1,
            filterable: false,
            name: 'food',
            referencedParameters: 'role',
            script: [
                $class: 'GroovyScript',
                fallbackScript: [
                    classpath: [],
                    sandbox: false,
                    script: 'return ["error"]'
                ],
                script: [classpath: [],
                    sandbox: false,
                    script: code
                ]
            ]

        ]
    ])
])
node {
    stage("Show Selection"){
        echo "$userId selected $food" 
    }
}

Have fun, and thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *