Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use both Groovy-defined and OS system variable in a multi-line shell script within Jenkins Groovy

I need to access Groovy-defined variables (e.g. var1) in a multi-line shell script in Jenkins. I need to use double-quote """ in sh. (I refer to here)

But I also need to read and change os system variable (e.g. aws_api_key) too. It needs to use single-quote ''' in sh and use \ to escape dollar $ sign. (I refer to here)

How can I use both of them? any help will be much appreciated.

e.g.

node ("Jenkins-Test-Slave") {
stage ("hello world") {
    echo 'Hello World'
}

def var1="bin"
stage ("test") {
    withEnv(["aws_api_key='define in withEnv'","service_url=''"]) {
        echo var1
        sh '''
            echo the groovy data var1 is "${var1}",'\${var1}',\$var1,${var1},var1!!!
            echo default value of aws_api_key is \$aws_api_key
            aws_api_key='changed in shell'
            echo new value of aws_api_key is \$aws_api_key

            export newvar='newxxx'
            echo the new var value is \$newvar
        '''
    }
}
}

The result is:

+ echo the groovy data var1 is ,${var1},,,var1!!!
the groovy data var1 is ,${var1},,,var1!!!
+ echo default value of aws_api_key is 'define in withEnv'
default value of aws_api_key is 'define in withEnv'
+ aws_api_key=changed in shell
+ echo new value of aws_api_key is changed in shell
new value of aws_api_key is changed in shell
+ export newvar=newxxx
+ echo the new var value is newxxx
the new var value is newxxx
like image 668
Orionpax Avatar asked Jan 04 '23 22:01

Orionpax


2 Answers

Instead of multi-line String (''') use multi-line GString (""") to make string interpolation work, then ${var1} will be interpolated as expected:

sh """
    echo the groovy data var1 is "${var1}",'\${var1}',\$var1,${var1},var1!!!
    echo default value of aws_api_key is \$aws_api_key
    aws_api_key='changed in shell'
    echo new value of aws_api_key is \$aws_api_key

    export newvar='newxxx'
    echo the new var value is \$newvar
"""
like image 137
Gergely Toth Avatar answered Jan 13 '23 14:01

Gergely Toth


def var1 = 'bin'

//the following are `groovy` strings (evaluated)

sh "echo var1 = $var1"
//outputs> echo var1 = bin

sh "echo var1 = ${var1}"
//outputs> echo var1 = bin

sh """echo var1 = ${var1}"""
//outputs> echo var1 = bin

sh "echo var1 = \$var1"
//outputs> echo var1 = $var1

//the following are usual strings (not evaluated)

sh 'echo var1 = $var1'
//outputs> echo var1 = $var1

sh '''echo var1 = $var1'''
//outputs> echo var1 = $var1

so, in your case just use

def var1 = 'bin'
sh """
   echo var1 = $var1
   shell_var = 'yyy'
   echo shell_var = \$shell_var
""""
like image 36
daggett Avatar answered Jan 13 '23 16:01

daggett