Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Enables/Revokes administrative mode for users in Jenkins using Role-Strategy and Build User plugins.
import com.michelin.cio.hudson.plugins.rolestrategy.Role;
import com.michelin.cio.hudson.plugins.rolestrategy.RoleMap;
import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy;
import jenkins.model.Jenkins;
import hudson.model.Result;
import hudson.EnvVars;
final String ROLE_PREFIX="sudo_";
EnvVars vars = build.getEnvironment(listener);
final String userName=vars .get("BUILD_USER_ID");
final boolean confirmed = Boolean.parseBoolean(vars.get("I_AM_SURE"));
final String mode=vars .get("ACTION");
def errorExit(msg) {
println "ERROR: "+msg;
return false;
}
// Check confirmation
if (!confirmed) {
println "User has not confirmed the change. The job will be aborted";
build.setResult(Result.NOT_BUILT);
return false;
}
// This stuff will work only for RoleBasedAuthorizationStrategy. TODO: add checks
RoleBasedAuthorizationStrategy strategy = (RoleBasedAuthorizationStrategy)Jenkins.getInstance().getAuthorizationStrategy();
RoleMap roles = strategy.getRoleMap(RoleBasedAuthorizationStrategy.GLOBAL);
// Extract role
final String roleName = ROLE_PREFIX+userName;
println "Request: " + mode+" sudo access rights (user="+userName+").";
println "Target role to be modified is "+roleName;
Role targetRole = roles.getRole(roleName);
if (targetRole == null) {
errorExit("User "+userName+" has not sudo access rights");
}
// Assign user to his sudo permissions
boolean sudoIsActive = roles.grantedRoles.get(targetRole).contains(userName);
switch (mode) {
case "GRANT":
if (sudoIsActive) {
println "Nothing to do. Sudo is active";
} else {
println "Assigning "+roleName+" to "+userName;
roles.grantedRoles.get(targetRole).add(userName);
}
break;
case "REVOKE":
if (sudoIsActive) {
println "Clearing assigments of "+roleName;
roles.grantedRoles.get(targetRole).remove(userName);
} else {
println "Nothing to do. Sudo is disabled";
}
break;
default:
errorExit("Mode "+mode+" is not supported");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.