Operations 5 min read

How to Safely Clean Up Old Webapp Directories with a Groovy CI Script

This article explains how to write a Groovy script for a CI pipeline that lists webapp directories on a Linux server, keeps the newest four, sorts them by modification time, and deletes the older ones using sudo to overcome permission issues, complete with full source code.

FunTester
FunTester
FunTester
How to Safely Clean Up Old Webapp Directories with a Groovy CI Script

Background: In a CI environment a dedicated server repeatedly receives WAR deployments, each creating a new webapps_* directory under /usr/local/tomcat/tomcat_aps. Over time these directories accumulate and fill the disk.

Problem: A simple cleanup script is needed to keep only the latest four webapp directories and delete the rest. The initial Groovy attempt listed the directories, sorted them, and called delete(), but the files were not removed because the script ran under a user without permission to delete Tomcat files.

Solution Overview: Use a Groovy script that builds a sudo -u tomcat rm -rf command for each directory to be removed, ensuring the operation runs with the same user that owns the Tomcat process.

def numberOfDirectoriesToKeep = 4

def webappsDir = new File('/usr/local/tomcat/tomcat_aps')

def webDirectories = webappsDir.listFiles().grep(/.*webapps_.*/)

def numberOfWebappsDirectories = webDirectories.size()

if (numberOfWebappsDirectories >= numberOfDirectoriesToKeep) {
    webDirectories.sort{ it.lastModified() }.reverse()[numberOfDirectoriesToKeep..numberOfWebappsDirectories-1].each { dir ->
        logger.info("Deleting ${dir}")
        def deleteCommand = "sudo -u tomcat rm -rf " + dir.toString()
        deleteCommand.execute()
    }
} else {
    logger.info("Too few web directories")
}

Full Script with Logging and Result Handling:

import org.slf4j.Logger
import com.my.ProcessingJobResult

def Logger logger = jobLogger
def ProcessingJobResult result = jobResult

try {
    logger.info("Deleting old webapps from CI - START")
    def numberOfDirectoriesToKeep = 4 // can be externalized
    def webappsDir = new File('/usr/local/tomcat/tomcat_aps')
    def webDirectories = webappsDir.listFiles().grep(/.*webapps_.*/)
    def numberOfWebappsDirectories = webDirectories.size()

    if (numberOfWebappsDirectories >= numberOfDirectoriesToKeep) {
        webDirectories.sort{ it.lastModified() }.reverse()[numberOfDirectoriesToKeep..numberOfWebappsDirectories-1].each { dir ->
            logger.info("Deleting ${dir}")
            def deleteCommand = "sudo -u tomcat rm -rf " + dir.toString()
            deleteCommand.execute()
        }
    } else {
        logger.info("Too few web directories")
    }

    result.status = Boolean.TRUE
    result.resultDescription = "Deleting old webapps from CI ended"
    logger.info("Deleting old webapps from CI - DONE")
} catch (Exception e) {
    logger.error(e.message, e)
    result.status = Boolean.FALSE
    result.resultError = e.message
}

return result

Note: There is a minor off‑by‑one indexing issue in the slice expression, but because the number of directories is always larger than the keep count, the author chose not to fix it.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AutomationlinuxScriptingCIGroovyFile Cleanup
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.