Monday, January 20, 2020

The Jenkins automation to read upstream job information is made possible with APIs. For example:

    for (String jobName : jobNames.keySet()) { 
        def imageName = jobNames.get(jobName) 
        def buildJson = ["wget", "-qO-", "${uri}"].execute().text 
        def start = buildJson.indexOf('"description":"') 
        def end = buildJson.indexOf('"', start+15) 
        def remoteBuildVersion = "" 
        println("${start}:${end}") 
        if (start != -1 && end != -1 && end > start) { 
            remoteBuildVersion = buildJson.substring(start+15, end) 
        } 
        manifestFileLines.each { line -> 
             if (line.contains("${imageName}:")) { 
                 localBuildVersion  =  line.split(":")[1] 
                 if (remoteBuildVersion != localBuildVersion) { 
                     pattern=remoteBuildVersion 
                     replacement=localBuildVersion 
                     println("replacing ${pattern} with ${replacement} in ${imageName}") 
                     filesToBeModified.eachFileRecurse( 
                            {file -> 
                                  fileText = file.text; 
                                  def backupFile = file.path + ".bak" 
                                  writeFile(file: backupFile, text:  fileText) 
                                  fileText = fileText.replaceAll(pattern, replacement) 
                                  writeFile(file: file.path, text: fileText) 
                            }) 
                 } else { 
                     println("${jobName} build version ${remoteBuildVersion} matches ${localBuildVersion}") 
                 } 
             } 
        } 
    } 

Note the above script is specific to Jenkinsfile and avoids popular groovy syntax even though groovy can be used in Jenkinsfile otherwise we might see errors such as : “Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods execute java.util.List. Administrators can decide whether to approve or reject this signature. 
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods execute java.util.List” 

No comments:

Post a Comment