代码之家  ›  专栏  ›  技术社区  ›  STN

如何从Jenkins推送到git?

  •  8
  • STN  · 技术社区  · 7 年前

    以下代码是Jenkins中的“执行Shell”构建步骤。作业从包含文件的回购中提取 ranger-policies/policies.json . 我想做的是更新该文件(在本例中使用curl命令),然后将更改提交给源代码管理并更新远程repo。作业使用SSH密钥通过SSH成功地从作业配置页面“源代码管理”部分的远程repo中提取。然而,当作业到达“Execute Shell”步骤中的“git push origin master”行时,我得到一个 Permission denied (publickey) 错误,就好像当我想要推送时,那些允许我成功拉取repo的SSH密钥在“执行Shell”步骤中不可用。

    curl -X GET --header "text/json" -H "Content-Type: text/json" -u user:pass "http://my-url.com/exportJson" > ranger-policies/policies.json
    
    git add ranger-policies/policies.json
    git commit -m "udpate policies.json with latest ranger policies `echo "$(date +'%Y-%m-%d')"`"
    git push origin master
    
    2 回复  |  直到 7 年前
        1
  •  14
  •   STN    7 年前

    我最终想出了如何让它发挥作用。解决方案涉及使用SSH代理插件。这里有一个逐步介绍我是如何做到这一点的,希望它能帮助其他人:

    1. 首先,创建一个新的管道作业。
    2. 然后,正如在 this 从Jenkins的文档发布,转到新管道作业的主屏幕,然后单击“管道语法”选择“git:git”作为“示例步骤,并在“存储库URL”字段中输入要推送到的git repo。然后从“凭据”下拉列表中选择该repo对应的有效SSH密钥。“一切都应该是这样: enter image description here 抓取“credentialsId”的值,在上面的屏幕截图中用红色突出显示。你以后会需要它的。

    3. 安装“工作区清理插件”( https://wiki.jenkins.io/display/JENKINS/Workspace+Cleanup+Plugin https://jenkins.io/doc/pipeline/steps/ssh-agent/ ,非可选,此过程需要)。

    4. 现在回到新的管道作业,点击“配置”,这将带您进入定义作业的屏幕。将以下代码放入“管道”部分(“定义”应设置为“管道脚本”): https://gist.github.com/ScottNeaves/5cdce294296437043b24f0f3f0a8f1d8
    5. 将您的“credentialsId”放入上述Jenkinsfile中的适当位置,并将回购名称固定在您想要的回购中,您应该很乐意去做。

    相关文件:

    1. https://jenkins.io/doc/pipeline/examples/#push-git-repo
    2. https://gist.github.com/blaisep/eb8aa720b06eff4f095e4b64326961b5#file-jenkins-pipeline-git-cred-md
    3. https://issues.jenkins-ci.org/browse/JENKINS-28335?focusedCommentId=269000&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-269000
        2
  •  1
  •   Andrew Gray    7 年前

    根据此 gist ,您需要根据以下内容设置远程源url:

    git remote set-url origin git@github.com:username/your-repository.git