1

In Jenkins pipeline I cannot embed the env variables:

sh 'curl -d '{"color":"green","message":"${BUILD_NUMBER}","notify":false,"message_format":"text"}' -H 'Content-Type: application/json' http:blahbah.com'

and the problem is even when I try to use escape chars \ in front of every ' and " the output on the target machine is always ${BUILD_NUMBER}

How should look the correct curl syntax here?

kol23
  • 1,498
  • 3
  • 16
  • 35

2 Answers2

1

Your curl -d argument command is surrounded with single-quotes.

curl -d '{"color":"green","message":"${BUILD_NUMBER}","notify":false,"message_format":"text"}' -H 'Content-Type: application/json' http:blahbah.com'

In general (at least in bash) "Single quotes won't interpolate anything, but double quotes will (for example variables, backticks, certain \ escapes, etc...)".

With Jenkins Pipelines, you need to be careful about the quote escaping that is provided. You can see some of the strange behaviors documented here.

One way to handle this case is to substitute the env.BUILD_NUMBER value in Groovy rather than at shell evaluation. Groovy's triple-quoted strings can also help with string quoting:

sh """curl -d '{"color":"green","message":"${env.BUILD_NUMBER}","notify":false,"message_format":"text"}' -H 'Content-Type: application/json' http:blahbah.com'"""

Here I:

  1. Surround the entire command with """. Double quotes are used for string interpolation and triple quotes are used to simplify the quoting inside for the curl command JSON.
  2. ${env.BUILD_NUMBER} is Groovy interpolated into the JSON body
mkobit
  • 43,979
  • 12
  • 156
  • 150
0

Instead of Using ${BUILD_NUMBER}, use $BUILD_NUMBER. It will do the trick. Here are some sample codes.

Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):

env.MYTOOL_VERSION = '1.33'
node {
  sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
}

pipeline { 
  agent any 
  stages {
    stage('Build') { 
        steps { 
            sh 'echo "Hello World $BUILD_ID"' 
        }
    }
  }
}
SV Madhava Reddy
  • 1,858
  • 2
  • 15
  • 33