Reputation: 19099
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
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
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
Reputation: 169
There are several alternative ways:
#!/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')
fileOperations([script.fileDeleteOperation(excludes: '', includes: 'test.zip')])
def new_exclude_patterns = [[pattern: ".git/**", type: 'EXCLUDE']]
cleanWs deleteDirs: false, skipWhenFailed: false, patterns: new_exclude_patterns
Upvotes: 11
Reputation: 282
Navigate to /scriptApproval/ (Manage Jenkins > In-process Script Approval) and approve the script.
Upvotes: 0