sfgroups
sfgroups

Reputation: 19099

Jenkins ver. 2.121.3 - Delete file from workspace

In Jenkins ver. 2.121.3 using pipeline trying to delete the file. Its giving script not permitted error message.

Is there a alternate way to delete the file in Jenkins with-out using OS command?

Scripts not permitted to use method java.io.File delete. Administrators can decide whether to approve or reject this signature.
[Pipeline] End of Pipeline
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method java.io.File delete

Pipeline code

stage('Delete test.zip file') {
    if (fileExists('test.zip')) {
        new File('test.zip').delete()
    } else {
        println "test.zip file not found"
    }
}

Upvotes: 1

Views: 42911

Answers (5)

Vetsin
Vetsin

Reputation: 2582

The proper way is via sh "rm test.zip" --

That is to say that Jenkins provides a few declarative steps out of box:

The equivalent of a "deleteFile" run via a pipeline (or shared library) would be like such:

getContext(hudson.model.Node).get(hudson.FilePath.class).child("test.zip").delete()

or:

import org.jenkinsci.plugins.workflow.cps.CpsThread

CpsThread.current().getContextVariable(
  FilePath.class, CpsThread.current().&getExecution, CpsThread.current().head.&get
)?.child('test.zip').delete()

But of course it makes more sense usually to just rm test.zip

Upvotes: 0

Gerold Broser
Gerold Broser

Reputation: 14762

Another way since Java 1.7/Groovy ?.? is:

Files.delete(Path.of(FQFN))

Upvotes: 0

Krishnom
Krishnom

Reputation: 1446

If you are running pipeline on linux slave (or windows slave with sh in path), you may use the below call to avoid interactive prompts.

sh(""" rm -rf "$directory" """)

Upvotes: 3

amdokamal
amdokamal

Reputation: 169

There are several alternative ways:

  1. By means of jenkins shared library you can wrap this code up to function or class:
#!/usr/bin/groovy
package org.utils

class PipelineUtils { 
    static def deleteFile(String name) { new File(name).delete() } 
}

in your pipeline script, you need to import the library:

@Library('your-jenkins-library')_    
import static org.utils.PipelineUtils.*
deleteFile('test.zip')
  1. As @Sean has suggested to approve the script via "Manage Jenkins > In-process Script Approval".
  2. There is File Operations Plugin:
fileOperations([script.fileDeleteOperation(excludes: '', includes: 'test.zip')])
  1. There is Workspace Cleanup Plugin, but you need to find suitable exclude-patterns, otherwise this will clean all files:
def new_exclude_patterns = [[pattern: ".git/**", type: 'EXCLUDE']]
cleanWs deleteDirs: false, skipWhenFailed: false, patterns: new_exclude_patterns

Upvotes: 11

Sean
Sean

Reputation: 282

Navigate to /scriptApproval/ (Manage Jenkins > In-process Script Approval) and approve the script.

Upvotes: 0

Related Questions