首页 > 解决方案 > 即使文件存在,Jenkins 管道“内容替换”插件也会出现“找不到文件”错误

问题描述

我第一次尝试 Jenkins 管道,但似乎无法弄清楚这里出了什么问题。我从 Subversion 签出了源代码,然后打算替换其中一个签出文件中的文件内容。

我收到以下错误(使用 Windows Jenkins slave)java.io.FileNotFoundException: File 'D:\JenkinsRoot\workspace\TestJob2\lib\database.cfg' 不存在

我可以看到该文件存在于从站上。

这是一个示例代码,

pipeline {
agent { label 'mynode' }
stages {
    stage('Test') {
        steps {
            checkout([$class: 'SubversionSCM', 
                additionalCredentials: [[...]], 
                excludedCommitMessages: '', 
                excludedRegions: '', 
                excludedRevprop: '', 
                excludedUsers: '', 
                filterChangelog: false, 
                ignoreDirPropChanges: false, 
                includedRegions: '', 
                locations: [[
                    credentialsId: '...', 
                    depthOption: 'infinity', 
                    ignoreExternalsOption: true, 
                    local: '.', 
                    remote: '...']], 
                workspaceUpdater: [$class: 'CheckoutUpdater']])
            sleep 5
            contentReplace(configs: [
                fileContentReplaceConfig(
                    configs: [
                        fileContentReplaceItemConfig(
                            matchCount: 1, 
                            replace: 'PSTG_USER=${PSTG_USER}', 
                            search: '^PSTG_USER=.*')], 
                        fileEncoding: 'UTF-8', 
                        filePath: 'lib/database.cfg')
        }
        }
    }
}

在上面的执行中,结帐正常进行,我添加了睡眠只是为了确保我不会过早更新文件。但是,我仍然收到文件未找到错误。任何指针?

该文件在 Windows 从站上使用以下命令存在,

D:\>dir D:\JenkinsRoot\workspace\TestJob2\lib\database.cfg
 Volume in drive D has no label.
 Volume Serial Number is 3268-CE51

 Directory of D:\JenkinsRoot\workspace\TestJob2\lib

02/04/2019  06:24 AM               175 database.cfg
               1 File(s)            175 bytes
               0 Dir(s)  101,310,660,608 bytes free

标签: jenkinsjenkins-pipeline

解决方案


以下代码对我有用,

pipeline {
    agent none
    stages {
        stage("Test") {
            steps {
                node('mynode'){
                    checkout(...)
                    script {
                        String out = readFile('lib/database.cfg').trim()
                        //This prints the original text
                        print out
                        out = out.replaceFirst(/DB_USER=.*/, "DB_USER=$DB_USER")
                        //This prints the replaced text
                        print out
                        writeFile(file: 'lib/database2.cfg', text: out, encoding: 'UTF-8')
                    }
                    //This prints the replaced text from the file
                    bat "type lib\\database2.cfg"
                }
            }
        }
    }
}

推荐阅读