How to add variable into sh command


I have the following pipeline:

@Library("ourLibrary@master") _

pipeline {
    agent any

    stages {
        stage('Ask Vault') {
            steps {
                script {

                    ourLibrary.init([logLevel: 'ALL'])

                    def secret = sh(returnStdout: true, script: 'curl -H "X-Vault-Token: token" -H "Content-Type: application/json" -X GET vault_address/v1/jenkins-test/data/user?version=1').trim()
                    def tokenData = new JsonSlurperClassic().parseText(secret)
                    def artifactoryToken = tokenData.get('data').get('data').get('artifactory-token')
                    def JSONPostData = '{"data":{"artifactory-token":"' + artifactoryToken + '"}}'

                    //add tokens to the new vault engine
                    sh('curl -H "X-Vault-Token: token" -H "Content-Type: application/json" -X POST -d \'$JSONPostData\' https://vault-address/v1/jenkins-test-pr-78/user')                    

Unfortunately, after I run this, I get

curl -H ‘X-Vault-Token: token’ -H ‘Content-Type: application/json’ -X POST -d ‘$JSONPostData’ https://vault-address/v1/jenkins-test-pr-78/user

instead of having the actual value of the JSONPostData.

If outside of the cURL I use: println("the JSONPostData token is: " + “${JSONPostData}”) , it prints the correct value.

Please let me know what is wrong.
Thank you.

You’re using single quotes, that makes groovy not interpolate the variables.
You should use double quotes

1 Like