使用Jenkins Git插件中的SSH密钥在构建期间运行Git命令

7
我们在Jenkins上的构建作业是发布构建的一部分,其中包括一些git命令,如git push和git pull,因此需要在构建期间从shell运行已验证的git命令。

我们的jenkins节点不保存任何凭据,因为它们是一次性docker容器,每次都会创建新的。

git插件使用Jenkins凭据来管理这个问题,并“某种方式”设置GIT_SSH以获取通过凭据配置的私钥。

我查看了源代码并尝试确定如何配置变量,以便我可以作为构建的SSH脚本运行例如git pull。但是没有成功。

有没有办法在使用Jenkins凭据的情况下,作为构建步骤之一运行git命令?

我目前的解决方案是将SSH密钥复制到节点作为构建环境设置的一部分,但似乎是重复的工作(加上潜在的安全问题)。


你可以通过命令行在Github中添加从机的公钥吗? - krishna_mee2004
每个从节点是一个一次性的Docker容器,没有SSH密钥或任何设置来支持它将比我目前所做的复制更加复杂。 - Elmar Weber
2个回答

2

我也曾经一段时间无法理解这个问题。尽管已经过去了将近三年,但我仍然会发布使用私有SSH密钥的解决方案。它也可以适用于用户/密码组合。

最初的回答:

  1. Add the key to the credentials section as kind "SSH Username with private key".

  2. In the build project use the "Bindings" (You need to tick the "Use secret text(s) or file(s)" in the Build Environment to make it available) to store the credential information in environment variables:

    enter image description here

  3. Now comes the tricky part on how to use the key in the git call. I chose GIT_SSH environment variable since the is the most backward compatible way. In order to make that work you need to create a wrapper script that contains the ssh call using the path to the key file provided in SSH_KEYFILE. One may find a better solution to create that script. For me the following shell commands worked:

    #!/bin/bash
    set +x
    
    SSH_WRAPPER_SCRIPT=/tmp/ssh_wrapper
    
    # delete pre-existing script
    [[ -f $SSH_WRAPPER_SCRIPT ]] && rm $SSH_WRAPPER_SCRIPT
    
    # create wrapper script with current keyfile path from bindings variable
    echo "#!/bin/sh" >> $SSH_WRAPPER_SCRIPT
    echo "exec /usr/bin/ssh -i ${SSH_KEYFILE} \"\$@\"" >> $SSH_WRAPPER_SCRIPT
    chmod +x $SSH_WRAPPER_SCRIPT
    
    # set GIT_SSH env var to use wrapper script
    export GIT_SSH=$SSH_WRAPPER_SCRIPT
    
    # now run your actual git commands here
    git ls-remote -h git@someserver.com:some_repo.git HEAD
    

1
很遗憾,上面答案中的图片已不再可用。因此,我将在此快速总结其内容:(1)安装“凭据绑定插件”(2)然后,项目配置包含“构建环境-使用秘密文本或文件”(3)截至2020年1月的最新版本中,选择“SSH用户私钥”绑定,并将“SSH_KEYFILE”输入为“密钥文件变量”。然后上述解决方案将起作用。 - leosh
我仍然可以正常查看图片并在单独的浏览器中打开链接。截至2020年1月,它仍然可以正常工作。 - cweigel
哦,那肯定是我的代理配置或互联网连接出了问题。 - leosh

-2
如果通过git运行共享凭据是必要的,请尝试使用git客户端插件,但如果您真的只想共享/存储凭据,请考虑使用凭据插件或类似工具。
请注意,您还可以运行一个shell脚本“安装后”,该脚本可以在机器上运行您需要执行的任何命令。

我认为我没有搞明白,插件对提到的问题没有帮助。而目前我正在进行的是使用复制的shell脚本 (虽然不是真正的shell脚本而是构建环境步骤)。 - Elmar Weber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接