带有共享库的Jenkinsfile

时间:2020-05-18 10:23:26

标签: jenkins continuous-integration jenkins-pipeline devops jenkins-groovy

无法弄清楚如何在具有共享库的管道中的某个阶段覆盖环境。

def call(Map config) {

if (config.nodeVersion == null) {
    config.nodeVersion = "11.12"
}

if (config.service == null) {
    throw new Exception('Service name must be set')
    // e.g live-client-roulette or  live-client-baccarat
}

if (config.buildScript == null) {
    config.buildScript = "npm run build"
}

pipeline {
    agent any

    options {
        disableConcurrentBuilds()
        timestamps()
        timeout(time: 1, unit: 'HOURS')
    }

    environment {
        NODE = "${config.nodeVersion}"
        BUILD_SCRIPT = "${config.buildScript}"

    }

    stage ('NPM build') {
            steps {
                script {
                    if (BRANCH_NAME ==~ /(master|release.*)/) {
                        environment {
                            NODE_ENV = 'production'
                        }                            
                    }
                    if (BRANCH_NAME == 'master') {
                        environment {
                            BUILD_SCRIPT = 'npm run build -p'
                        }
                    }
                }
                npmBuild()
            }
        }

这是npmbuild()函数的内容。

def call () {
withDockerContainer(image: "node:${NODE}", toolName: 'latest') {
    sh "${BUILD_SCRIPT}"
   }
}

但是,当分支是主环境时,请勿覆盖$ BUILD_SCRIPT env。 任何想法在这种情况下如何覆盖它?

1 个答案:

答案 0 :(得分:1)

原因是“环境”子句应保持在“脚本”之外的阶段以下。 你能试一下吗 ?

stage ('NPM build') {
    environment {
        NODE_ENV  = (BRANCH_NAME ==~ /(master|release.*)/) ? 'production' : 'dev'
        BUILD_SCRIPT = (BRANCH_NAME == 'master') ?: 'npm run build -p'
    } 
    steps {
            npmBuild()
        }
    }

或在script{}内,您可以使用export命令代替evironment{}

            script {
                if (BRANCH_NAME ==~ /(master|release.*)/) {
                   sh 'export BUILD_SCRIPT=\'npm run build -p\''                           
                }}