Getting Java. Io. Notserializableexception: Org. Jenkinsci. Plugins. Workflow. Job. Workflowjob Error in Jenkins

I am using declarative pipeline wherein when I build my pipeline it is giving me java.io.NotSerializableException: org.jenkinsci.plugins.workflow.job.WorkflowJob error.

These are the 2 methods which I am using:-

@NonCPS
def getJob(name) {
    def hi = Hudson.instance
    return hi.getItemByFullName(name, Job)
}

@NonCPS
def getParam(WorkflowJob job, String paramName) {
    def prop = job.getProperty(ParametersDefinitionProperty.class)
    for (param in prop.getParameterDefinitions()) {
        if (param.name == paramName) {
            return param
        }
    }
    return null
}

And below is the part of my code where I am getting this error.

stages{
        stage("A"){
            steps{
                
                script {
                    
                    def job = getJob(JOB_NAME)
                    def param = getParam(job, "AWS Ser")
                    def service_name = ("${SERVICE_NAME}".replace('AWS Ser:', '')).toString().tokenize(',[]')
                    if (service_name != 'All') {
                        
                        def regions = "${REGIONS}".toString()
                        regions.split('\n').each() {
                            service_name.each() {
                                
                                sh '''
                                    echo "Welcome"
                                '''
                                    
                                

                            }
                            
                        }
                    }

Here, if you see when I put sh script then I get this error and if I remove this sh script then there is no error.

I tried to troubleshoot and something is wrong with the 2 methods which I mentioned above.

1 Answer

Don't return the WorkflowJob object to the Pipeline step. Refactor your functions like below.

@NonCPS
def getJob(name) {
    def hi = Hudson.instance
    return hi.getItemByFullName(name, Job)
}

@NonCPS
def getParam(String jobName, String paramName) {
    def job = getJob(jobName)
    def prop = job.getProperty(ParametersDefinitionProperty.class)
    for (param in prop.getParameterDefinitions()) {
        if (param.name == paramName) {
            return param
        }
    }
    return null
}

Then in the Pipeline stage call getParam as.

def param = getParam(JOB_NAME, "AWS Ser")
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest