如何将jenkins凭据传递到docker build命令中? [英] How to pass jenkins credentials into docker build command?
问题描述
我的Jenkins管道代码成功地使用bitbucket签出了我的私人git仓库
My Jenkins pipeline code successfully checks out my private git repo from bitbucket using
checkout([$class: 'GitSCM',
userRemoteConfigs: [[credentialsId: 'cicd-user', url:'ssh://git@bitbucket.myorg.co:7999/A/software.git']]
在相同的software.git中,我有一个Dockerfile,我想用来构建Kubernetes上software.git中存在的各种构建目标,并且我正在尝试以下方法将jenkins凭据传递到我要构建和运行的Docker容器中
in same software.git I have a Dockerfile that I want to use to build various build targets present in software.git on Kubernetes and I am trying the below to pass jenkins credentials into a docker container that I want to build and run.
因此,当我检出software.git(在代码上方)时,在相同的詹金斯管道中,我尝试执行以下操作以构建docker容器
So in the same jenkins pipeline when I checked out software.git (above code), I try to do the following to get the docker container built
withCredentials([sshUserPrivateKey(credentialsId: 'cicd-user', keyFileVariable: 'FILE')]) {
sh "cd ${WORKSPACE} && docker build -t ${some-name} --build-arg USERNAME=cicd-user --build-arg PRIV_KEY_FILE=$FILE --network=host -f software/tools/jenkins/${some-name}/Dockerfile ."
}
我在Dockerfile中
in Dockerfile I do
RUN echo "$PRIV_KEY_FILE" > /home/"$USERNAME"/.ssh/id_rsa && \
chmod 700 /home/"$USERNAME"/.ssh/id_rsa
RUN echo"Host bitbucket.myorg.co \ n \ tStrictHostKeyChecking no \ n";>>〜/.ssh/config
RUN echo "Host bitbucket.myorg.co\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config
但是仍然从我的Docker容器中,我无法成功检出我的私有存储库.我想念什么?有什么意见,建议吗?谢谢.
But still from my Docker container I am not able to successfully checkout my private repo(s). What am I missing ? Any comments, suggestions ? Thanks.
推荐答案
请阅读有关 Groovy字符串的信息插值.
在您的表情中
sh "cd ${WORKSPACE} && docker build -t ${some-name} \
--build-arg USERNAME=cicd-user \
--build-arg PRIV_KEY_FILE=$FILE --network=host \
-f software/tools/jenkins/${some-name}/Dockerfile ."
您使用双引号将Groovy插值到字符串中的所有变量.这包括 $ FILE
,因此Groovy将其替换为名为 FILE
的Groovy变量的值.您没有任何具有该名称的Groovy变量(而是与Groovy不同的 bash
变量),因此将其替换为空字符串.
you use double quotes so Groovy interpolates all the variables in the string. This includes $FILE
so Groovy replaces that with the value of Groovy variable named FILE
. You don't have any Groovy variable with that name (but rather bash
variable which is different from Groovy) so this gets replaced with an empty string.
为防止插值该特定变量,您需要通过用 \
将此 $
转义,以提示Groovy不要插值该特定变量:
To prevent interpolating that particular variable, you need to hint Groovy not to interpolate this particular one, by escaping this $
with \
:
sh "cd ${WORKSPACE} && docker build -t ${some-name}\
--build-arg USERNAME=cicd-user \
--build-arg PRIV_KEY_FILE=\$FILE --network=host \
-f software/tools/jenkins/${some-name}/Dockerfile ."
这篇关于如何将jenkins凭据传递到docker build命令中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!