Home > Back-end >  Use jenkins environment variable in SH script with multiple quote
Use jenkins environment variable in SH script with multiple quote

Time:08-17

I want to use jenkins env variable with SH, but inside multiple quote from curl.

Example:

script {
  container('deployer') {
    sh "curl -X POST --data-urlencode \"payload={'channel': '#notification-test-devops', 'username': 'Jenkins Build', 'text': '[Blocked Production] ${env.JOB_BASE_NAME} (${env.BRANCH_NAME} #${BUILD_NUMBER}) <${BUILD_URL}|View Build>', 'icon_emoji': ':jenkins:'}\" https://hooks.slack.com/services/XXX/XXX/XXX"
  }
}

Current result seems it's not rendered:

[Blocked Staging] ${env.JOB_BASE_NAME} (${env.BRANCH_NAME} #${BUILD_NUMBER}) <${BUILD_URL}|View Build>

Screenshot

Expectation: The jenkins env variable will be rendered in Slack message.

CodePudding user response:

you have to backslash your variables.

Change ${env.BRANCH_NAME} by ${env.BRANCH_NAME}

Example :

script {
  container('deployer') {
    sh "curl -X POST --data-urlencode \"payload={'channel': '#notification-test-devops', 'username': 'Jenkins Build', 'text': '[Blocked Production] ${env.JOB_BASE_NAME} (${env.BRANCH_NAME} #${BUILD_NUMBER}) <${BUILD_URL}|View Build>', 'icon_emoji': ':jenkins:'}\" https://hooks.slack.com/services/XXX/XXX/XXX"
  }
}

Became :

script {
  container('deployer') {
    sh "curl -X POST --data-urlencode \"payload={'channel': '#notification-test-devops', 'username': 'Jenkins Build', 'text': '[Blocked Production] \${env.JOB_BASE_NAME} (\${env.BRANCH_NAME} #${BUILD_NUMBER}) <${BUILD_URL}|View Build>', 'icon_emoji': ':jenkins:'}\" https://hooks.slack.com/services/XXX/XXX/XXX"
  }
}

CodePudding user response:

You need to put your message text into double quotes to detect the variables. Give also to your shell block three doubles quotes to no interfer with the doubles others doubles quotes inside the shell block"

script {
  container('deployer') {
    sh """
        curl -X POST --data-urlencode \"payload={'channel': '#notification-test-devops', 'username': 'Jenkins Build', 'text': "[Blocked Production] ${env.JOB_BASE_NAME} (${env.BRANCH_NAME} #${BUILD_NUMBER}) <${BUILD_URL}|View Build>", 'icon_emoji': ':jenkins:'}\" https://hooks.slack.com/services/XXX/XXX/XXX
    """

  }
}
  • Related