How to invoke Ant in a Jenkins Groovy Pipeline

20,413

Solution 1

you can use ant wrapper in Jenkins`s pipeline groovy script.

withAnt(installation: 'LocalAnt') {
// some block
   sh "ant build"
//for windows 
   bat "ant build"
}

Remember to configure the ant tool in the Jenkins "Global Tool Configuration" with the same name "LocalAnt".

Solution 2

You can try this:

def antVersion = 'Ant1.9.1'
withEnv( ["ANT_HOME=${tool antVersion}"] ) {
    sh '$ANT_HOME/bin/ant target1 target2'
}

Under Windows this would look like this (I didn't test it though):

def antVersion = 'Ant1.9.1'
withEnv( ["ANT_HOME=${tool antVersion}"] ) {
    bat '%ANT_HOME%/bin/ant.bat target1 target2'
}

This assumes that you have Ant configured in Jenkins with name 'Ant1.9.1'.

Solution 3

I needed this multiple times within the same Jenkinsfile that needs to be executed on both linux and windows agents so I created a method for it.

You can call ant like this

callAnt("-v -p")

if you add this method definition to your jenkinsfile

def callAnt(String Parameters) {
    if (isUnix()) {
        env.PATH = "${tool 'ant'}/bin;${env.PATH}"
        sh "ant ${Parameters}"
    }
    else {
        env.PATH = "${tool 'ant'}\\bin;${env.PATH}"
        bat "ant ${Parameters}"
    }
}

Share:
20,413
user5917011
Author by

user5917011

Updated on July 09, 2022

Comments

  • user5917011
    user5917011 almost 2 years

    I have created a Jenkins Pipeline job. In this job I want to do the build using Ant. I have configured the Ant variable in Manage **Jenkins > Global Tool Configuration** as Ant1.9.1= D:\path_to_hybris\hybris\bin\platform\apache-ant-1.9.1.

    In a freestyle jenkins Job, I know that the build.xml location can be specified as in the below screenshot: enter image description here

    but I am unable to understand how to specify the ant groovy script beyond this point, especially where can we mention the path to build.xml file:

    def antHome = tool 'Ant1.9.1'
    ????
    ????
    
  • henhen
    henhen about 4 years
    for the sh "ant build" do I need to put the path to the build xml file or will simply typing `"ant build" work?
  • sys64738
    sys64738 about 2 years
    use something like sh "ant -f build.xml all" where build.xmlis the path to the build file and all is the target. the complete looks like this: withAnt(installation: 'Ant1.9.1') { sh "ant -f build.xml all" } where Ant1.9.1 is the name of the Ant installation in Jenkins