I have the following groovy script in a jenkins build
def myFractureNO = ${FRACTURE_NO};
def myBuildNumber = ${BUILD_NUMBER};
def projectXml = new XmlSlurper().parseText("curl http://sparkbuilder.corp.adobe.com:8080/job/FractureAUT/api/xml".execute().text);
projectXml.build.each {
if(it.number < myBuildNumber)
{
def jobXml = new XmlSlurper().parseText(("curl http://sparkbuilder.corp.adobe.com:8080/job/FractureAUT/" + it.number + "/api/xml").execute().text);
if(1) {
def myparams = jobXml.getAction(hudson.model.ParametersAction.class);
for( p in myparams ) {
if (p.name.toString == "FRACTURE_NO") {
if (p.value.toString() == "$myFractureNO") {
println p.value.toString();
}
}
}
}
}
}
I get an error saying
java.io.IOException: Cannot run program "groovy"
when jenkins tries to run this script on a Jenkins slave. How do I fix this?
Now I get the following error when trying to execute the script as a system script
groovy.lang.MissingMethodException: No signature of method: Script1.$() is applicable for argument types: (Script1$_run_closure1) values [Script1$_run_closure1#5e38bed4]
Possible solutions: is(java.lang.Object), run(), run(), any(), any(groovy.lang.Closure), use([Ljava.lang.Object;)
at Script1.run(Script1.groovy:1)
The following is not valid groovy:
def myFractureNO = ${FRACTURE_NO};
def myBuildNumber = ${BUILD_NUMBER};
I'm guessing you're trying to get some variables from the environment. See this related question: https://stackoverflow.com/a/26428580/172599
Related
In a jenkins shared library I can do something like this:
Jenkinsfile
#Library(value="my-shared-lib", changelog=false) _
jobGenerator {
notifier = [notifyEveryUnstableBuild: true]
}
sharedLibary/vars/jobGenerator.groovy
def call(body) {
println 'hi!'
}
To better understand the flow of whats goes on I have created two groovy files locally (with no reference to jenkins at all):
samples/launcher.groovy
jobGenerator {
s = 's'
}
samples/jobGenerator.groovy
def call(body) {
println 'inside jobGenerator '
}
But when I run that with:
groovy "/home/user/samples/launcher.groovy"
I get:
Caught: groovy.lang.MissingMethodException: No signature of method: launcher.jobGenerator() is applicable for argument types: (launcher$_run_closure1) values: [launcher$_run_closure1#61019f59]
groovy.lang.MissingMethodException: No signature of method: launcher.jobGenerator() is applicable for argument types: (launcher$_run_closure1) values: [launcher$_run_closure1#61019f59]
at launcher.run(launcher.groovy:2)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
So how much of the above code is jenkins/shared library specific? And is it even possible to write something like the above in plain groovy?
Or put in another way. How do I convert the above jenkins code to plain groovy?
IMHO following is close to what jenkins is doing
launcher.groovy
// load library scripts/functions
def binding = this.getBinding()
def gshell = new GroovyShell(this.getClass().getClassLoader(),binding)
new File("./my-lib").traverse(nameFilter: ~/.*\.groovy$/){f-> binding[f.name[0..-8]] = gshell.parse(f) }
// main
bar{
foo(name:"world")
}
./my-lib/foo.groovy
def call (Map m){
return "hello $m.name"
}
./my-lib/bar.groovy
def call (Closure c){
println ( "BAR: "+c() )
}
#> groovy launcher.groovy
BAR: hello world
I have created a pipeline that takes an array of JSON objects and will call a shared library which will iterate over the JSON objects
When trying to run the Jenkins job to test that I can forward the objects but I'm seeing the following error:
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: imageBuild.call() is applicable for argument types: (java.lang.String) values: [[{"dockerConfig":"home/pipelines/conf/journeys/dockerbuild.yaml","aquaConfig":"home/pipelines/conf/journeys/aquascan.yaml","gtag": "v1.0.1","preFixName": "journey1"},{"dockerConfig":"home/pipelines/conf/if.com/dockerbuild.yaml","aquaConfig":"home/pipelines/conf/if.com/aquascan.yaml","gtag": "v2.0.2","preFixName": "journey2"},{"dockerConfig":"home/pipelines/conf/colleague/dockerbuild.yaml","aquaConfig":"home/pipelines/conf/colleague/aquascan.yaml","gtag": "v3.0.3","preFixName": "journey2"}]]
Possible solutions: call(), call(java.util.Map), wait(), any(), wait(long), main([Ljava.lang.String;)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)
Code:
library identifier: 'jenkins-sharedlib-cooking#BB-3611', retriever: modernSCM([$class: 'GitSCMSource',
remote: 'https://github.com/lbg-gcp-foundation/jenkins-sharedlib-cooking-lifecycle.git',
credentialsId: 'jenkinsPAT'])
def configList = '[{"dockerConfig":"home/pipelines/conf/journeys/dockerbuild.yaml","aquaConfig":"home/pipelines/conf/journeys/aquascan.yaml","gtag": "v1.0.1","preFixName": "journey1"},{"dockerConfig":"home/pipelines/conf/if.com/dockerbuild.yaml","aquaConfig":"home/pipelines/conf/if.com/aquascan.yaml","gtag": "v2.0.2","preFixName": "journey2"},{"dockerConfig":"home/pipelines/conf/colleague/dockerbuild.yaml","aquaConfig":"home/pipelines/conf/colleague/aquascan.yaml","gtag": "v3.0.3","preFixName": "journey2"}]'
pipeline {
environment {
def config =
brand =
environmentName =
CLUSTER_NAME =
CLUSTER_PROJECT =
VERSION = '1.0.0'
}
options {
ansiColor('xterm')
timeout(time: 150, unit: 'MINUTES')
disableConcurrentBuilds()
buildDiscarder(logRotator(numToKeepStr: '100'))
}
agent {
kubernetes {
label "jrn-${UUID.randomUUID().toString()}"
yamlFile "pipelines/conf/podTemplate.yaml"
}
}
stages {
stage('Stage 6 - Docker Image ') {
parallel {
stage ('Docker Image - Journeys') {
steps {
echo "*********************** Docker Journeys ***********************************"
container('docker') {
echo "Building the docker image..."
imageBuild(configList)
}
archiveArtifacts artifacts: "*.html", allowEmptyArchive: true
}
}
}enter code here
}
}
Looks like the groovy method or global variable imageBuild in the shared library Jenkins-shared lib-cooking#BB-3611 does not expecting any parameter but you are trying to pass a string, that's the reason you are getting MissingMethodException.
with the details
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: imageBuild.call() is applicable for argument types: (java.lang.String) values
To fix the issue, you have to change the shared library method or global variable imageBuild from imageBuild() to imageBuild(String param) or imageBuild(def param)
I will try to illustrate with an example similar to your example for your reference.
Assuming you have a shared library in a git repository named - jenkins-sharedlib-cooking-lifecycle and you are following the folder structure suggested by Jenkins shared library documentation
// vars/imageBuild.groovy
import groovy.json.JsonSlurper
def call(def imagebuildParameter) {
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(imagebuildParameter)
// use loop on object to retrive the value like below
println object[0].name
}
//Jenkinsfile
node {
stage('stageName') {
def x = '[{"name": "foo"},{"name": "bar"}]'
imageBuild(x)
}
}
I'm trying to build a bunch of similar jobs (changing parameters) by reading from a config YAML file.
However, when I try to use the readYaml method from the pipeline-utility-steps-plugin (version 2.5.0 is installed) I get the following error when I try to seed it:
ERROR: (borg_backups.groovy, line 31) No signature of method: borg_backups.readYaml() is applicable for argument types: (java.util.LinkedHashMap) values: [[file:/var/jenkins_home/workspace/seed-job/redacted/us-west-2/borg-backups/config/borg-stage-config.yml]]
Finished: FAILURE
This is the snippet of the code where I use it:
environments.each { envEntry ->
folder("$basePath/$envEntry.key") {
displayName("$envEntry.value")
description("Backup Jobs uploaded to Borg $envEntry.value environment")
}
regions.each { regionEntry ->
String configFilePath = "redacted/$regionEntry/borg-backups/config/borg-$envEntry.key-config.yml"
def fullTestPath = new File("$seedWorkspacePath/$configFilePath")
if( fullTestPath.exists() ) {
folder("$basePath/$envEntry.key/$regionEntry") {
displayName("$regionEntry")
description("Backup Jobs uploaded to Borg $envEntry.value environment: $regionEntry region")
}
def configs = readYaml (file: "$seedWorkspacePath/$configFilePath")
if (configs.borg_environment == "stage"){
folder("$basePath/$envEntry.key/$regionEntry/kafka") {
displayName(configs.services.kafka.name)
description("Checking if it is parsing the YAML configs correctly")
}
}
I'm new to Groovy and am trying to invoke a Groovy script as a Jenkins Post-build Action, but whenever I run it, I'm getting "ERROR: Failed to evaluate groovy script":
groovy.lang.MissingMethodException: No signature of method: Script1.stage() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl, Script1$_run_closure1) values: [branch_1, Script1$_run_closure1#7e39737b]
Possible solutions: wait(), any(), isCase(java.lang.Object) at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)
Here is my code :
def warList1= ["one.war", "two.war", "three.war" ]
def branches = [:]
for (int i = 0; i < 10 ; i++) {
int index=i, branch = i+1
stage ("branch_${branch}"){
branches["branch_${branch}"] = {
node {
sshagent(credentials : ['someuser-SSH']){
sh "scp ${WORKSPACE}/${warList1[index]} someuser#<somefqdn>:/tmp/pscp/dev"
}
}
}
}
}
}
I think that your issue come from the fact that you can not use stage method in a Groovy Post Build Action. This method is only available in a pipeline script.
I'm attempting to delete the build history from Jenkins using the instructions in this answer:
How do I clear my Jenkins/Hudson build history?
However, I'm getting the following error message:
groovy.lang.MissingMethodException: No signature of method:
jenkins.branch.OrganizationFolder.getBuilds() is applicable for
argument types: () values: [] Possible solutions: getViews(),
doBuild(jenkins.util.TimeDuration), getUrl(), getClass(),
getActions(), getApi() at
org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)
at
org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:49)
at
org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
If I run this script:
def jobName = "github-test"
def job = Jenkins.instance.getItem(jobName)
println(job)
I get the following output:
jenkins.branch.OrganizationFolder#134f3a3c[github-test]
I'm using version 2.32.2.
Here's the exact script that I ran:
def jobName = "github-test"
def job = Jenkins.instance.getItem(jobName)
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()
The job that you are trying to delete, github-test, is an organization folder, e.g. you get jenkins.branch.OrganizationFolder. This means that it's not an actual job with actual builds, instead it's a folder which contains other jobs. Worth noting is that OrganizationFolder is of the type ComputedFolder which means that it is populated automatically by Jenkins when it finds new repositories and branches (on github).
So I'm guessing that you wan't to remove all builds from the sub-jobs in your github-test job/folder. I've modified the linked answer so that it accounts for folders:
import com.cloudbees.hudson.plugins.folder.AbstractFolder
import hudson.model.AbstractItem
// change this variable to match the name of the job whose builds you want to delete
def jobName = "test"
// Set to true in order to reset build number to 1
def resetBuildNumber = false
def removeBuilds(job, resetBuildNumber) {
if (job instanceof AbstractFolder) {
for (subJob in job.getItems()) {
removeBuilds(subJob, resetBuildNumber)
}
} else if (job instanceof AbstractItem) {
job.getBuilds().each { it.delete() }
if (resetBuildNumber) {
job.nextBuildNumber = 1
job.save()
}
} else {
throw new RuntimeException("Unsupported job type ${job.getClass().getName()}!")
}
}
removeBuilds(Jenkins.instance.getItem(jobName), resetBuildNumber)
You can use the script below to delete builds. You can specify how many latest builds to retain, just add a value of your choice to MAX_BUILDS.make it 0 to delete everything.
Assuming the builds you want to deleted belongs to "github-test". Replace jobName value with your choice
MAX_BUILDS = 5
def jobName = "github-test"
def job = Jenkins.instance.getItem(jobName)
println ""
println "selected Jenkins Job : "
println job.name
def recent = job.builds.limit(MAX_BUILDS)
println recent
for (build in job.builds) {
if (!recent.contains(build)) {
println ""
println "========================================================="
println "Preparing to delete: " + build
build.delete()
println ""
}
}