How do I fix this ant-junit task to work with configuration caching?

I have this task which uses ant and it’s not compatible with configuration cache. The ant api is not very transparent and I don’t know how to fix it:

tasks.register("mergeJUnitReports") {
    val testFlavor = project.extra["testFlavor"].toString()
    val testBuildType = project.extra["testBuildType"].toString()
    val unitTestTask = "test${testFlavor.capitalize()}${testBuildType.capitalize()}UnitTest"

    val resultsDir = file("${project.layout.buildDirectory.asFile.get()}/test-results/$unitTestTask")

    doLast {
        if (file(resultsDir).exists()) {
            ant.withGroovyBuilder {
                "taskdef"(
                    "name" to "junitreport",
                    "classname" to "org.apache.tools.ant.taskdefs.optional.junit.XMLResultAggregator",
                    "classpath" to antJUnit.asPath
                )
                "junitreport"("todir" to resultsDir) {
                    "fileset"("dir" to resultsDir, "includes" to "TEST-*.xml")
                }
            }
        }
    }
}

You did not share what problem you get reported, but it is probably because you access antJUnit from execution phase.

The question is, why you need that task at all. Most probably the best solution is, to eradicate the need for that task.
Besides the various bad practices you use there like ext/extra properties, prematurely getting the build dir property value at configuration time, not declaring inputs and outputs, …