How to configure Jenking without GUI

It is possible to create the jobs in jenkins using Groovy.
You can create a Groovy script file $JENKINS_HOME/init.groovy, or any .groovy file in the directory $JENKINS_HOME/init.groovy.d/, to run some additional things right after Jenkins starts up.

In Ubuntu $JENKINS_HOME is by default configured in /var/lib/jenkins/

Authentication

We can for example disable security creating a new file called for example /var/lib/jenkins/init.groovy.d/basic-security.groovy:

#!groovy
import jenkins.model.*
import hudson.security.*
import hudson.util.*;
import jenkins.install.*;

def instance = Jenkins.getInstance()

println "--> creating local user 'admin'"
instance.setInstallState(InstallState.INITIAL_SETUP_COMPLETED)

def strategy = new AuthorizationStrategy.Unsecured()
instance.setAuthorizationStrategy(strategy)
instance.save()

It can also be necessary to avoid run the setupWizard which can be done passing jenkins.install.runSetupWizard=false as JAVA arguments:

echo "JAVA_ARGS=\"-Djenkins.install.runSetupWizard=false\"" >> /etc/default/jenkins

creatingJobs

You can automatically new jobs can be created via scripts on startup. For example we can create the file /var/lib/jenkins/init.groovy.d/initial-jobs.groovy:

#!groovy

import jenkins.model.Jenkins;
import hudson.model.FreeStyleProject;
import hudson.tasks.Shell;

class myScriptClass{
 static void createJob(folderName, scriptName){   
   def folder = Jenkins.instance.getItem(folderName)
   if (folder == null){
      print("Creating Job "+folderName)
      def job = Jenkins.instance.createProject(FreeStyleProject, folderName)
      job.buildersList.add(new Shell(scriptName))
      job.save()
   }
 }
}
myScriptClass.createJob('Create Database','/opt/myapp/createdb.sh')
myScriptClass.createJob('Lauch tests','mvn test')

The Job can be configured with the tasks defined in hudson.tasks package which are added to the buildersList.

If you want to add those scripts to the sudoers list:

echo "jenkins ALL = NOPASSWD: /opt/myapp/createdb.sh" >> /etc/sudoers

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s