I am trying to get a new job to run every time my Jenkins restarts. I want to do this through "init.groovy" script. For example let's say if I restart my jenkins server it will execute a job that says "Hello world". And I have to create this job from my init.groovy script.
I have this code so far
import jenkins.model.Jenkins
import org.jenkinsci.plugins.workflow.job.WorkflowJob
WorkflowJob job = Jenkins.instance.createProject(WorkflowJob, 'my-pipeline2')
now I don't know how to configure this job instance without getting into the GUI. I want to add pipeline scripts to it. Like echo "Hello world". And then I want to finally build this job. I want to do all that from this one init.groovy script. I couldn't find any solution to this over internet. So any help is greatly appreciated. Thanks
You could also try the Startup Trigger plugin.
Once installed, go the Job that you want to trigger after startup and in the section 'Build Triggers', check 'Build when Jenkins first starts'
(This question may be old, but hope my answer helps someone)
So I have finally done this with the following groovy script.
#!groovy
import jenkins.model.*
import hudson.security.*
import jenkins.install.*;
import hudson.triggers.SCMTrigger;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
def instance = Jenkins.getInstance()
println "--> creating local user 'admin'"
def hudsonRealm = new HudsonPrivateSecurityRealm(false)
hudsonRealm.createAccount('admin','admin')
instance.setSecurityRealm(hudsonRealm)
def strategy = new FullControlOnceLoggedInAuthorizationStrategy()
instance.setAuthorizationStrategy(strategy)
instance.save()
jenkins = Jenkins.instance;
workflowJob = new WorkflowJob(jenkins, "workflow2");
jobName = "create-dsl-job2";
gitTrigger = new SCMTrigger("* * * * *");
dslProject = new hudson.model.FreeStyleProject(jenkins, jobName);
dslProject.addTrigger(gitTrigger);
jenkins.add(dslProject, jobName);
job = jenkins.getItem(jobName)
builders = job.getBuildersList()
hudson.tasks.Shell newShell = new hudson.tasks.Shell("echo \"Hello\" ")
builders.replace(newShell)
gitTrigger.start(dslProject, true);
Related
I am trying to run a groovy script in Jenkins slave node to retrieve child jobs from a folder in Jenkins slave node. Here is the groovy script I tried:
I tried some SO answers and found groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding
But this doesn't solve my problem.
Please find the code that I tried:
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import jenkins.model.*
static main(args){
def childJobFolder = "childJob"
def childJobNameList = []
def env = System.getenv()
// Setting the environment properties to variables.
def jenkinsUsername = env.UAT_JENKINS_MY_USER
def jenkinsPassword = env.UAT_JENKINS_MY_PASS
def jsonSlurper = new JsonSlurper()
// Getting the child job names from "childJob" folder
Jenkins.instance.getItemByFullName(childJobFolder).allJobs.each{
def childJobName = it.name.toString()
if(childJobName.startsWith("job-")){
childJobNameList.add(childJobName)
}
}
println "\n" + "Child Jobs Available: " + childJobNameList + "\n"
}
Here is what I got in the console:
Caught: groovy.lang.MissingPropertyException: No such property: Jenkins for class: hudson3067346520259876246
groovy.lang.MissingPropertyException: No such property: Jenkins for class: hudson3067346520259876246
at hudson3067346520259876246.run(hudson3067346520259876246.groovy:17)
Build step 'Execute Groovy script' marked build as failure
Can someone help me to fix this error? Thanks in advance!
Finally, I found out the solution for this error. This is caused by running on plain groovy script instead of system groovy script. As Jayan said the Jenkins variables only available for System groovy scripts and not for plain groovy script. For that reason I could not load Jenkins instances from plain groovy script.
I searched a lot for this problem but couldn't find working solution anywhere. Can anybody please help me out? I want to get already existing env vars value through jenkins script console.
You need to distinguish:
build environment variables:
def myVar = build.getBuildVariables().get('myVar')
system environment variables:
System.getenv('MY_VARIABLE')
If you see
groovy.lang.MissingPropertyException: No such property: manager for class: Script1
Check this answer, and define build first:
import hudson.model.*
def build = Thread.currentThread().executable
def buildNumber = build.number
According to this answer, in order to access env vars from Jenkins script console, do as follows :
import jenkins.model.*;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.EnvVars;
jenkins = Jenkins.instance;
EnvironmentVariablesNodeProperty prop = jenkins.getGlobalNodeProperties().get(EnvironmentVariablesNodeProperty.class)
EnvVars env = prop.getEnvVars()
def myVariable = env['MY_VAR']
The env vars listed in http://<JENKINS_URL>/env-vars.html are available for each build. In order to access these variables in the Jenkins script console you need to define first the build :
build = Jenkins.instance.getItemByFullName('JOB_NAME').getBuildByNumber(BUILD_NUMBER)
envvars = build.getEnvironment()
envvars.each{envvar ->
println envvar
}
I need to check if specific job is running from another job. I dont want use API or plugins. Just bare hudson model.
I already tried some properties of Jenkins.instance.getItemByFullName('folder/job').lastBuild but they either returning whole job status (stable/unstable) or there is no RUNNING results. I even seen that there is a script which finds current running executors. So i dont believe that there is no way of checking running jobs.
https://wiki.jenkins.io/display/JENKINS/Find+builds+currently+running+that+has+been+executing+for+more+than+N+seconds
import com.cloudbees.groovy.cps.NonCPS
import jenkins.model.*
import hudson.model.Result
#NonCPS
def getProject(projectName) {
def project = jenkins.model.Jenkins.instance.getItemByFullName(projectName)
if (!project) {error("Project not found: $projectName")}
return project
}
project = getProject('folder/job')
build = project.lastBuild
def checkStatus2(){
//return Jenkins.instance.getItemByFullName('folder/job').lastBuild.getResult()
return Jenkins.instance.getItemByFullName('folder/job').lastBuild.buildStatusSummary.message
}
stage('check Job A status'){
//def status = checkStatus2()
//echo status
//if(hudson.model.Result.RUNNING.equals(status)){
if(build.#result == hudson.model.Result.NOT_BUILT){
echo "running"
}else{
echo "not running"
}
}
I found a thread which gave me a hint
Jenkins workflow check if job is running or schedulled
So i tried ...
if(Jenkins.instance.getItemByFullName('folder/job').isBuilding())
... and it works.
I'm having problems with my Jenkinsfile.
I want to list all running workers in current job, but jenkins just fails without printing any error. Code snippet:
#NonCPS
def check_running_process() {
// Check if PR build already in progress to kill old one
def pull_id = env.ghprbPullId.toInteger()
println pull_id
def current_build_id = env.BUILD_ID.toInteger()
println current_build_id
def currentJob = Jenkins.instance.getItemByFullName('jobname')
println currentJob
}
Output:
[Pipeline] echo
2
[Pipeline] echo
47
So Jenkins stops at def currentJob = Jenkins.instance.getItemByFullName('jobname')
There is no error produced, just a build fail.
There are no errors in jenkins.log file.
This works in scripting console.
Did anyone had the same problem?
Thank you
Okay, this was my problem.
I was calling check_running_process() inside try handler.
This produced no error, but failed because
method jenkins.model.Jenkins getItemByFullName java.lang.String
signature was not approved
(nor it produced script approval request).
I'm trying to setup Jenkins to be fully automated once I launch it from a docker container.
My question is how do I automate the configuration of the global Jenkins settings. For example the items in manage jenkins and credentials?
I'm using this a reference:
https://wiki.jenkins.io/display/jenkins/remote+access+api
Currently, I have the set these items up manually. I would like to fully automate the CI server creation. Is this possible with Jenkins or is there some human intervention that is required?
Any help would be greatly appreciated.
we used chef to setup the master , and it run some groovy scripts to install all the plugin and configuration. it almost done fully automatically , beside 1 or 2 plugins that I didn't find the syntax to configure all others works fine.
I installed all the plugins using Jenkins CLI , check yourJenkins/cli/ for reference.
for the general configuration you can install all the tools
import jenkins.model.*
import hudson.model.*
def inst1 = Jenkins.getInstance()
def desc1 = inst1.getDescriptor("hudson.tools.JDKInstaller")
println desc1.doPostCredential('buildJenkins#gmail.com','JenkinsOracleXXXXX')
import jenkins.model.*
import hudson.model.*
import hudson.tools.*
// JDK installation
def inst = Jenkins.getInstance()
def desc = inst.getDescriptor("hudson.model.JDK")
def versions = [
"jdk-1.8.101": "jdk-8u101-oth-JPR",
// "jdk-1.8.102": "jdk-8u102-oth-JPR"
]
general variables
// general properties
instance = Jenkins.getInstance()
globalNodeProperties = instance.getGlobalNodeProperties()
envVarsNodePropertyList = globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)
newEnvVarsNodeProperty = null
envVars = null
if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
globalNodeProperties.add(newEnvVarsNodeProperty)
envVars = newEnvVarsNodeProperty.getEnvVars()
} else {
envVars = envVarsNodePropertyList.get(0).getEnvVars()
}
envVars.put("ARTIFACTORY_URL", "artifactory-url")
envVars.put("ARTIFACTORY_USER", "jenkins")
envVars.put("DOCKER_USER", "docker-push")
instance.save()
email address
// admin Email
def jenkinsLocationConfiguration = JenkinsLocationConfiguration.get()
jenkinsLocationConfiguration.setAdminAddress('admin#yours.com')
jenkinsLocationConfiguration.save()
there a lot of examples , just look for groovy Jenkins configuration ..
if you have any specific question let me know.