Groovy parameter to shell script - shell

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

Related

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

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]
}

how to use choice parameter in Jenkins pipeline in batch command

how to use choice parameter in Jenkins declarative pipeline in batch command.
I'm using following stage:
choice(
choices: 'apply\ndestroy\n',
description: '',
name: 'DESTROY_OR_APPLY')
stage ('temp') {
steps {
echo "type ${params.DESTROY_OR_APPLY}"
bat'echo "type01 ${params.DESTROY_OR_APPLY}"'
bat'echo "type01 %{params.DESTROY_OR_APPLY}%"'
bat'echo type01 [${params.DESTROY_OR_APPLY}]'
}
echo does resolve to correct parameter value but under bat none of the above code works.
You almost got the syntax right.
If you change it to one of the below options, the bat command receives the value of your choice.
steps {
bat "echo type01 ${DESTROY_OR_APPLY}"
}
or
steps {
bat 'echo type01 ' + DESTROY_OR_APPLY
}
You can also use ${params.DESTROY_OR_APPLY} in the first or params.DESTROY_OR_APPLY in the second example if you want to use the params definition consequently in your code.

Console Output in pipeline:Jenkins

I have created a complex pipeline. In each stage I have called a job. I want to see the console output for each job in a stage in Jenkins. How to get it?
The object returned from a build step can be used to query the log like this:
pipeline {
agent any
stages {
stage('test') {
steps {
echo 'Building anotherJob and getting the log'
script {
def bRun = build 'anotherJob'
echo 'last 100 lines of BuildB'
for(String line : bRun.getRawBuild().getLog(100)){
echo line
}
}
}
}
}
}
The object returned from the build step is a RunWrapper class object. The getRawBuild() call is returning a Run object - there may be other options than reading the log line-by-line from the looks of this class. For this to work you need to either disable the pipeline sandbox or get script approvals for these methods:
method hudson.model.Run getLog int
method org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper getRawBuild
If you are doing this for many builds, it would be worth putting some code in a pipeline shared library to do what you need or define a function in the pipeline.

jenkins pipeline function errors with no error

I am using a jenkins pipeline script to make product tests on our machines
the father of all tests looks like this
node('nightly-master') {
stage 'run'
println PRODUCTS
oliTest('win7.nightly.test', 'checkAndWaitForInstalledProduct.py', 'esxi', 'opsi-local-image-prepare', 'opsi-local-image-win7', PRODUCTS)
)
}
PRODUCTS is a textbox variable, enetered at the build start
the function oliTest() is this:
def call(SERVERID, CHECKSCRIPT, VIRTUALIZATION, OLIPREPARE, OLINETBOOT, PRODUCTS){
try {
timeout(time: 5, unit: 'HOURS') {
println SERVERID
println CHECKSCRIPT
println VIRTUALIZATION
println OLIPREPARE
println OLINETBOOT
println PRODUCTS
//oliPrepare(SERVERID, CHECKSCRIPT, VIRTUALIZATION, OLIPREPARE, OLINETBOOT)
oliProd(SERVERID, CHECKSCRIPT, VIRTUALIZATION, PRODUCTS)
oliBackup(SERVERID, CHECKSCRIPT, VIRTUALIZATION)
oliRestore(SERVERID, CHECKSCRIPT, VIRTUALIZATION)
}
} catch(error) {
sh "fab -f /home/adminuser/scripts/${VIRTUALIZATIO}Nfab.py powerOffVm:vmName=${SERVERID}"
sh 'return 1'
}
}
the println values are printed correctly into the jenkins log
as soon as the function oliProd() is called the test fails without any error message at the forr loop in the following block
def call(SERVERID, CHECKSCRIPT, VIRTUALIZATION, PRODUCTS){
stage 'install Products'
println SERVERID
println CHECKSCRIPT
println VIRTUALIZATION
println PRODUCTS
sh " echo ${PRODUCTS}"
sh "echo ${SERVERID}"
sh "for i in ${PRODUCTS}; do opsi-admin -d method setProductActionRequestWithDependencies $i ${SERVERID} setup;done"
}
writing it multi line with '''COMMAND''' exists with an error, because ${SERVERID} is not expanded and left empty
Any suggestions how to make things work??
Cheers
Note that you could use have triple double-quotes instead of triple single-quotes. That would have fixed that simple problem.
However, you really should be doing your iteration in the script code itself, instead of trying to do iteration in the shell.
Jon S suggested to resolve script methods such as "echo" against a reference to the "pipeline object as in oliTest(this, ...) where oliTest declares a Script parameter and passes it along to other methods/instances to be used to resolve echo as scriptObj.echo.
println in "call" method of "vars/foo.groovy" works, but not in method in class

How can I run a sub function in Bash

How can I run a 'sub function' from a script in command line? Example:
#script_1.sh
main_function() {
sub_function() {
echo "hello world"
}
}
I tried to source this file and call the function from another script:
#script_2.sh
source script_1.sh
sub_function
But I get
script_2.sh: line 3: sub_function: command not found
while I expected to just get hello world.
Thus defined the sub_function will be defined after function is called.
So:
#script_1.sh
function() {
sub_function() {
#cmd
}
}
#script_2.sh
source script_1.sh
function
sub_function
... should work ... except you should rename function, as it's a reserved word
The step missing in your question is to invoke function first - its action is to define sub_function.
Note that sub_function doesn't 'belong' to function in any way - its definition is just a side-effect of running function.
P.S. I assume you aren't really trying to call it function - that's a reserved word in bash.

Resources