Job based security per branch - Jenkins Multibranc

2019-07-01 10:51发布

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条回答
forever°为你锁心
2楼-- · 2019-07-01 10:58

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:

查看更多
登录 后发表回答