Jenkins:以编程方式添加项目默认构建授权

时间:2017-10-17 17:46:47

标签: jenkins groovy

我使用DSL创建不同的工作。但是,当我启动我的Jenkins容器时,我收到以下错误:

Processing DSL script neojob.groovy
ERROR: script not yet approved for use
Finished: FAILURE

要修复此错误,我需要选择"以用户身份运行,触发"项目默认构建授权,如下所示:

enter image description here 我的问题是我如何在一个groovy脚本或程序化的方式中这样做,以便我的容器可以完全初始化Jenkins。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

For me the following groovy code is working to programmatically configure the Authorize Project Plugin in Jenkins' Global Security section. I place the script in Jenkins' init.groovy.d/ directory to trigger it on every start.

import jenkins.*
import jenkins.model.*
import hudson.model.*
import jenkins.model.Jenkins
import org.jenkinsci.plugins.authorizeproject.*
import org.jenkinsci.plugins.authorizeproject.strategy.*
import jenkins.security.QueueItemAuthenticatorConfiguration

def instance = Jenkins.getInstance()

// Define which strategies you want to allow to be set per project
def strategyMap = [
  (instance.getDescriptor(AnonymousAuthorizationStrategy.class).getId()): true, 
  (instance.getDescriptor(TriggeringUsersAuthorizationStrategy.class).getId()): true,
  (instance.getDescriptor(SpecificUsersAuthorizationStrategy.class).getId()): true,
  (instance.getDescriptor(SystemAuthorizationStrategy.class).getId()): false
]

def authenticators = QueueItemAuthenticatorConfiguration.get().getAuthenticators()
def configureProjectAuthenticator = true
for(authenticator in authenticators) {
  if(authenticator instanceof ProjectQueueItemAuthenticator) {
    // only add if it does not already exist
    configureProjectAuthenticator = false
  }
}

if(configureProjectAuthenticator) {
  authenticators.add(new ProjectQueueItemAuthenticator(strategyMap))
}

instance.save()

Their plugin's javadoc helps to know about the classes. Further, I had a look at their tests on github, to figure out how to configure those objects in Jenkins.

From now on I can set a job's authorization rule via the JobDSL Plugin like this:

job("SEED/SeedMainJobs") {
  properties {
    authorizeProjectProperty {
      strategy {
        triggeringUsersAuthorizationStrategy()
      }   
    }   
  }

  ...
}