This post shows how to customize standard Pipeline “steps” in Jenkinsfile besides their common usage.
List of basic Jenkinsfile steps in this post:
checkout/git
emailext
findFiles
input
junit
parameters/properties
podTemplates
sendSlack
stash/unstash
withCredentials
checkout/git step
scm is the global variable for the current commit AND branch AND repository of Jenkinsfile.
checkout scm means checking out all other files with same version as the Jenkinsfile associated with running pipeline.
To check out another repository, you need to specify the paremeters to checkout step.
Checkout from another Git repo
12345678910
checkout([$class:'GitSCM',branches:[[name:'*/master']],userRemoteConfigs:[[url:'http://git-server/user/repository.git']]])// From README file.checkoutscm:[$class:'MercurialSCM',source:'ssh://hg@bitbucket.org/user/repo',clean:true,credentialsId:'1234-5678-abcd'],poll:false// If scm is the only parameter, you can omit its name, but Groovy syntax then requires parentheses around the value:checkout([$class:'MercurialSCM',source:'ssh://hg@bitbucket.org/user/repo'])// Short hand form for Gitgitbranch:'develop',url:'https://github.com/WtfJoke/Any.git'
To send email as HTML page, set content type to HTML and use content as ${FILE,path="email.html"}.
In Jenkinsfile, the code should look like this:
Send HTML report as email
12345678
emailext(subject:'Deploy Notice',to:EMAIL_AUDIENCE,body:'${FILE,path="deploy_email.html"}',presendScript:'$DEFAULT_PRESEND_SCRIPT',replyTo:'devops@my.company.com',mimeType:'text/html'// email as HTML)
Note that it’s single-quoted strings, not double-quoted, being used for body and presendScript parameters in the example code above.
Simple input step can be used to ask for approval to proceed.
For asking input from a list of multiple choices, you can use the advanced version of input.
Input from list of choices
123456
sh"source scripts/findCL.sh > choiceLists.txt"defchoiceOptions=readFile"${env.WORKSPACE}/choiceLists.txt"defchoice=input(id:'CHOICE_LIST',message:'Choose a CL',parameters:[[$class:'ChoiceParameterDefinition',name:'CHOICE_LIST_SELECTED',description:'Select one',choices:choiceOptions]])
parameters step adds certain job parameters for the overall pipeline job.
parameters step in Declarative pipeline
1234567891011121314151617181920212223
pipeline{options{buildDiscarder(logRotator(numToKeepStr:'30',artifactNumToKeepStr:'30'))disableConcurrentBuilds()}agent{node{label'aqueduct-agent'}}parameters{choice(name:'ClusterName',choices:'func\ninteg\nperf',description:'Name of the cluster to test.')}stages{stage("Build"){steps{echo"Hello"...}}// end of stage}post{always{...}}}
In Scripted pipeline, its equivalent counterpart is properties step, as shown below.
In the Jenkins UI, this will be converted to configurations when you click on “View Configuration” for that job, as shown in screenshot below.
Note that the configurations in this page is read-only when using Jenkinsfile.
Any modifications made to the page will be ignored, leaving configurations set in Jenkinsfile final (“Infrastructure as Code”).
node('test-agent'){stage('Checkout'){checkoutscm}stage('Main'){withCredentials([string(credentialsId:'matrixsfdc-slack',variable:'TOKEN')]){slackSend(teamDomain:'matrixsfdc',channel:'#jenkins-pcloud',token:env.TOKEN,baseUrl:'https://matrixsfdc.slack.com/services/hooks/jenkins-ci/',color:'#FFFF00',message:"STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})")}}input'Finished with K8S pod?'}
stash/unstash steps
stash step can be used to save a set of files, to be unstashed later in the same build, generally for using in another workspace.
unstash will restore the files into the same relative locations as when they are stashed.
If you want to change the base directory of the stashed files, you should wrap the stash steps in dir step.
We should use stash/unstash to avoid the common anti-pattern of copying files into some special, globally visible directory such as Jenkins home or one of its subdirectories.
Using such anti-pattern will make it hard to support many jobs for many users since, eventually, there will be some name clash and, subsequently, some convoluted naming of those files to avoid such name clashes.
Note that stash and unstash steps are designed for use with small files.
If the size is above 5 MB, we should consider an alternative such as Nexus/Artifactory for jar files, blob stores for images.
There are different variations of withCredentials step.
The most common ones are:
Binding secret to username and password separately
12345678
node{withCredentials([usernamePassword(credentialsId:'amazon',usernameVariable:'USERNAME',passwordVariable:'PASSWORD')]){// available as an env variable, but will be masked if you try to print it out any which waysh'echo $PASSWORD'// also available as a Groovy variable—note double quotes for string interpolationecho"$USERNAME"}}
Binding secret to $username:$password
12345678
node{withCredentials([usernameColonPassword(credentialsId:'mylogin',variable:'USERPASS')]){sh''' set +x curl -u $USERPASS https://private.server/ > output '''}}
For secret file, the file will be passed into some secret location and that secret location will be bound to some variable.
If you want the secret files in specific locations, the workaround is to create symlinks to those secret files.
Binding secret file
123456789101112131415
withCredentials([file(credentialsId:'host-cert',variable:'HOST_CERT'),file(credentialsId:'host-key',variable:'HOST_KEY'),file(credentialsId:'cert-ca',variable:'CERT_CA')]){sh""" mkdir download ln -s ${env.HOST_CERT} download/hostcert.crt ln -s ${env.HOST_KEY} download/hostcert.key ln -s ${env.CERT_CA} download/ca.crt """// The Python script read those files download/*.* by defaultsh"python python/main.py"}
For “private key with passphrase” Credential type, sshagent is only usage that I know (credential ID is jenkins_ssh_key in this example):