Issue
Hopefully this is a straightforward issue. I have a groovy method I'm calling from within a Jenkinsfile that is supposed to execute a docker build
shell command. The line is as follows:
sh "docker build --build-arg \"VERSION=${tag}\" -t \"${project}:${tag}\" ."
However, when I run this from Jenkins, it seems to break this command into newlines, confusing docker:
17:26:05.151 docker build --build-arg "VERSION=<tag>
17:26:05.151 " -t "<project>:<tag>
17:26:05.151 " .
17:26:05.451 invalid argument "<project>:<tag>\n" for "-t, --tag" flag: invalid reference format
17:26:05.451 See 'docker build --help'.
The double quotes around the variables were necessary to get the full command in in some form. Without them, the output cuts off, like this:
17:17:24.368 ++ docker build --build-arg VERSION=<tag>
17:17:24.368 "docker build" requires exactly 1 argument.
Something is definitely wrong with how I'm translating bash to groovy, but I'm not sure what.
Solution
Consider the following:
def tag = "testing_tag\n"
def project="test_proj"
node {
echo "docker build --build-arg \"VERSION= " +
tag +
"\" -t \"${project}:" +
tag + "\" ."
}
Will give you exactly what you have:
docker build --build-arg "VERSION=tag
" -t "project:tag
" .
You can get rid of any newline characters using .replace("\n", "" )
def tag = "tag\n"
def project="project"
node {
echo "docker build --build-arg \"VERSION=" +
tag.replace("\n", "" ).trim() +
"\" -t \"${project}:" +
tag.replace("\n", "" ).trim() + "\" ."
}
A better option would be replacing all newline characters:
echo "docker build --build-arg \"VERSION=${tag}\" -t \"${project}:${tag}\" .".replace("\n", "" ).trim()
Now you just need to substitute echo
with sh
def tag = "tag\n"
def project="project"
node {
def command = "docker build --build-arg \"VERSION=${tag}\" -t \"${project}:${tag}\" .".replace("\n", "" ).trim()
echo command
sh command
}
This example replaces every newline character, regardless if it's a variable coming from Jenkins (in my case) or not. Just adapt for your needs.
Answered By - agentsmith
Answer Checked By - Mary Flores (JavaFixing Volunteer)