How to pass env vars to a MultibranchPipelineJob created by Jenkins Job DSL? - jenkins

I am creating a MultibranchPipelineJob with Jenkins Job DSL. I want to pass some environment variables to the job, but I can't figure out how to do that from the documentation.

MultibranchPipeline Job no longer support parameters
You can use Folder Properties Plugin to set your Env variables, which can be accessed by all the jobs within that folder. https://plugins.jenkins.io/folder-properties/
However, the MultiBranch pipeline job has a lot of performance issues so we moved away from multibranch pipeline jobs. We wrote a DSL job that would act as a multibranch pipeline job - which will scan through the git branches and create Simple pipeline jobs as needed.

You pass them as parameters like this:
parameters {
stringParam("MyVariable1", "my-value1")
stringParam("MyVariable2", "${my-dynamic-value2}")
}
Then consume them in the job using parameters or environment (both work equally) as this:
echo "my vars are ${parameters.MyVariable1} or ${env.MyVariable2}"

Related

Jenkins with Jenkinsfile Pipeline - Trigger Builds Remotely

I have a Jenkinsfile setup for our CI/CD pipeline, and it runs through the pipeline on git actions like Pull Requests, Branch Creation, Tag Pushes, etc..
Prior to this setup, I was used to setting up Jenkins build jobs in the Jenkins UI. The advantage of this, was that I could setup dedicated build jobs that I could trigger remotely, and independently of git webhook actions. I could do a POST to the job endpoint with parameters to trigger various actions.
Documentation for this process would be referenced here - see "Trigger Builds Remotely"
I could also hit the big button that says "Build", or "Build with Parameters" in the UI, which was super nice.
How would one do this with a Jenkinsfile? Is this even possible to define build jobs in a pipeline definition within a Jenkinsfile? I.E. define functions / build jobs that have dedicated URLs that could be called on the Jenkins URL independent of webhook callbacks?
What's the best practice here?
Thanks for any tips, references, suggestions!
I would recommend starting with Multibranch pipelines. In general you get all the things you mentioned, but a little better. Because thhe paramteres can be defined within your Jenkinsfile. In short just do it like this:
Create a Jenkinsfile an check this into a Git Repository.
To create a Multibranch Pipeline: Click New Item on Jenkins home page.
Enter a name for your Pipeline, select Multibranch Pipeline and click OK.
Add a Branch Source (for example, Git) and enter the location of the repository.
Save the Multibranch Pipeline project.
A declarative Jenkinsfile can look like this:
pipeline {
agent any
parameters {
string(name: 'Greeting', defaultValue: 'Hello', description: 'How should I greet the world?')
}
stages {
stage('Example') {
steps {
echo "${params.Greeting} World!"
}
}
}
}
A good tutorial with screenshhots can be found here: https://www.jenkins.io/doc/book/pipeline/multibranch/

Jenkins Job Migration to Jenkinsfile

I am searching for a way to convert existing jenkins pipeline jobs with parameters to Jenkinsfile that include the parameter within it.
Maybe xml to Jenkinsfile or something but I am yet to discover a way (found job to DSL or something like that)
I am looking to get job to scripted groovy parameter

Jenkins - How to pass environmental variable from freestyle job to pipeline job

I have a freestyle job in Jenkins and would normally pass parameters to another freestyle job using the Predefined parameters option.
example:
PROJECT=Myproject
PATH=/depot/workspace/
Previously I could access the above values through the KEY in the downstream job through the environment by using ${PROJECT} OR ${PATH}.
My problem now is that I have a pipeline job that needs to access the above values but when using ${PROJECT} OR ${PATH} it does not work.
So, in general how I want it to work is have the freestyle job run first and pass the parameters to the downstream pipeline job.
You might need to use "${params.PROJECT}" in your pipeline to access the parameters.

Environment variable in Jenkins Pipeline

Is there any environment variable available for getting the Jenkins Pipeline Title?
I know we can use $JOB_NAME to get title for a freestyle job,
but is there anything that can be used for getting Pipeline name?
You can access the same environment variables from groovy using the same names (e.g. JOB_NAME or env.JOB_NAME).
From the documentation:
Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):
env.MYTOOL_VERSION = '1.33'
node {
sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
}
These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.
For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job
To avoid problems of side effects after changing env, especially using multiple nodes, it is better to set a temporary context.
One safe way to alter the environment is:
withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
sh '$MYTOOL_HOME/bin/start'
}
This approach does not poison the env after the command execution.

What are seed jobs in Jenkins and how does it work?

What are seed jobs in Jenkins and how does it work ?
Can we create a new job from seed job without using github ?
That depends on context. Jenkins itself does not provide "seed jobs".
There's plugins that allow creating jobs from other jobs, like the excellent Job-DSL plugin. With that, you can create jobs where a groovy script creates a larger number of jobs for you.
The Job-DSL plugin refers to those jobs as "seed jobs" (but they're regular freestyle or pipeline jobs). The Job-DSL plugin does not require a github connection.
The seed job is a normal Jenkins job that runs the Job DSL script; in turn, the script contains instructions that create additional jobs. In short, the seed job is a job that creates more jobs. In this step, you will construct a Job DSL script and incorporate it into a seed job. The Job DSL script that you’ll define will create a single freestyle job that prints a 'Hello World!' message in the job’s console output.
A Job DSL script consists of API methods provided by the Job DSL plugin; you can use these API methods to configure different aspects of a job, such as its type (freestyle versus pipeline jobs), build triggers, build parameters, post-build actions, and so on. You can find all supported methods on the API reference site.
The jobs we used for creating new jobs are called Seed Jobs and this seed job generates new jobs using Jenkins files (using JobDSL plugin).
Here, we disabling this feature (Enable script security for Job DSL scripts)
Jenkins Dashboard→ Manage Jenkins → Configure Global Security
Way to create seed job :
JobDSL scripts for generating new jobs.
Job1.groovy
job("Job1"){
description("First job")
authenticationToken('secret')
label('dynamic')
scm {
github('Asad/jenkins_jobDSL1', 'master')
}
triggers {
gitHubPushTrigger()
}
steps {
shell ('''
echo "test"
''')
}
}
buildPipelineView('project-A') {
title('Project A CI Pipeline')
displayedBuilds(5)
selectedJob('Job1')
showPipelineParameters()
refreshFrequency(60)
}
and create same way others Job2.groovy and so on.
For Jenkins Job DSL documentation:-
Follow https://jenkinsci.github.io/job-dsl-plugin/
Think about a job - what is it actually ?
It is actually just a java/jre object that represents like this
How you generates such job/build ?
Configure Jenkins UI -> rest api to Jenkins url -> Jenkins service receive your call on the relevant endpoint -> calling to the relevant code/method and generate this new job
How Seed job will make it ?
Configure seed job on Jenkins UI only once -> run this seed job - > this code run against the internal Jenkins methods and skip all the manual process describes above
Now, when your code can talk directly to Jenkins code , things are much easier.just update your code on the relevant repo - and you are done

Resources