Job based security per branch - Jenkins Multibranch pipeline

依然范特西╮ 提交于 2019-12-10 18:44:21

问题


I have a Jenkins multi-branch pipeline for building artifacts and there are branches for master, *-dev etc.

I want to enable project based security on a per branch basis, ie only allow devs to run the *-dev branch jobs of the build not any other ones because doing so would have undesirable effects.

I know there is project based security, but I didn't see any per branch. Does this exist? We are behind in updating Jenkins and are currently running Jenkins 2.46.1.

Otherwise I am thinking I might have to have a separate upstream job to call the correct branch of the downstream one and make the downstream artifact job unable to be run by devs with the privilege to do so. (This sounds like overkill).

Or is there any way to accomplish this in the branch's Jenkinsfile?


回答1:


Here's some Jenkinsfile groovy that will get you close to what you want:

// return the user id that caused this build; else empty string
@NonCPS
def user_id_cause() {
    def CAUSE = currentBuild.rawBuild.getCause(
        hudson.model.Cause.UserIdCause.class
    );
    return CAUSE ? CAUSE.getUserId() : "";
}

// return all groups to which the given user id belongs
@NonCPS
def groups(USER_ID) {
    return Jenkins.instance.securityRealm.loadUserByUsername(USER_ID).authorities.collect{ it.toString() };
}

...

env.USER_ID_CAUSE = user_id_cause();
if (!env.BRANCH_NAME.endsWith('-dev')) {
    if (env.USER_ID_CAUSE) {
        if ('jenkins_admins' in groups(env.USER_ID_CAUSE)) {
            echo("INFO: user id `${env.USER_ID_CAUSE}` is in the group `jenkins_admins`.");
        } else {
            currentBuild.result = 'ABORTED';
            error("user id `${env.USER_ID_CAUSE}` is not in the group `jenkins_admins`.");
        }
    }
}

Caveats:

  • These tricks rely heavily on API functions that require "In-process Script Approval" by a Jenkins administrator.
  • The above example assumes the existence of the jenkins_admins group to which privileged users belong --- your user/groups situation may be very different.
  • In general, playing with objects returned from Jenkins API functions should be done within @NonCPS-annotated functions --- you risk java.io.NotSerializableException otherwise.

References:

  • https://github.com/jenkinsci/workflow-cps-plugin/blob/master/README.md
  • http://javadoc.jenkins-ci.org/hudson/model/Cause.UserCause.html
  • http://javadoc.jenkins-ci.org/hudson/model/Run.html#getCause-java.lang.Class-
  • http://javadoc.jenkins.io/hudson/security/SecurityRealm.html#loadUserByUsername-java.lang.String-


来源:https://stackoverflow.com/questions/46894075/job-based-security-per-branch-jenkins-multibranch-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!