Is there any way to pass variables from bash script to Jenkinsfile without using extra plugins - jenkins-pipeline

I'm trying to use variables declared in bash script in my Jenkinsfile (jenkins pipeline) without using extra plugins like EnvInject plugin
please help, any idea will be appreciated

you need to output those variables to a file like Property/Yaml file. Then use pipeline step readProperties / readYaml to read into Map in Jenkinsfile.
steps {
sh'''
...
AA=XXX
BB=YYY
set > vars.prop
'''
script {
vars = readProperties file: 'vars.prop'
env << vars // merge vars into env
echo 'AA='+ env['AA']
}
}

I have done it with something like this, you can store the variables inside Shell into a file inside workspace and then you are out of shell block, read the file in groovy to load the key value pair into your environment
Something like:
def env_file = "${WORKSPACE}/shell_env.txt"
echo ("INFO: envFileName = ${env_file}")
def read_env_file = readFile env_file
def lines = read_env_file.readLines()
lines.each { String line ->
def object = line.split("=")
env.object[0] = object[1]
}

Related

Groovy parameter to shell script

I've been trying to separate my code into two different files: callTheFunction.groovy and theFunction.groovy.
As you can see from the name of the file:
callTheFunction.groovy calls the function defined in theFunction.groovy, passing random values in as parameters.
theFunction is a shell script - inside groovy function - which is supposed to use the parameters passed from callTheFunction.
PROBLEM:
The shell script does not recognize/understand the arguments, the variables are empty, no value.
theFunction.groovy
def call(var1, var2) {
sh '''
echo "MY values $var1 and $var2"
'''
}
callTheFunction.groovy
def call {
pipeline {
stages {
stage ('myscript') {
steps {
theFunction("Value1", "Value2")
}
}
}
}
}
OUTPUT FROM PIPELINE:
MY values and
I am aware that there are similar issues out there:
Pass groovy variable to shell script
How to assign groovy variable to shell variable
UPDATES
You can use environment variable without having environment {}
Use environment variables like the ones i have used here (i refactored your code a little bit). Using triple single quotes for shell script for loop and adding grrovy variable to it:
def callfunc() {
sh '''
export s="key"
echo $s
for i in $VARENV1
do
echo "Looping ... i is set to $i"
done
'''
}
pipeline {
agent { label 'agent_1' }
stages {
stage ('Run script') {
steps {
script {
env.VARENV1 = "Peace"
}
callfunc()
}
}
}
}
OUTPUT:
Reference:
Jenkins - Passing parameter to groovy function

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.

Pass CommandLine Arguments to buildScript

I have a below task
task showLog1 <<{
def grgit = org.ajoberstar.grgit.Grgit.open(dir: '')
def log = grgit.log {
range '$tag1','$tag2'
}
}
Now I was using my tag names after the range but I want to pass this through Command Line. I have gone through few links like http://mrhaki.blogspot.in/2010/10/gradle-goodness-pass-command-line.html and I am passing from cli using -p like below:
gradlew showLog1 -ptag1=tag_one -ptag2=tag_two
But this doesn't give me the log. Anything that I am missing
Try a capital "P".
Like so: -Ptag1=tag_one -Ptag2=tag_two
Its working, I need to write my task like below:
build.gradle
def grgit = org.ajoberstar.grgit.Grgit.open(dir: "")
def log = grgit.log {
range "$tag1","$tag2"
}
Then I need to execute it like this :
Command Line
gradlew showLog1 -Ptag1=tag_one -project-prop tag2=tag_two
If you pass your vars via -P option as format -PvarName=xxx. varName became a property of you project object in buildScript
if (project.hasProperty('varName')) { //check varName is set or not
println "varName set to:" + varName; //use the varName directly.
}

Gradle: using a directory variable

In gradle I want to use a directory variable, what in ant would be ${mydir}.
def mydir = new File("mydir")
copy {
from 'example.txt'
into '${mydir}/out/'
}
How to do this? The docs don't contain information on this issue AFAICS, http://gradle.org/docs/current/userguide/working_with_files.html
Try:
into new File(mydir, out)
or if with GString
into "${mydir}/out/"
(note the double " quotes)

Why won't gradle Exec task run my command?

I have read around stackoverflow and the gradle forms, but I am still stumped. The ultimate goal here is that after I copy some files, I want to set the writable flag -- because 'copy' doesn't like overwriting read-only files on 'nix (huh...), nor can it be forced to do so (harumph!).
Here is the outline of what I have:
task setPermissions (type : Exec) {
executable = 'chmod -R +w'
}
// ... a little while later ...
task('somethingElse') << {
// ... unrelated stuff ...
def String targetDir = "$aVar/theTarget"
// >> TASK CALL <<
setPermissions {
commandLine = [executable + " $targetDir"]
}
// but that doesn't work... this does...
proc = Runtime.getRuntime().exec("chmod -R +w $deployDir")
proc.waitFor()
}
I have tried variations in "setPermissions".
Trial 1:
commandLine = 'chmod'
args = '-R', '+w'
In which case I appended the target directory to "args" when I called setPermissions.
Trial 2:
commandLine = 'chmod -R +w'
In which case I appended the target directory to "commandLine" when I called setPermissions. I also tried making it the only "args" value.
Trial 3:
commandLine = 'chmod', '-R', '+w'
In which case I appended the target directory to "commandLine" when I called setPermissions. I also tried making it the only "args" value.
So what am I doing wrong here that an Exec task won't run this properly, but the Rt.gR.exec() will?
You can't call a task from another task. You'll have to make one depend on the other, or call the Project.exec method from a task action. The syntax for configuring the exec method is exactly the same as for the Exec task.
PS: Have you tried to use Copy.fileMode instead of chmod?

Resources