book
  • README
  • cheatsheet
    • bash
      • builtin
      • syntactic sugar
      • cmd
      • havefun
    • text-processing
      • awk
      • sed
      • html
      • json
      • regex
      • unicode
    • osx
    • curl
    • tricky
    • widget
    • proxy
    • colors
    • math
    • media
    • ssl
      • keystore
      • verification
      • server
      • client
      • tricky
    • windows
      • powershell
      • choco
      • wsl
      • wt
      • shortcut
      • clsid
      • env
      • shell:folder
  • vim
    • nvim
    • install
    • color
    • plugins
      • usage
      • other plugins
      • deprecated
    • tricky
    • viml
    • windows
    • troubleshooting
  • devops
    • admin tools
    • ssh
    • git
      • config
      • alias
      • submodule
      • eol
      • example
      • gerrit
        • gerrit API
      • github
      • troubleshooting
      • tricky
      • statistics
    • pre-commit
    • release-tools
    • tmux
      • cheatsheet
    • ansible
    • vault
    • artifactory
      • api
      • cli
      • aql
      • nginx cert
    • klocwork
      • kwadmin
      • kwserver
      • api
      • q&a
    • elk
    • mongodb
    • android
    • mobile
  • jenkins
    • config
      • windows
    • appearance
    • troubleshooting
    • jenkinsfile
      • utility
      • parallel
      • build
      • envvar
      • properties
      • trigger
      • node
    • script
      • job
      • build
      • stage
      • agent
      • security & authorization
      • exception
      • monitor
      • tricky
    • api
      • blueocean
    • cli
    • plugins
      • kubernetes
      • docker
      • shared-libs
      • lockable-resource
      • ansicolor
      • badge
      • groovy-postbuild
      • simple-theme
      • customizable-header
      • artifactory
      • jira-steps
      • job-dsl
      • build-timeline
      • crumbIssuer
      • coverage
      • uno-choice
      • tricky
  • virtualization
    • kubernetes
      • init
        • kubespray
        • kubeadm
          • environment
          • crio v1.30.4
          • docker v1.15.3
          • HA
        • addons
        • etcd
      • kubectl
        • pod
        • deploy
        • replicasets
        • namespace
        • secrets
      • node
      • certificates
      • events
      • kubeconfig
      • kubelet
      • troubleshooting
      • cheatsheet
      • auth
      • api
      • tools
        • monitor
        • helm
        • network
        • minikube
    • docker
      • run & exec
      • voume
      • remove
      • show info
      • dockerfile
      • dockerd
      • tricky
      • troubleshooting
      • windows
    • crio
    • podman
  • ai
    • prompt
  • osx
    • apps
      • init
      • brew
    • defaults
    • system
    • network
    • script
    • tricky
  • linux
    • devenv
    • util
      • time & date
      • output formatting
      • params
      • tricky
    • nutshell
    • disk
    • network
    • troubleshooting
    • system
      • apt/yum/snap
      • authorization
      • apps
      • x11
    • ubuntu
      • systemctl
      • x
    • rpi
  • programming
    • groovy
    • python
      • config
      • basic
      • list
      • pip
      • q&a
    • others
    • archive
      • angular
      • maven
      • mysql
        • installation
        • logs
      • ruby
        • rubyInstallationQ&A
  • tools
    • fonts
    • html & css
    • Jira & Confluence
    • node & npm
      • gitbook
      • hexo
      • github.page
      • code themes
    • app
      • microsoft office
      • vscode
      • virtualbox
      • iterm2
      • browser
      • skype
      • teamviewer
      • others
  • quotes
  • english
Powered by GitBook
On this page
  • jenkins API
  • customized build
  • exception
  • withCredentials

Was this helpful?

  1. jenkins

jenkinsfile

PrevioustroubleshootingNextutility

Last updated 8 months ago

Was this helpful?

reference:

  • |

[!NOTE|label:good examples for pipeline flow:]

jenkins API

update node name

  • get label

    @NonCPS
    def getLabel(){
      for (node in jenkins.model.Jenkins.instance.nodes) {
        if (node.getNodeName().toString().equals("${env.NODE_NAME}".toString())) {
          currentLabel = node.getLabelString()
          return currentLabel
        }
      }
    }
  • set label

    @NonCPS
    def updateLabel(nodeName, newLabel) {
      def node = jenkins.model.Jenkins.instance.getNode(nodeName)
      if (node) {
        node.setLabelString(newLabel)
        node.save()
      }
    }
  • Jenkinsfile Example

    String curLabel       = null
    String newLabel       = null
    String testNodeName   = null
    String curProject     = env.JOB_NAME
    String curBuildNumber = env.BUILD_NUMBER
    
    node( 'controller' ) {
      try{
        stage("reserve node") {
          node("${params.tmNode}") {
            testNodeName = env.NODE_NAME
            curLabel  = getLabel()
            newLabel = "${curLabel}~running_${curProject}#${curBuildNumber}"
            echo "~~> lock ${testNodeName}. update lable: ${curLabel} ~> ${newLabel}"
            updateLabel(testNodeName, newLabel)
          } // node
        } // reserve stage
      } finally {
      if (newLabel) {
        stage("release node") {
          nodeLabels = "${newLabel}".split('~')
          orgLabel = nodeLabels[0]
          echo "~~> release ${testNodeName}. update lable ${newLabel} ~> ${orgLabel}"
          updateLabel(testNodeName, orgLabel)
        } // release stage
      } // if
    } // finally

raw build

reference:

Map buildResult = [:]

node( 'controller' ) {
  buildResult = build job: '/marslo/artifactory-lib',
                      propagate: true,
                      wait: true
  buildResult.each { println it }

  println """
                                      "result" : ${buildResult.result}
                         "getBuildVariables()" : ${buildResult.getBuildVariables()}
                  "getBuildVariables().mytest" : ${buildResult.getBuildVariables().mytest}
                  "getRawBuild().getEnvVars()" : ${buildResult.getRawBuild().getEnvVars()}
              "getRawBuild().getEnvironment()" : ${buildResult.getRawBuild.getEnvironment()}
                            "getBuildCauses()" : ${buildResult.getBuildCauses()}
                             "getChangeSets()" : ${buildResult.getChangeSets()}
                    "buildVariables["mytest"]" : ${buildResult.buildVariables["mytest"]}
                        "buildResult.rawBuild" : ${buildResult.rawBuild}
                    "buildResult.rawBuild.log" : ${buildResult.rawBuild.log}
"rawBuild.environment.RUN_CHANGES_DISPLAY_URL" : ${buildResult.rawBuild.environment.RUN_CHANGES_DISPLAY_URL}
  """
} // node

get changeSets

reference:

def res = [:]
timestamps { ansiColor('xterm') {
  node( 'controller' ){
    cleanWs()
    buildResult = build '/marslo/down'
    if( currentBuild.rawBuild.changeSets.isEmpty() ) {
      println "no new code committed"
    } else {
      buildResult.rawBuild.changeSets.each { cs ->
        cs.items.each { item ->
          println """
            -----------------------------
                  revision : ${item.commitId}
                    author : ${item.author}
                   message : ${item.msg}
            affected files :
              \t\t${item.affectedFiles.collect{ f -> f.editType.name + ' - ' + f.path }.join('\n\t\t\t\t')}
          """
        }
      }
    }
  }
}}
  • via api

    $ curl -sSg \
           https://jenkins.sample.com/job/<group>/job/<pipeline>/<buildId>/api/json |
           jq -r .changeSets[]
    
    # or
    $ curl -sSg \
           https://jenkins.sample.com/job/<group>/job/<pipeline>/<buildId>/api/json?depth=100&&tree=changeSets[*[*]]
if( manager.build.result.isBetterThan(hudson.model.Result.UNSTABLE) ) {
  def cmd = 'ssh -p 29418 $host gerrit review --verified +1 --code --review +2 --submit $GERRIT_CHANGE_NUMBER,$GERRIT_PATCHSET_NUMBER'
  cmd = manager.build.environment.expand(cmd)
  manager.listener.logger.println("Merge review: '$cmd'")
  def p = "$cmd".execute()
  manager.listener.logger.println(p.in.text)
  manager.addShortText("M")
}

customized build

display name

currentBuild.displayName = '#' + Integer.toString(currentBuild.number) + ' mytest'

description

currentBuild.description = 'this is whitebox'

exception

[!TIP|label:references:]

import hudson.AbortException

throw new AbortException( "throw aborted exception" )

show catch message

try {
  throw new AbortException( "throw aborted exception" )
} catch(e) {
  def sw = new StringWriter()
  e.printStackTrace( new PrintWriter(sw) )
  println sw.toString()
  // throw e                // if not throw error, the catch process will only print the error message
}

withCredentials

import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.common.StandardCredentials

def sample( String credential ) {
  [
    inSSH   : { println ".. ${credential}: ssh credential"   } ,
    inHttps : { println ".. ${credential}: git access token" }
  ]
}

def runWithCredentials ( String credential ) {
  Closure classifyCredential = { cid ->
    [
      ( com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl )   : {
        sample( credential ).inHttps()
      } ,
      ( com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey ) : {
        sample( credential ).inSSH()
      }
    ].find { it.key.isInstance(cid) }.value.call()
  }
  classifyCredential CredentialsProvider.lookupCredentials( StandardCredentials.class, jenkins.model.Jenkins.instance ).find { credential == it.id }
}

[ 'GITHUB_ACCESS_TOKEN', 'GITHUB_SSH_CREDENTIAL' ].each { runWithCredentials(it) }
  • result

    .. GITHUB_ACCESS_TOKEN: git access token
    .. GITHUB_SSH_CREDENTIAL: ssh credneital

|

|

using

Setup triggers inside the Jenkins Pipeline flow
Setup triggers inside the Jenkins Pipeline flow
Externalize the configuration of the Jenkins Pipeline flow
Externalize the configuration of the Jenkins Pipeline flow
org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper
hudson.model.Build<P,B>
hudson.model.Run<JobT,RunT>
hudson.plugins.git.GitChangeSet
hudson.scm.ChangeLogSet
Interface ChangeLogSet.AffectedFile
Class ChangeLogSet.Entry
hudson.model.AbstractBuild<P,R>
How to access Changelogs in a Pipeline Job?
lsjostro/changesets.groovy
manager.build.result.isBetterThan
Class Exception
How to time out Jenkins Pipeline stage and keep the pipeline running?
hudson.AbortException
* jenkinsci/jenkins/jenkinsfile
* jenkins-infra/pipeline-library
Pipeline Examples
Jenkins Pipeline Syantx
Jenkins Pipeline Cookbook
Pipeline Steps Reference
org.jenkinsci.plugins.workflow.steps
Pipeline Utility Steps
Jenkins Pipeline Cookbook
* declarative-pipeline-examples
Class Exception
Class TimeoutStepExecution
Class TimeoutStepExecution.ExceededTimeout
TimeoutStepExecution.java
Understanding the Differences Between Jenkins Scripted and Declarative Pipeline: A Comprehensive Guide with Real-World Examples
jenkins API
update node name
raw build
manager.build.result.isBetterThan
customized build
display name
description
exception
using hudson.AbortException
show catch message
withCredentials
get rawbuild changeset