简体   繁体   中英

Reuse groovy object / class in jenkins pipeline - shared library

i'm trying to reuse a groovy classes for multiple projects in a shared library. For this i created a simple Image class, which can build, tag and push container images by given image name, version etc...

The instantiation of an image object works fine and i can call the build method without any problem. But i would like to pass the object to another stage in the jenkinsfile, which causes the following error message:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: com.Image.$() is applicable for argument types: (org.jenkinsci.plugins.workflow.cps.CpsClosure2) values: 

Is there any way to pass objects ?

Jenkinsfile building stage:

    stage('building base container image with python') {
        when {
            anyOf { expression {return params.BuildBaseImages} }
        }
        steps {
            script{ 
            base_python = new Image(this, "${params.PYTHON_DOCKER_IMAGE_NAME}","${params.PYTHON_VERSION}", "centos7_baseimage_python/")
            base_python.build()
            alert.success "${params.PYTHON_DOCKER_IMAGE_NAME} builded"
            }
        }

        post {
            failure {
                error 'failed'
            }
        }
    }

Jenkinsfile tagging stage:

        stage('tag base image') {
        when {
            anyOf { expression {return params.BuildBaseImages} }
        }
                steps {
                    script {
                    base_python = base_python.tag("${DOCKER_IMAGE_FOLDER}${params.PYTHON_DOCKER_IMAGE_NAME}${params.PYTHON_VERSION}","${DOCKER_REGISTRY}") 
                    }
                }
    }

If you want to use variables across stages you need to declare them globally for example check the below.

// Global variable declaration
def base_python

pipeline {
    agent any
    stages {
        stage('Initialize') {      
             steps {
                 script {
                    base_python = new Image(this, "${params.PYTHON_DOCKER_IMAGE_NAME}","${params.PYTHON_VERSION}", "centos7_baseimage_python/")  
               }
            }
        }
        stage('Use') {    
                 steps {
                    script {
base_python.tag("${DOCKER_IMAGE_FOLDER}${params.PYTHON_DOCKER_IMAGE_NAME}${params.PYTHON_VERSION}","${DOCKER_REGISTRY}")              
                    }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM