在 Jenkins 脚本管道中设置环境变量然后 运行 脚本

Set environment variables then run script in Jenkins Scripted Pipeline

我是 Jenkins、Groovy 和管道的新手。我创建了一个简单的管道阶段,如下所示:

//working build but not setting env variables
node('build-01') {
    stage('Building') {
        echo "[*] Starting build (id: ${env.BUILD_ID}) on ${env.JENKINS_URL}"
        try {
            sh 'ls -l'
            //ls shows the damn file
            sh '. setup-target'
        } catch(all) { 
            sh "echo 'Failed to run setup-target script with error: ' ${all}"
        }
    }    
}

这行得通。但是我想 modify/add 环境变量到会话 运行 这个脚本(这个脚本是一个 bash 文件,上面有正确的 shebang 行)。所以我做了:

node('build-01') {
    withEnv(["CMAKE_INSTALL_DIR=${WORKSPACE}", "SDK_INSTALL_DIR=${WORKSPACE}"]){
        stage('Building') {
            echo "[*] Starting build (id: ${env.BUILD_ID}) on ${env.JENKINS_URL}"
            try {
                sh 'ls -l'
                //ls shows the damn file
                sh '. setup-target'
            } catch(all) { 
                sh "echo 'Failed to run setup-target script with error: ' ${all}"
            }
        }    
    }
}

此错误为:

/home/jenkins-sw/ci/workspace/myWorkSpace@tmp/durable-6d30b48d/script.sh: line 1: .: setup-target: file not found

Failed to run setup-target script with error: hudson.AbortException: script returned exit code 1

但是环境变量已设置,我通过在 ls -l 行正下方执行 sh 'printenv' 来检查这一点。有趣的是 ls -l 确实显示了脚本。

我错过了什么?

更新

以下:

node('build-01') {
    withEnv(["CMAKE_INSTALL_DIR=${WORKSPACE}", "SDK_INSTALL_DIR=${WORKSPACE}"]){
        stage('Building') {
            echo "[*] Starting build (id: ${env.BUILD_ID}) on ${env.JENKINS_URL}"
            try {
                sh 'ls -l'
                //ls shows the damn file
                sh './setup-target'
            } catch(all) { 
                sh "echo 'Failed to run setup-target script with error: ' ${all}"
            }
        }    
    }
}

结果:

/home/jenkins-sw/ci/workspace/myWorkSpace@tmp/durable-6d30b48d/script.sh: line 1: ./setup-target: Permission denied

有意思。 withEnv 如何影响权限?什么?!如果我对该文件进行 chmod 以获得权​​限,我会收到一个新错误,与 "missing workspace".

有关

我的猜测是 CMAKE_INSTALL_DIRSDK_INSTALL_DIR 在路径上。

而不是 sh '. setup-target' 你应该 sh './setup-target'.

我明白了。我直接克隆到工作区,然后将我的环境变量也设置为指向工作区。我修改了这两个东西。我现在在我的工作区中创建一个目录并克隆到它,我还将我的环境变量设置为我工作区内的目录。像这样:

node('build-01') {
    withEnv(["CMAKE_INSTALL_DIR=${WORKSPACE}/cmake_install", "SDK_INSTALL_DIR=${WORKSPACE}/sdk"]){
        stage('Building') {
            echo "[*] Starting build (id: ${env.BUILD_ID}) on ${env.JENKINS_URL}"
            try {
                sh 'ls -l'
                //ls shows the damn file
                dir('path/to/checkout/') {
                    sh '. ./setup-target'
                }
            } catch(all) { 
                sh "echo 'Failed to run setup-target script with error: ' ${all}"
            }
        }    
    }
}

这行得通。