Search code examples
jenkinsjenkins-pipeline

Rename a file - Jenkins


As part of our pipeline I need to rename a file before it gets pushed up to GitHub. Previously this worked when running the Jenkins job on a master node, but now we run them on agents

def rename_build_file() {
  print "Append Version Number to File"
  // File without version
  String myFile = "${WORKSPACE_PATH}/release-pipeline/project/dist/myFile.js

  // File with version
  String myFileNew = "${WORKSPACE_PATH}/release-pipeline/project/dist/myfile-1.0.js"

  // Rename File
  new File(myFile).renameTo(new File(myFileNew));
}

Within our JenkinsFile we call helper.rename_build_file() and this usually works

When i sshd onto the agent I found that I had to run sudo to manually change a filename (did not have to enter a password), am i to assume that when the Jenkins job is running it's not running as sudo

And if that's the case how could i do this running the job?

Thanks


Solution

  • When working with files across multiple agents, you should use pipeline's workflow steps like fileExists, readFile, and writeFile. You can use a combination of these steps to create a new file with the desired name in the current workspace.

    def sourceFile = "release-pipeline/project/dist/myFile.js"
    
    if (fileExists(file: sourceFile)) {
        def newFile = "release-pipeline/project/dist/myFile-1.0.js"
    
        writeFile(file: newFile, encoding: "UTF-8", text: readFile(file: sourceFile, encoding: "UTF-8"))
    }