Commands fail when moving to them custom class in jenkinsfile

感情迁移 提交于 2020-01-03 02:52:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!