简体   繁体   中英

Bash variable escaping in a Jenkinsfile

I am trying the following:

sh '''
    changelog=$(git log `git describe --tags --abbrev=0 HEAD^`..HEAD --oneline)
    curl --data '{"\tag_name\": \\"v0.0.${BUILD_NUMBER}\\",\"target_commitish\": \"master\",\"name\": \\"Release v0.0.$BUILD_NUMBER\\",\"body\": \\"$changelog\\",\"draft\": false,\"prerelease\": false}' https://****/api/v3/repos/****/****/releases?access_token=$JENKINS_ACCESS_TOKEN_PSW
'''

Basically I want to include "dynamic" values for tag , name and body which are taken using the Jenkins build number ( $BUILD_NUMBER ) and a bash variable containing the result of git log ( changelog ).

I've made all sort of single and double quotes and other escaping changes that I am not sure anymore how it should be.

This currently fails with:

curl: (6) Could not resolve host: variable
curl: (6) Could not resolve host: escaping
curl: (6) Could not resolve host: 9a21d71
curl: (6) Could not resolve host: more
curl: (6) Could not resolve host: escaping
curl: (6) Could not resolve host: attempts
curl: (6) Could not resolve host: 708ed0f
curl: (6) Could not resolve host: more
curl: (6) Could not resolve host: escaping'

It can't handle the contents inside the changelog variable.

The challenge here is not just to properly escape the quotes when dynamically generating a string, but also to ensure that the result is a valid JSON. For example in your case changelog may contain newlines and quotes and, when it is expanded into the "body": "$changelog" part of your POST data, those characters must be properly escaped.

To this end use the jq utility to generate the POST JSON data as explained in the answer to a similar question :

sh '''
    changelog=$(git log `git describe --tags --abbrev=0 HEAD^`..HEAD --oneline)
    jq -n --arg tagname "v0.0.$BUILD_NUMBER"      \
          --arg name "Release v0.0.$BUILD_NUMBER" \
          --arg body "$changelog"                 \
          '{"tag_name": $tagname, "target_commitish": "master", "name": $name, "body": $body, "draft": false, "prerelease": false}'  |
    curl -d@- https://****/api/v3/repos/****/****/releases?access_token=$JENKINS_ACCESS_TOKEN_PSW
'''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM