user2994884
user2994884

Reputation: 163

Access Groovy (jenkinsfile) variable inside command-substitution sh block

I have a common jenkinsfile (Jenkins 2.0 pipeline plugin) and I am trying to run a 'nested' curl command inside of a script component:

                    def v = version()
                    def envId = environment()
                    def projectId = projectId()
                    def APIKey = xxx
                    sh "curl -H "Content-Type: application/json" -H "X-Octopus-ApiKey: "'$APIKey'" -d '{"ReleaseId":"'$(curl -H "Content-Type: application/json" -H "X-Octopus-ApiKey: "'$APIKey'" -d '{"version":"'$v'", "ProjectId":"'$projectId'", "Environment-Id":"'$envId'"}' http://xxxxx | grep '"Id":' | head -1 | cut -d ':' -f 2 | cut -d '"' -f 2)'", "EnvironmentId":"'$envId'"}' http://xxxxxx"

As you can see, I am using command substitution within the curl command to pass the ReleaseId value. Do I need to be using a different way to access the variables such as envId, projectId, and APIKey within the $() command substitution portion of my curl command?

From previous research I am wrapping the values of they JSON keys in the format "'$somevar'" however I am getting standard errors for that not being found.

Thank you

Upvotes: 1

Views: 1674

Answers (1)

Michael
Michael

Reputation: 2683

The problem with your code is that you don't escape the double quotes within the command. For Groovy the string which is passed to the sh command ends just before Content-Type unless you escape the double quotes with a backslash.

Also you need to escape dollar signs you want to be interpreted by Bash. Groovy's string interpolation uses the same syntax as Bash.

I tried to fix your command. Hopefully I found all the issues:

sh "curl -H \"Content-Type: application/json\" -H \"X-Octopus-ApiKey: \"'${APIKey}'\" -d '{\"ReleaseId\":\"'\$(curl -H \"Content-Type: application/json\" -H \"X-Octopus-ApiKey: \"'${APIKey}'\" -d '{\"version\":\"'${v}'\", \"ProjectId\":\"'${projectId}'\", \"Environment-Id\":\"'${envId}'\"}' http://xxxxx | grep '\"Id\":' | head -1 | cut -d ':' -f 2 | cut -d '\"' -f 2)'\", \"EnvironmentId\":\"'${envId}'\"}' http://xxxxxx"

By the way, I put the variables from groovy in curly braces. This is not necessary in this case but I consider it a good practice.

Upvotes: 1

Related Questions