'How do I get a users roles from inside a Jenkins pipeline?

I'm using Jenkins Enterprise.

When I login I can go here: https://myserver/cjoc/roles/whoAmI

I see the following info:

User: [email protected]
Groups: "Administrators" administer
External groups: "authenticated", "groupone", "grouptwo"

How do I see this from inside a running pipeline?

I can get the Jenkins user like this, but how do I get the user's external groups?

def currentBuild = currentBuild.rawBuild
def cause = currentBuild.getCause(hudson.model.Cause.UserIdCause.class)
def theJenkinsUser = cause?.getUserName()


Solution 1:[1]

    def user_id = cause.getUserId()

    def user_groups = User.getById(user_id, false).getAuthorities()
    if ('groupone' in user_groups || 'grouptwo' in user_groups) {
        println "This user is allowed"
    } else {
        currentBuild.result = "ABORTED"
        error("User not allowed")
    }

Solution 2:[2]

slight update , incase you don't get current user by the first command in MaratC's script you can use following which helped me. ALso not sure why false is required there but it fails without true or false value.

 def userid=currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MaratC
Solution 2 10raw