What is the proper way to use readYaml in Jenkins declarative pipeline - jenkins

I saw examples of how to read a YAML file from a scripted Jenkins. I am looking for an example of how to properly read YAML (using readYaml?) in Jenkins declarative pipeline

The documentation: https://www.jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readyaml-read-yaml-from-files-in-the-workspace-or-text
In a single line, you can use readYaml like this:
def yaml = readYaml text: yourYamlContent
and you should have a yaml object you can extract data from, such as:
env.SOURCE_BRANCH = yaml.source.branch.name

Related

Groovy script to get Jenkins pipeline's script path

I want to run a script in Jenkins Script Console to retrieve scriptPath parameter of all jobs/pipelines configured in Jenkins. I found the way to get names of the pipelines but I want scriptPath parameters of each pipeline.
Any leads?
All pipeline jobs are instances of org.jenkinsci.plugins.workflow.job.WorkflowJob and can be found using the Jenkins.instance.getAllItems function.
Once found, each job contains an attribute of the FlowDefinition class whcih is accessible via the getDefinition() method. There are two types of definition for pipelines:
CpsFlowDefinition - for pipelines which define an inline script (not SCM), the script is accessible via the getScript() method.
CpsScmFlowDefinition - for pipelines which define an SCM script, the script is accessible via the getScriptPath() method.
So to achieve what you want you can go over relevant jobs and extract the relevant attribute:
def pipelineJobs =Jenkins.instance.getAllItems(org.jenkinsci.plugins.workflow.job.WorkflowJob)
def scmJobs = pipelineJobs.findAll { it.definition =~ 'CpsScmFlowDefinition'}
scmJobs.each {
println "Pipeline Name: ${it.name}"
println "SCM Script Path: ${it.definition.scriptPath}"
}
If all your jobs are SCM pipelines you can use the following single liner:
Jenkins.instance.getAllItems(org.jenkinsci.plugins.workflow.job.WorkflowJob)*.definition.scriptPath
For a single specific job you can use:
Jenkins.instance.getItemByFullName("<PIPELINE_NAME>").definition.scriptPath // or just script for inline definition

How to retrieve Jenkins environment from Groovy script?

I am setting a Jenkins. I am programming with my pipeline using Global Pipeline Libraries to be able to increase reusability. Scripts are object oriented and in Groovy. Information about the concept can be found there
I don't manage to retrieve the Jenkins specific environment using my library script. I would like for instance to access:
Build_ID
Build_Number
JOB_Name
Workspace_path
I tryied to use env.WORKSPACE but it is returning a NULL. I manage to retrieve it directly in the pipeline but this is not my goal.
I am using Jenkins 2.303.1.
Depending on how you write your scripts, you might need to inject the Jenkins environment. For example, if you go for a more object oriented way
// vars/whatever.groovy
import ...
#Field
def myTool = new MyTool(this)
// src/.../MyTool.groovy
import ...
class MyTool {
private final jenkins
MyTool(steps) {
this.jenkins = jenkins
}
def echoBuildNumber() {
this.jenkins.echo(this.jenkins.env.BUILD_NUMBER)
}
}
// Jenkinsfile
#Library(...)
node {
echo env.BUILD_NUMBER // echoes build number
whatever.myTool.echoBuildNumber() // echoes build number
}
So the env which you are looking for can be accessible using like this in groovy script
${env.BUILD_NUMBER}
${env.JOB_NAME}
${env.WORKSPACE}
${env.BUILD_ID}

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

Loading a JSON file from another job's archive into a Jenkins pipeline

I'd like to store a JSON file as the output of one job, and read that JSON in and parse it for use in a pipeline in a different job. I'm having trouble getting the JSON from the first job into my workspace so I can read it.
This mentions reading in a JSON, but not how to get it into the workspace = Pass Jenkins Pipeline parameters from a Jenkins job?
I see some suggestions that involve adding build steps (URL SCM plugin), but adding build steps doesn't seem available in my pipeline job
You should have a look at archiveArtifacts and copyArtifacts. You would archive the JSON file in one job and then copy it from in the other.
Edit:
In a pipeline you would do something like:
copyArtifacts(projectName: 'sourceproject')
or
copyArtifacts(projectName: 'downstream', selector: lastSuccessful())
You can look it up here: https://wiki.jenkins.io/display/JENKINS/Copy+Artifact+Plugin

How to invoke Inject environment variables to the build process plugin in jenkinsFIle jenkins 2.x with pipeline

I'm trying to migrate my project from jenkins 1 to jenkins 2.x using pipeline as code or Jenkinsfile.
But I don't see any option in snippet generator to generate environment injector plugin into a script in Jenkinsfile.
Anyone can help?
I'm assuming that you want to read properties from a specific file and inject them as environment variables?
If so, this is a solution:
Create the file that will contain the environment properties
You create some properties file called project.properties with following content:
PROJECT_VERSION='1.4.34'
Then, on your pipeline code, you've to add the following code in order to be able to read the file and inject read variables as environment variables:
node {
load "${WORKSPACE}\\project.properties" // assuming that props file is in
Jenkins Job's workspace
echo "PROJECT VERSION: ${PROJECT_VERSION}"
}
First line read and inject variable PROJECT_VERSION as environment variable
Second line is just to print read variable to make sure that everything worked seamlessly
Result:
Wanted to just comment on your question, but my lack of reputation is hindering me.
The list of supported steps is here: https://jenkins.io/doc/pipeline/steps/
In general, you can use other plugins by using their Java style invocation.
i.e.
step([$class: 'classname', parametername: 'value'])
I used this example for read a properties file and use it in a pipeline stage:
node(){
file = readFile('params.txt')
prop=[:]
file.eachLine{ line ->
l=line.split("=")
prop[l[0]]=l[1]
}
withEnv(['MyVar1='+prop["MyVar1"],'MyVar2='+prop["MyVar2"],'MyVar3='+prop["MyVar3]]){
stage('RUN_TEST'){
echo env.MyVar1
echo env.MyVar2
echo env.MyVar3
sh"echo $MyVar1"
}
}
}

Resources