p.streef p.streef - 1 year ago 371
Groovy Question

Get gradle variables in jenkins pipeline script

I'm trying to migrate my build pipelines to the "Pipeline plugin" using the groovy build scripts.

My pipelines are usually:

  1. Test (gradle)

  2. IntegrationTest (gradle)

  3. Build (gradle)

  4. Publish (artifactory)

I would like to use the gradle variables like version/group etc. in my jenkins build script to publish to the correct folders in artifactory. Something the artifactory plugin would take care of for me in the past. How can this be achieved?

For a single gradle project I use something like this:

def version = 1.0
def gitUrl = 'some.git'
def projectRoot = ""
def group = "dashboard/frontend/"
def artifactName = "dashboard_ui"
def artifactRepo = "ext-release-local"

stage "git"

git branch: 'develop', poll: true, url: "${gitUrl}"


sh 'chmod +x gradlew'
stage "test"
sh './gradlew clean test'

stage "build"
sh './gradlew build createPom'

stage "artifact"
def server = Artifactory.server('artifactory_dev01')
def uploadSpec = """{
"files": [
"pattern": "build/**.jar",
"target": "${artifactRepo}/$group/${artifactName}/${version}/${artifactName}-${version}.jar"
"pattern": "pom.xml",
"target": "${artifactRepo}/$group/${artifactName}/${version}/${artifactName}.pom"
def buildInfo1 = server.upload spec: uploadSpec
server.publishBuildInfo buildInfo1

Answer Source

I think you actually have two different approaches to tackle this problem :

1. Get version/group from sh script

Find a way to get Gradle version from gradle build tool (e.g. gradle getVersion(), but I'm not familiar with Gradle) and then use shell script to get this version. If Gradle command to get the version is gradle getVersion(), you would do in your pipeline :

def projectVersion = sh script: "gradle getVersion()", returnStdout: true
def projectGroup= sh script: "gradle getGroup()", returnStdout: true

and then just inject your $projectVersion and $projectGroup variables in your current pipeline.

2. Configure your Gradle build script to publish to Artifactory

This is the reverse approach, which I personnaly prefer : instead of giving Artifactory all your Gradle project information, juste give Gradle your Artifactory settings and use Gradle goal to easily publish to Artifactory.

JFrog has a good documentation for this solution in their Working with Gradle section. Basically, you will follow the following steps :

  1. Generate a compliant Gradle build script from Artifactory using Gradle Build Script Generator and include it to your project build script
  2. Use Gradle goal gradle artifactoryPublish to simply publish your current artifact to Artifactory
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download