检查用户是否已经在詹金斯中创建

时间:2019-02-14 16:42:17

标签: docker jenkins groovy

如何检查Groovy上的Jenkins是否已创建用户?

我正在使用此脚本来自动创建管理用户https://github.com/foxylion/docker-jenkins/blob/master/docker-images/master/default-user.groovy,但是不幸的是,每次docker容器(及其重启)时,它都会启动。因此,我在Jenkins GUI中失去了其他手动创建的用户。

1 个答案:

答案 0 :(得分:1)

看起来getSecurityRealm()将返回一个包含HudsonPrivateSecurityRealm的impl ...这样看起来就可以工作:

import jenkins.model.*
import hudson.security.*
import org.acegisecurity.userdetails.UsernameNotFoundException
import org.springframework.dao.DataAccessException

def env = System.getenv()

def jenkins = Jenkins.getInstance()
jenkins.setSecurityRealm(new HudsonPrivateSecurityRealm(false))
jenkins.setAuthorizationStrategy(new GlobalMatrixAuthorizationStrategy())

def user = null;
try {

  jenkins.getSecurityRealm().loadUserByUsername(env.JENKINS_USER);

} catch (UsernameNotFoundExceoption n) {
  user = jenkins.getSecurityRealm().createAccount(env.JENKINS_USER, env.JENKINS_PASS)
  user.save()

  jenkins.getAuthorizationStrategy().add(Jenkins.ADMINISTER, env.JENKINS_USER)
  jenkins.save()
} catch (org.springframework.dao.DataAccessException d) {
   /// log
}