Reputation: 1557
In Jenkins, I know I can do this...
pipeline {
agent any
stages {
stage('Demo') {
steps {
MyFunction()
}
}
}
}
void MyFunction() {
sh 'ls /'
}
In this situation, the function is within the pipeline, but then I can always extract MyFunction
into a shared library for reuse across pipelines.
But would it be possible to do this with a post-build step?
In this case, I would like to convert this into a function and extract it into a library.
post {
always {
/* clean up our workspace */
deleteDir()
/* clean up tmp directory */
dir("${workspace}@tmp") {
deleteDir()
}
/* clean up script directory */
dir("${workspace}@script") {
deleteDir()
}
dir("${workspace}@2") {
deleteDir()
}
dir("${workspace}@2@tmp") {
deleteDir()
}
}
}
I've tried this
post {
always{
test()
}
}
}
With Function
void test() {
{
/* clean up our workspace */
deleteDir()
/* clean up tmp directory */
dir("${workspace}@tmp") {
deleteDir()
}
/* clean up script directory */
dir("${workspace}@script") {
deleteDir()
}
dir("${workspace}@2") {
deleteDir()
}
dir("${workspace}@2@tmp") {
deleteDir()
}
}
}
But it doesn't seem to work.
Is this possible at all or am I just missing something really obvious?
Upvotes: 2
Views: 1060
Reputation: 6859
The way that works for us to clean up the workspace after a specific stage and without trying to guess the folder name is to make your post function in stage:
pipeline {
agent any
stages {
stage('1') {
steps {
echo 'Hello World'
}
post {
cleanup {
script {
// Workspace Cleanup plugin
cleanWs deleteDirs: true,
notFailBuild: true,
cleanWhenAborted: true,
cleanWhenFailure: true,
cleanWhenSuccess: true
}
}
}
}
}
}
We use WorkspaceCleanup plugin.
Upvotes: 1
Reputation: 389
Passing the name of the workspace as a parameter in the function will solve your issue. The below script works.
pipeline {
agent any
stages {
stage('Hello') {
steps {
echo 'Hello World'
}
}
}
post{
always{
echo "In : ${env.WORKSPACE}"
test(env.WORKSPACE)
}
}
}
void test(workspace){
echo "In test : " + workspace
deleteDir()
dir("${workspace}@tmp") {
deleteDir()
}
}
Also, instead of calling deleteDir()
for multiple tmp directories, if you call deleteDir()
only once, then it will delete the workspace as well as tmp directories
Upvotes: 1