Index

Jenkins configuration as code

environment variables

ENV CASC_JENKINS_CONFIG=$JENKINS_HOME/jenkins.yaml

config.yaml

setting global jenkins authorization strategy
jenkins:
  authorizationStrategy:
	globalMatrix:
	  grantedPermissions:
		- "Overall/Administer:admin"
		- "Overall/Read:anonymous"
		- "View/Read:anonymous"
		- "Job/Read:anonymous"
		- "Job/Build:anonymous"
		- "Job/Cancel:authenticated"
configuring seed job
jobs:
  - file: "/data/jenkins/work/seed_job.groovy"
prevent jenkins from asking for approval for scripts
security:
  apiToken:
	creationOfLegacyTokenEnabled: false
	tokenGenerationOnCreationEnabled: false
	usageStatisticsEnabled: true
  globalJobDslSecurityConfiguration:
	useScriptSecurity: false
setting up an environment variable
globalNodeProperties:
	- envVars:
		env:
		- key: "[key]"
		  value: "[value]"
config git
jenkins:
  scmCheckoutRetryCount: 5
tool:
  git:
	installations:
	- home: "/usr/bin/git"
	  name: "git"

documentation

https://github.com/jenkinsci/configuration-as-code-plugin/blob/master/README.md

job-dsl

hello world job
#!/usr/bin/env groovy
job('hello-job') {
	displayName('Hello Job')
	steps {
		shell('echo "hello from \$PWD"')
	}   
}
now to make the seed job actually load worker jobs
#!/usr/bin/env groovy
job('seed-job') {
	displayName('Seed Job')
	steps {
		shell("cp -r /data/jenkins/jobs \$(pwd)")
		dsl {
			external('jobs/*.groovy')
			ignoreExisting(false)
			removeAction('DELETE')
			removeViewAction('DELETE')
			lookupStrategy('SEED_JOB')
		}
	}   
}
logging (shows up in seed log)
out.println('Hello from a Job DSL script!')
logging (shows up in jenkins log)
import java.util.logging.Logger
Logger logger = Logger.getLogger('org.example.jobdsl')
logger.info('Hello from a Job DSL script!')
runnning a shell script from workspace
steps {
		shell(readFileFromWorkspace('shell/script.sh'))
	}
adding parameters to a job
parameters {
		booleanParam('RUN_TESTS', true, 'uncheck to disable tests')
		stringParam('foo', 'bar', 'parameter description')
		choiceParam('choice', ['502', '508'], 'my first choice')
	}   
	steps {
		shell('echo "$foo = $choice"')
	}
some available variables
JOB_NAME
JENKINS_HOME=/home/[user]/.jenkins
HUDSON_HOME=/home/[user]/.jenkins
WORKSPACE=/home/[user]/.jenkins/workspace/[job]
JENKINS_URL
JOB_URL
BUILD_URL
printing all available environment variables (job dsl build step)
binding.variables.each{ 
  println "@ ${it.key} = ${it.value}"
}
documentation
https://wiki.jenkins.io/display/JENKINS/Building+a+software+project
https://github.com/jenkinsci/job-dsl-plugin/wiki/User-Power-Moves

scm

store jobs in git repository and automatically update jenkins
repo="https://example.com/jobs.git"
job('seed-job') {
		triggers {
				scm('@daily')
		}
		scm {
				git {
						branch('master')
						remote {
								url(repo)
						}
						extensions {
								cleanAfterCheckout()
						}
				}
		}
		steps {
				dsl {
						external('jobs/*.groovy')
						ignoreExisting(false)
						removeAction('DELETE')
						removeViewAction('DELETE')
						lookupStrategy('SEED_JOB')
				}
		}
}

cron jobs

every hour
triggers {
		cron("@hourly")
	}
regular cron syntax
// {Minute} {Hour 0-23} {DayOfMonth} {Month} {DayofWeek}
	triggers {
		// every minute
		cron("* * * * *")
	}
documentation jenkins cron syntax
https://jenkins.io/doc/book/pipeline/syntax/#triggers

clean up old builds

logRotator {
		numToKeep(10)
		artifactNumToKeep(10)
	}

serving a static file from jenkins

userContent('[path]', streamFileFromWorkspace('[file]'))
userContent('[path]', new File('[file]').newInputStream())
http://yourhost/userContent/[path]

jenkins api

absolute path os script
println("script directory: ${new File(__FILE__).parent.absolutePath}")
access seed job (FreeStyleProject)
SEED_JOB.quietPeriod
run a script in the seed directory
shell(SEED_JOB.getSomeWorkspace().child('myscript.sh').toString())
FreeStyleProject API
https://javadoc.jenkins-ci.org/hudson/model/FreeStyleProject.html
access executor
hudson.model.Executor.currentExecutor()
https://javadoc.jenkins-ci.org/hudson/model/Executor.html
to get the url for a job's config xml
https://[host]:[port]/[job]/config.xml

documentation

jenkins api
https://javadoc.jenkins-ci.org
groovy
https://groovy-lang.org/
jcascplugin
https://github.com/jenkinsci/configuration-as-code-plugin/blob/master/README.md
job dsl documentation
https://plugins.jenkins.io/job-dsl
jenkins dsl api
https://jenkinsci.github.io/job-dsl-plugin/
job dsl forum
https://groups.google.com/forum/#!msg/job-dsl-plugin