代码之家  ›  专栏  ›  技术社区  ›  Robert Strauch

在声明性jenkinsfile的另一个阶段中使用变量

  •  1
  • Robert Strauch  · 技术社区  · 7 年前

    我在写声明 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 回复  |  直到 7 年前
        1
  •  2
  •   StephenKing    7 年前

    您只需要在一个作用域中定义变量,然后您就可以访问它了,也就是说。

    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()
                        }
                    }
                }
            }
        }
    
    }