0
0
JenkinsHow-ToBeginner · 3 min read

How to Delete a Build in Jenkins Quickly and Safely

To delete a build in Jenkins, go to the specific job, click on the build number you want to remove, then select Delete Build from the left menu. Alternatively, use a Groovy script in the Jenkins Script Console to delete builds programmatically.
📐

Syntax

Deleting a build in Jenkins can be done manually or via script.

  • Manual deletion: Navigate to the build page and click Delete Build.
  • Script deletion: Use Groovy commands in the Jenkins Script Console to delete builds by their build number.
groovy
def job = Jenkins.instance.getItemByFullName('job-name')
if (job != null) {
  def build = job.getBuildByNumber(buildNumber)
  if (build != null) {
    build.delete()
    println("Build #${buildNumber} deleted.")
  } else {
    println("Build #${buildNumber} not found.")
  }
} else {
  println('Job not found.')
}
💻

Example

This example shows how to delete build number 5 of a job named MyProject using the Jenkins Script Console.

groovy
def job = Jenkins.instance.getItemByFullName('MyProject')
if (job != null) {
  def build = job.getBuildByNumber(5)
  if (build != null) {
    build.delete()
    println('Build #5 deleted.')
  } else {
    println('Build #5 not found.')
  }
} else {
  println('Job MyProject not found.')
}
Output
Build #5 deleted.
⚠️

Common Pitfalls

Common mistakes when deleting builds in Jenkins include:

  • Trying to delete builds without proper permissions, which will fail silently or show errors.
  • Deleting builds from the wrong job or wrong build number.
  • Not refreshing the Jenkins UI after deletion, causing confusion about whether the build was removed.

Always double-check the job name and build number before deleting.

groovy
/* Wrong way: Using incorrect job name */
def job = Jenkins.instance.getItemByFullName('WrongJob')
if (job == null) {
  println('Job not found. Cannot delete build.')
}

/* Right way: Correct job name and build number */
def job = Jenkins.instance.getItemByFullName('MyProject')
def build = job.getBuildByNumber(5)
if (build != null) {
  build.delete()
  println('Build #5 deleted.')
} else {
  println('Build #5 not found.')
}
📊

Quick Reference

Tips for deleting builds in Jenkins:

  • Use the Jenkins web UI for quick manual deletions.
  • Use the Script Console for bulk or automated deletions.
  • Always confirm job and build numbers before deleting.
  • Ensure you have the necessary permissions to delete builds.

Key Takeaways

Delete builds manually via the Jenkins UI by selecting the build and clicking 'Delete Build'.
Use Groovy scripts in the Jenkins Script Console to delete builds programmatically.
Always verify the job name and build number before deleting to avoid mistakes.
Ensure you have the correct permissions to delete builds in Jenkins.
Refresh the Jenkins UI after deletion to see the updated build list.