问题
I'm setting up a new build. Running a simple shell command works perfectly, like below:
stage("Demo") {
sh "echo 'Hi There'"
}
I have been trying to "package" my shell scripts into their own classes just to neaten things up a bit. The problem is that when trying to execute the same exact shell script from within a class, jenkins fails the builds with:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified method java.lang.Class sh java.lang.String
This is a simple example that fails for me after moving the above method into its own class:
stage('Demo stage') {
Tools.PrintMe("Hi There")
}
public class Tools {
public static void PrintMe(String message) {
sh "echo " + message
}
}
There is also no option provided in the script manager to Whitelist this rejected method.
Is there a way to get around this? Or is there a limitation that I'm not aware of?
回答1:
@Crait to make a call of predefined steps in your own class you need to path script object to you class.
So, try this:
stage('Demo stage') {
Tools.PrintMe(this, "Hi There")
}
public class Tools {
public static void PrintMe(def script, String message) {
script.sh "echo " + message
}
}
回答2:
As @sshepel pointed out above, code executing in a plain script is not in the same context as code inside a class. I resolved it in a similar way to above by creating a static reference to the script object and then executing against that in my classes.
//Set the static reference in the script
Script.environment = this
public class Script {
public static environment
}
public class Tools {
public static void PrintMe(String message) {
Script.environment.sh "echo " + message
}
}
I did it this way to avoid polluting method signatures with passing the script object around. The downside is that all my classes will have a dependency on having "Script.environment = this" set.
来源:https://stackoverflow.com/questions/39817225/commands-fail-when-moving-to-them-custom-class-in-jenkinsfile