Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins: Add project default build authorization programmatically

Tags:

jenkins

groovy

I using DSLs to create my different jobs. However, when I start up my Jenkins container, I get this error of:

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

To fix this error, I need to select "Run as User who triggered Build under" project default build authorization, like so:

enter image description here My question is how do I do that in a groovy script or in a programmatic way so my container can fully initialize Jenkins.

Any help would be greatly appreciated.

like image 321
Gerb Avatar asked Mar 08 '23 19:03

Gerb


1 Answers

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()
      }   
    }   
  }

  ...
}
like image 189
fishi0x01 Avatar answered Mar 14 '23 08:03

fishi0x01