在声明性Jenkinsfile的另一阶段使用变量

时间:2019-02-06 18:57:58

标签: jenkins jenkins-pipeline

我正在写一个看起来像这样的声明性Jenkinsfile。在“构建”阶段,我定义了变量“ customImage”,我想在“推”阶段使用该变量。

不幸的是,我无法使它正常工作。

pipeline {

    agent any

    stages {
        stage("Build") {
            steps {
                script {
                    def commitHash = GIT_COMMIT.take(7)
                    echo "Building Docker image for commit hash: " + commitHash
                    def customImage = docker.build("myimage:${commitHash}")
                }
            }
        }
        stage("Push") {
            steps {
                echo "Pushing Docker image to registry..."
                script {
                    docker.withRegistry(REGISTRY_SERVER, REGISTRY_CREDENTIALS) {
                        $customImage.push()
                    }
                }
            }
        }
    }

}

1 个答案:

答案 0 :(得分:2)

您只需要在一个范围内定义变量,您就可以在以后访问它,即

def customImage
pipeline {
    agent any
    stages {
        stage("Build") {
            steps {
                script {
                    def commitHash = GIT_COMMIT.take(7)
                    echo "Building Docker image for commit hash: " + commitHash
                    customImage = docker.build("myimage:${commitHash}")
                }
            }
        }
        stage("Push") {
            steps {
                echo "Pushing Docker image to registry..."
                script {
                    docker.withRegistry(REGISTRY_SERVER, REGISTRY_CREDENTIALS) {
                        customImage.push()
                    }
                }
            }
        }
    }

}