Pass job parameter to gradle task in scripted pipeline - gradle

i'm trying to convert my freestyle job in a scripted pipeline, i'm using gradle for the build and artifactory to resolve my dependecies and publish artifacts.
My build is parametraized with 3 params and in freestyle job when i configure Invoke gradle script I have the checkbox Pass all job parameters as System properties and in my
project.gradle file I use the params with System.getProperty() command.
Now implementing my pipeline I define the job parameters, I have these like enviromnent variables in the Jenkinsfile but can I pass this params to the gradle task?
Following the official tutorial to use Artifactory-Gradle plugin in pipeline I run my build with :
buildinfo = rtGradle.run rootDir: "workspace/project/", buildFile: 'project.gradle', tasks: "cleanJunitPlatformTest build"
Can I pass params to gradle build and use in my .gradle file?
Thank's

Yes, you can. If using sh ''' then switch that to sh """ to get the expanded values
Jenkinsfile
#!/usr/bin/env groovy
pipeline {
agent any
parameters {
string(name: 'firstParam', defaultValue: 'AAA', description: '')
string(name: 'secondParam', defaultValue: 'BBB', description: '')
string(name: 'thirdParam', defaultValue: 'CCC', description: '')
}
stages {
stage ('compile') {
steps {
sh """
gradle -PfirstParam=${params.firstParam} -PsecondParam=${params.secondParam} -PthirdParam=${params.thirdParam} clean build
sh """
}
}
}
}
and inside your build.gradle you can access them as
def firstParam = project.getProperty("firstParam")
You can also use SystemProperty with -D prefix as compared to project property with -P. In that case you can get the value inside build.gradle as
def firstParam = System.getProperty("firstParam")

Related

Gradle zip task neither failing nor working

I'm trying to create a custom Gradle 4.3.1 task that will:
Run ./gradlew build which produces a build/libs/myapp.jar artifact; then
Creates a myapp-1.0.zip ZIP file whose contents include:
build/libs/myapp.jar; and
./AppGuide.md; and
./app-config.json
Here's my best attempt:
task zipMeUp(type: Zip) {
String zipName = 'myapp-1.0.zip'
doFirst {
tasks.build
}
from 'build/libs/myapp.jar'
from 'AppGuide.md'
from 'app-config.json'
into zipName
}
When I run this (./gradlew zipMeUp) I get the following output:
HarveyZ:myapp myuser$ ./gradlew zipMeUp
BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed
But nothing actually seems to happen (no myapp-1.0.zip file in the directory). Any idea what the fix/solution is?
Don't use doFirst, use dependsOn
task zipMeUp(type:Zip, dependsOn :[build]) {
String zipName = 'myapp-1.0.zip'
from 'build/libs/myapp.jar'
from 'AppGuide.md'
from 'app-config.json'
version = "1.0"
baseName = "myapp"
}

jenkinsfile - How do I access custom properties in my pom.xml?

Let's say I have a custom property in my pom.xml set like this:
<properties>
<app>com.myProject.app</app>
</properties>
How can I access it in my jenkinsfile?
This:
def pom = readMavenPom file: 'pom.xml'
def appName = pom.app
returns
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified field org.apache.maven.model.Model app
Thanks in advance!
I know two approaches:
Use properties-maven-plugin to write the properties to a file. Use readProperties in the Jenkinsfile to read the properties.
Works only if properties aren't needed until after Maven ran.
Also, with the right circumstances, the properties file may be the stale one from a previous run, which is insiduous because the property values will be right anyway 99.9% of the time.
Use pom = readMavenPom 'path/to/pom.xml'. Afterwards, access the property like this: pom.properties['com.myProject.app'].
I like approach 2 much better: No extra plugin configuration in the POM, no file written, less sequencing constraints, less fragilities.
In pipeline style, inside Jenkinsfile you can access the value as follows
pipeline {
environment {
POM_APP = readMavenPom().getProperties().getProperty('app')
}
stages{
stage('app stage'){
steps{
script{
sh """
echo ${POM_APP}
"""
}
}
}
}
Read a maven project file
try this:
IMAGE = readMavenPom().getArtifactId()
VERSION = readMavenPom().getVersion()
jenkins pipeline add this stage.
more see
stage('info')
{
steps
{
script
{
def version = sh script: 'mvn help:evaluate -Dexpression=project.version -q -DforceStdout', returnStdout: true
def artifactId = sh script: 'mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout', returnStdout: true
}
}
}

How to call another projects build.gradle file with command line arguments

I went through the following link and successfully implemented a task which calls build.gradle file from another project. i.e. solution provided by #karl worked for me.
But I need something up on that.
Can somebody help me to know how I can pass command line arguments while calling another build.gradle? Command line argument should be the variable which I have generated from my current build.gradle file.
In my case, I am defining a buildNumber and doing something like this:
def buildNumber = '10.0.0.1'
def projectToBuild = 'projectName'
def projectPath = "Path_till_my_Project_Dir"
task executeSubProj << {
def tempTask = tasks.create(name: "execute_$projectToBuild", type: GradleBuild)
// ****** I need to pass buildNumber as command line argument in "$projectPath/$projectToBuild/build.gradle" ******
tempTask.tasks = ['build']
tempTask.buildFile = "$projectPath/$projectToBuild/build.gradle"
tempTask.execute()
}
You should never call execute directly on any gradle object. The fact it's feasible doesn't mean it should be done and it's highly discouraged since you intrude internal gradle's execution graph structure.
What you need is a task of type GradleBuild which has StartParameter field that can be used to carry build options.
So:
task buildP2(type: GradleBuild) {
buildFile = '../p2/build.gradle'
startParameter.projectProperties = [lol: 'lol']
}
Full demo can be found here, navigate to p1 directory and run gradle buildP2.
You should modify your script in the following way:
def buildNumber = '10.0.0.1'
def projectToBuild = 'projectName'
def projectPath = "Path_till_my_Project_Dir"
task executeSubProj(type: GradleBuild) {
buildFile = "$projectPath/$projectToBuild/build.gradle"
tasks = ['build']
startParameter.projectProperties = [buildNumber: '10.0.0.1']
}
In the project that is executed use project.findProperty('buildNumber') to get the required value.

Gradle clean erasing my file prior to ZIP task execution

I have the following simple task in my build:
task generateFile << {
def file = new File("$buildDir/setclasspath.sh")
file.text = "sample"
outputs.file(file)
}
task createDistro(type: Zip, dependsOn: ['copyDependencies','packageEnvironments','jar', 'generateFile']) <<{
from generateClasspathScript {
fileMode = 0755
into 'bin'
}
}
When I run gradle clean build I see the following output:
Cannot call TaskOutputs.file(Object) on task ':generateFile' after task has started execution. Check the configuration of task ':generateFile' as you may have misused '<<' at task declaration
How do I declare the task file creation outputs as an input to the zip task while also ensuring they happen in the execution phase?
If I leave off the << then the clean task wipes the generated file before the ZIP can use it. If I keep them, I get the above error.
It's the opposite as what is being suggested in the comments. You are trying to set the outputs in execution phase. The correct way to do what you are probably trying to do is for example:
task generateFile {
def file = new File("$buildDir/setclasspath.sh")
outputs.file(file)
doLast {
file.text = "sample"
}
}

The nested copy task of svnant can't work in gradle

i am a newbie of both gradle and groovy, now i am try to setup a tag on my subversion repository. Below is my gradle script:
task svnrev {
// use ant to retrieve revision.
ant.taskdef(resource: 'org/tigris/subversion/svnant/svnantlib.xml') {
classpath {
fileset(dir: 'lib/DEV/svnant', includes: '*.jar')
}
}
ant.svn(javahl: 'false', svnkit: 'true', username: "${_svn_user}", password: "${_svn_password}", failonerror: 'false') {
ant.info(target: "${_svn_source_url}", propPrefix: 'svninfo')
}
// retrieve property of ant project and assign it to a task's property, refer to:
// http://gradle.1045684.n5.nabble.com/can-t-find-or-extract-properties-from-svnant-info-function-in-gradle-td3335388.html
ext.lastRev = ant.getProject().properties['svninfo.lastRev']
// retrieve property of gradle project
//getProject().properties['buildFile']
}
task svntag << {
ant.svn(javahl: 'false', svnkit: 'true', username: "${_svn_user}", password: "${_svn_password}", failonerror: 'false') {
copy(srcurl: "${_svn_source_url}", desturl="${_svn_tag_url}", message="Create tag: ${_svn_tag_url}")
}
}
The task 'svnrev' works normally, however when run 'gradle svntag', i constantly got a error message:
* What went wrong:
A problem occurred evaluating root project 'AFM-IGPE-v2.0.0'.
> Could not find method copy() for arguments [{srcurl=svn://192.168.2.9/IGPE/trunk_dev}, svn://192.168.2.9/IGPE/tag/AFM, Create tag: svn://192.168.2.9/IGPE/tag/AFM] on root project 'AFM-IGPE-v2.0.0'.
Also I tried
ant.copy(srcurl: "${_svn_source_url}", desturl="${_svn_tag_url}", message="Create tag: ${_svn_tag_url}")
And this time a different error message shown:
* What went wrong:
A problem occurred evaluating root project 'AFM-IGPE-v2.0.0'.
> No signature of method: org.gradle.api.internal.project.DefaultAntBuilder.copy() is applicable for argument types: (java.util.LinkedHashMap, org.codehaus.groovy.runtime.GStringImpl, org.codehaus.groovy.runtime.GStringImpl) values: [[srcurl:svn://192.168.2.9/IGPE/trunk_dev], ...]
Possible solutions: any(), notify(), wait(), grep(), every(), find()
In fact I just simple translate my ant build.xml to gradle, and my ant build.xml works well. I have googled a period time, however no results found. Pls help and thanks in advance for your kindly help.
At first sight, I can spot two problems:
It has to be task svnrev << {, not task svnrev {.
Groovy named parameters are written with a :, not a =. (The latter instead assigns a default value to a positional parameter.) That's probably why you get the error for ant.copy (you mix and match between : and =).

Resources