Skip to content

Instantly share code, notes, and snippets.

@entrofi
Last active August 21, 2021 21:58
Show Gist options
  • Save entrofi/1ac4048a35c42785fab10e79b9a017f0 to your computer and use it in GitHub Desktop.
Save entrofi/1ac4048a35c42785fab10e79b9a017f0 to your computer and use it in GitHub Desktop.
ci/cd as code - Creating a stateless jenkins instance
#!groovy
import hudson.security.*
import jenkins.model.*
def instance = Jenkins.getInstance()
def username = 'admin_groovy'
def hudsonRealm = new HudsonPrivateSecurityRealm(false)
hudsonRealm.createAccount(username,'123456')
instance.setSecurityRealm(hudsonRealm)
def strategy = new FullControlOnceLoggedInAuthorizationStrategy()
strategy.setAllowAnonymousRead(false)
instance.setAuthorizationStrategy(strategy)
instance.save()
import hudson.plugins.git.*
import jenkins.*
import jenkins.model.*
import hudson.*
import javaposse.jobdsl.plugin.*
import hudson.model.*
/**
* Api documentation for job dsl https://jenkins.io/doc/pipeline/steps/job-dsl/
*/
def jenkinsInstance = Jenkins.getInstance()
def jobName = "SeedJob"
// jobDsl plugin uses a free style project in order to seed jobs, let's initialise it.
def seedProdject = new FreeStyleProject(jenkinsInstance, jobName);
seedProdject.save()
def jobDslBuildStep = new ExecuteDslScripts()
jobDslBuildStep.with {
ignoreExisting = true
lookupStrategy = LookupStrategy.JENKINS_ROOT
removedJobAction = RemovedJobAction.DELETE
removedViewAction = RemovedViewAction.DELETE
useScriptText = true
scriptText = "job('example') {\n" +
" steps {\n" +
" shell('echo Hello World!')\n" +
" }\n" +
"}"
}
seedProdject.getBuildersList().add(jobDslBuildStep)
jenkinsInstance.reload()
/**
* Script to install build related tools like maven, jdk etc.
*/
import jenkins.model.*
import hudson.model.*
import hudson.tools.*
import hudson.tasks.Maven.MavenInstallation;
import hudson.util.DescribableList;
def instance = Jenkins.getInstance()
/**
* Install jdk
*/
def javaDescriptor = instance.getDescriptor(hudson.model.JDK.class)
def javaInstallations = []
def javaVersions = [
"jdk8": "jdk-8u102",
"jdk11": "jdk-11.0.5"
]
for (version in javaVersions) {
def installer = new JDKInstaller(version.value, true)
def installerProps = new InstallSourceProperty([installer])
def installation = new JDK(version.key, "", [installerProps])
//installer.getDescriptor().doPostCredential('username', 'password')
javaInstallations.push(installation)
}
javaDescriptor.setInstallations(javaInstallations.toArray(new JDK[0]))
javaDescriptor.save()
/**
* Install maven: https://stackoverflow.com/questions/55353804/how-to-automate-maven-and-java-jdk8-installation-with-groovy-for-jenkins
*/
mavenName = "maven3"
mavenVersion = "3.6.0"
println("Checking Maven installations...")
// Grab the Maven "task" (which is the plugin handle).
mavenPlugin = Jenkins.instance.getExtensionList(hudson.tasks.Maven.DescriptorImpl.class)[0]
// Check for a matching installation.
maven3Install = mavenPlugin.installations.find {
install -> install.name.equals(mavenName)
}
// If no match was found, add an installation.
if(maven3Install == null) {
println("No Maven install found. Adding...")
newMavenInstall = new hudson.tasks.Maven.MavenInstallation('maven3', null,
[new hudson.tools.InstallSourceProperty([new hudson.tasks.Maven.MavenInstaller(mavenVersion)])]
)
mavenPlugin.installations += newMavenInstall
mavenPlugin.save()
println("Maven installation added.")
} else {
println("Maven installation found. Done.")
}
import jenkins.model.Jenkins
import javaposse.jobdsl.plugin.GlobalJobDslSecurityConfiguration
import java.util.logging.Logger
def instance = Jenkins.instance
Logger logger = Logger.getLogger('jobdsl')
def jobDslSecurityConfig = instance.getExtensionList(GlobalJobDslSecurityConfiguration.class)[0]
if(jobDslSecurityConfig.useScriptSecurity) {
jobDslSecurityConfig.useScriptSecurity = false;
jobDslSecurityConfig.save()
logger.info("Script security disabled for jobDsl plugin")
}
//https://jenkinsci.github.io/job-dsl-plugin/#path/multibranchPipelineJob-branchSources
//https://javadoc.jenkins.io/plugin/workflow-multibranch/index.html?org/jenkinsci/plugins/workflow/multibranch/WorkflowBranchProjectFactory.html
def multiBranchJobs = [
[
name : 'spring-sandbox',
remote: 'https://github.com/entrofi/spring.git',
jenkinsFilePath: 'restassured-asciidoctor/Jenkinsfile',
includes: '*'
]
]
multiBranchJobs.each {
currentJob ->
multibranchPipelineJob(currentJob.name) {
branchSources {
git {
id(UUID.randomUUID().toString())
remote(currentJob.remote)
includes(currentJob.includes)
}
}
factory {
workflowBranchProjectFactory {
scriptPath(currentJob.jenkinsFilePath ?: 'Jenkinsfile')
}
}
orphanedItemStrategy {
discardOldItems {
numToKeep(100)
daysToKeep(10)
}
}
}
}
version: '3.2' #docker-compose.yml
services:
jenkins_entrofi:
build:
context: jenkins/
privileged: true
user: root
ports:
- 7080:8080
- 50005:50000
container_name: jenkins_entrofi
volumes:
- /var/run/docker.sock:/var/run/docker.sock
def jobScriptsRepository = "https://github.com/entrofi/oyunbahcesi.git"
def branch = "*/master"
def jobsScriptFile = "ci_cd/jenkins/configs/jobdsl/*.groovy"
def scm = new GitSCM(GitSCM.createRepoList(jobScriptsRepository, "jenkins"), [new BranchSpec(branch)], false, [], null, null, [])
def advancedJobName = "AdvancedSeedJob"
def advancedSeedProject = new FreeStyleProject(jenkinsInstance, advancedJobName)
advancedSeedProject.scm = scm
advancedSeedProject.save()
import hudson.plugins.git.*
import jenkins.*
import jenkins.model.*
import hudson.*
import javaposse.jobdsl.plugin.*
import hudson.model.*
/**
* Api documentation for job dsl https://jenkins.io/doc/pipeline/steps/job-dsl/
* Create a simple seed job and execute a job dsl script to create a job
*/
def jenkinsInstance = Jenkins.getInstance()
def jobName = "SimpleSeedJob"
// jobDsl plugin uses a free style project in order to seed jobs, let's initialise it.
def seedProject = new FreeStyleProject(jenkinsInstance, jobName);
seedProject.save()
def jobDslBuildStep = new ExecuteDslScripts()
jobDslBuildStep.with {
ignoreExisting = true
lookupStrategy = LookupStrategy.JENKINS_ROOT
removedJobAction = RemovedJobAction.DELETE
removedViewAction = RemovedViewAction.DELETE
useScriptText = true
scriptText = "job('DSL-Tutorial-1-Test') {\n" +
" scm {\n" +
" git('git://github.com/quidryan/aws-sdk-test.git')\n" +
" }\n" +
" triggers {\n" +
" scm('H/15 * * * *')\n" +
" }\n" +
" steps {\n" +
" maven{" +
" mavenInstallation('maven3')\n" +
" goals('clean install')\n" +
" }" +
" }\n" +
"}"
}
seedProject.getBuildersList().add(jobDslBuildStep)
/**
* Advanced job creation
*/
def jobScriptsRepository = "https://github.com/entrofi/oyunbahcesi.git"
def branch = "*/master"
def jobsScriptFile = "ci_cd/jenkins/configs/jobdsl/*.groovy"
def scm = new GitSCM(GitSCM.createRepoList(jobScriptsRepository, "jenkins"), [new BranchSpec(branch)], false, [], null, null, [])
def advancedJobName = "AdvancedSeedJob"
def advancedSeedProject = new FreeStyleProject(jenkinsInstance, advancedJobName)
advancedSeedProject.scm = scm
advancedSeedProject.save()
def advancedJobDslBuildStep = new ExecuteDslScripts()
advancedJobDslBuildStep.with {
ignoreExisting = true
lookupStrategy = LookupStrategy.JENKINS_ROOT
removedJobAction = RemovedJobAction.DELETE
removedViewAction = RemovedViewAction.DELETE
scriptText = ""
useScriptText = false
//create jobs using the scripts in a remote repository
targets = jobsScriptFile
}
advancedSeedProject.getBuildersList().add(advancedJobDslBuildStep)
jenkinsInstance.reload()
def advancedJobDslBuildStep = new ExecuteDslScripts()
advancedJobDslBuildStep.with {
ignoreExisting = true
lookupStrategy = LookupStrategy.JENKINS_ROOT
removedJobAction = RemovedJobAction.DELETE
removedViewAction = RemovedViewAction.DELETE
scriptText = ""
useScriptText = false
//create jobs using the scripts in a remote repository
targets = jobsScriptFile
}
advancedSeedProject.getBuildersList().add(advancedJobDslBuildStep)
jenkinsInstance.reload()
//...imports
def instance = Jenkins.getInstance()
/**
* Install jdk
*/
def javaDescriptor = instance.getDescriptor(hudson.model.JDK.class)
def javaInstallations = []
def javaVersions = [
"jdk8": "jdk-8u102",
"jdk11": "jdk-11.0.5"
]
for (version in javaVersions) {
def installer = new JDKInstaller(version.value, true)
def installerProps = new InstallSourceProperty([installer])
def installation = new JDK(version.key, "", [installerProps])
//installer.getDescriptor().doPostCredential('username', 'password')
javaInstallations.push(installation)
}
javaDescriptor.setInstallations(javaInstallations.toArray(new JDK[0]))
javaDescriptor.save()
/**
* Install maven: https://stackoverflow.com/questions/55353804/how-to-automate-maven-and-java-jdk8-installation-with-groovy-for-jenkins
*/
mavenName = "maven3"
mavenVersion = "3.6.0"
println("Checking Maven installations...")
// Grab the Maven "task" (which is the plugin handle).
mavenPlugin = Jenkins.instance.getExtensionList(hudson.tasks.Maven.DescriptorImpl.class)[0]
// Check for a matching installation.
maven3Install = mavenPlugin.installations.find {
install -> install.name.equals(mavenName)
}
// If no match was found, add an installation.
if(maven3Install == null) {
println("No Maven install found. Adding...")
newMavenInstall = new hudson.tasks.Maven.MavenInstallation('maven3', null,
[new hudson.tools.InstallSourceProperty([new hudson.tasks.Maven.MavenInstaller(mavenVersion)])]
)
mavenPlugin.installations += newMavenInstall
mavenPlugin.save()
println("Maven installation added.")
} else {
println("Maven installation found. Done.")
}
Jenkins.instance.pluginManager.plugins.each{
plugin -> println("${plugin.getShortName()}")
}
FROM jenkins/jenkins:lts
USER jenkins
ADD init.groovy/ /usr/share/jenkins/ref/init.groovy.d/
COPY configs/plugins /var/jenkins_init_config/plugins
RUN /usr/local/bin/install-plugins.sh < /var/jenkins_init_config/plugins
ace-editor
ant
antisamy-markup-formatter
apache-httpcomponents-client-4-api
authentication-tokens
bouncycastle-api
branch-api
build-timeout
cloudbees-folder
command-launcher
credentials
credentials-binding
display-url-api
docker-commons
docker-workflow
durable-task
email-ext
git
git-client
git-server
github
github-api
github-branch-source
gradle
handlebars
jackson2-api
jdk-tool
job-dsl
jquery-detached
jsch
junit
ldap
lockable-resources
mailer
mapdb-api
matrix-auth
matrix-project
momentjs
pam-auth
pipeline-build-step
pipeline-github-lib
pipeline-graph-analysis
pipeline-input-step
pipeline-milestone-step
pipeline-model-api
pipeline-model-declarative-agent
pipeline-model-definition
pipeline-model-extensions
pipeline-rest-api
pipeline-stage-step
pipeline-stage-tags-metadata
pipeline-stage-view
plain-credentials
resource-disposer
scm-api
script-security
ssh-credentials
ssh-slaves
structs
subversion
timestamper
token-macro
workflow-aggregator
workflow-api
workflow-basic-steps
workflow-cps
workflow-cps-global-lib
workflow-durable-task-step
workflow-job
workflow-multibranch
workflow-scm-step
workflow-step-api
workflow-support
ws-cleanup
pipeline {
agent any
tools {
maven 'maven3'
jdk 'jdk8'
}
stages {
stage('Build') {
steps {
sh 'mvn -B -DskipTests clean package'
}
}
stage('Test') {
steps {
sh 'mvn test'
}
post {
always {
junit 'target/surefire-reports/*.xml'
}
}
}
stage('Deliver') {
steps {
sh 'echo Delivered'
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment