1

I am using below Jenkinsfile to create maven build and archive it after.

pipeline {
agent any

stages {
    stage('Build') {
        steps {
            withMaven(maven: 'mvn installed') {
                sh "mvn clean package"
            }
        }
        post {
            success {
                archiveArtifacts 'target/*.jar'
            }
        }
    }
}

After archiving the build it gets saved to target folder which has the jar file I want to use. However the build folder also contains the original com.. folder that contains the same jar. Is there any way I can delete this com folder after archiving, because it is just taking extra space in my server that I am not using at all.

Edit: I am not looking to clean the workspace but rather the original com folder inside the builds/<build_no>/archive/ folder

dev Joshi
  • 305
  • 2
  • 21

2 Answers2

1

Based on @dev-joshi's edit,

not looking to clean the workspace but rather the original com folder inside the builds/<build_no>/archive/ folder

I am guessing you are referring to the the target location for the "Archive the artifacts" post-build step and not the ./target directory, output of the maven compile step.

Your answer lies in the "[ X ] Discard old builds" option Discard Old Builds option

"Max # of builds to keep with artifacts" [ 1 ]
[if not empty, only up to this number of builds have their artifacts retained]
Setting that to [ 1 ] should achieve your objective.

If using a pipeline, this S/O answer and the syntax docs provides the syntax options:

 options { 
    buildDiscarder(logRotator(artifactNumToKeepStr: '1')) 
 }

You will have to execute another build for the existing artifacts to be cleaned up.

I'd also suggest you set Archive option:
"[ X ] Archive artifacts only if build is successful"
You don't want to blow away successful artifacts with a partially completed build.

Note too: mvn install will copy the generated artifacts to the local repo, following standard maven rules. That is normally outside the local workspace (unless choosing [ x ] private repo). You can then run mvn clean to delete the intermediary artifacts (*.class and *.jar, etc.) from the local workspace, returning you back to pre-build state. You can use the "Delete workspace" post-build step with "Patterns for files to be deleted" to achieve a similar effect (if you know what you are doing, or to simply remove the workspace entirely.

Ian W
  • 4,559
  • 2
  • 18
  • 37
-1

You need to install Workspace Cleanup plugin and add to the post section

post {
  success {
    archiveArtifacts 'target/*.jar'
    cleanWs ()
  }
  failure {
    cleanWs ()
  }
}
  

You can add cleanWs to always block, but in this case always is executing first all the time.

Dmitriy Tarasevich
  • 1,082
  • 5
  • 6