Craigt Craigt - 2 months ago 66
Groovy Question

Commands fail when moving to them custom class in jenkinsfile

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?

Answer

@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
    }
}
Comments