是否可以使用 Jenkins 管道进行 Git 合并/推送

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38769976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 04:27:21  来源:igfitidea点击:

Is it possible to Git merge / push using Jenkins pipeline

gitjenkinsgroovybitbucket

提问by Progger

I am trying to create a Jenkins workflow using a Jenkinsfile. All I want it to do is monitor the 'develop' branch for changes. When a change occurs, I want it to git tag and merge to master. I am using the GitSCM Step but the only thing that it appears to support is git clone. I don't want to have to shell out to do the tag / merge but I see no way around it. Does anyone know if this is possible? I am using BitBucket (on-prem) for my Git server.

我正在尝试使用 Jenkinsfile 创建一个 Jenkins 工作流程。我想要它做的就是监视“开发”分支的变化。当发生变化时,我希望它 git tag 并合并到 master。我正在使用 GitSCM Step,但它似乎唯一支持的是 git clone。我不想花钱去做标签/合并,但我看不出有什么办法。有谁知道这是否可能?我正在为我的 Git 服务器使用 BitBucket(本地)。

回答by Pom12

It is not possible at the moment because GitPublisherplugin, the plugin previously responsible for tagging/merging/pushing in freestyle jobs, has not been updated to be compatible with Jenkins pipelines. You can follow that issue on both the pipeline plugins compatibility pageand the dedicated GitPublisher Jira issue.

目前这是不可能的,因为GitPublisher插件,以前负责标记/合并/推送自由式作业的插件,尚未更新为与 Jenkins 管道兼容。您可以在管道插件兼容性页面和专用GitPublisher Jira 问题上关注该问题

So it seems the only option you have is to actually shell out your tag/merge commands... However, note that you can still benefit from some Jenkins built-in capabilities such as the use of credentials for your Git repo, which make it pretty straightforward to then tag / merge following your needs.

因此,您似乎唯一的选择是实际执行标记/合并命令......但是,请注意,您仍然可以从一些 Jenkins 内置功能中受益,例如使用 Git 存储库的凭据,这使得它然后根据您的需要标记/合并非常简单。

Example check-out :

示例退房:

git url: "ssh://jenkins@your-git-repo:12345/your-git-project.git",
    credentialsId: 'jenkins_ssh_key',
    branch: develop

Then the tag / merge / push will be pretty straightforward :

然后标签/合并/推送将非常简单:

sh 'git tag -a tagName -m "Your tag comment"'
sh 'git merge develop'
sh 'git commit -am "Merged develop branch to master'
sh "git push origin master"

I hope that one day GitPublisher will be released in a pipeline-compatible version, but for now this workaround should do.

我希望有一天 GitPublisher 会以管道兼容的版本发布,但现在这种解决方法应该可以。

回答by andrzej.szmukala

If what you're after are the git credentials you can use the SSH Agent plugin like in this link: https://issues.jenkins-ci.org/browse/JENKINS-28335?focusedCommentId=260925&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-260925

如果您想要的是 git 凭据,您可以使用 SSH 代理插件,如此链接中所示:https: //issues.jenkins-ci.org/browse/JENKINS-28335?focusedCommentId=260925&page=com.atlassian.jira。 plugin.system.issuetabpanels%3Acomment-tabpanel#comment-260925

sshagent(['git-credentials-id']) {
  sh "git push origin master"
}

回答by Tomas Bjerre

In my case I was forced to work with HTTPS. I solved it by:

就我而言,我被迫使用 HTTPS。我通过以下方式解决了它:

  1. Creating a username/password credential bitbucketUsernamePassword.
  2. Using that credential to checkout.
  3. Setting credential.helper before doing checkout.
  4. Doing a git checkout branchto get a local branch tracking remote.
  1. 创建用户名/密码凭证bitbucketUsernamePassword
  2. 使用该凭据结帐。
  3. 在结帐之前设置 credential.helper。
  4. 执行git checkout 分支以获取本地分支跟踪远程。

Then I am able to push things with git pushafter that.

然后我就可以用git push推送东西了。

Like this:

像这样:

sh 'git config --global credential.helper cache'
sh 'git config --global push.default simple'

checkout([
    $class: 'GitSCM',
    branches: [[name: branch]],
    extensions: [
        [$class: 'CloneOption', noTags: true, reference: '', shallow: true]
    ],
    submoduleCfg: [],
    userRemoteConfigs: [
        [ credentialsId: 'bitbucketUsernamePassword', url: cloneUrl]
    ]
])
sh "git checkout ${branch}" //To get a local branch tracking remote

Then I can do things like:

然后我可以做这样的事情:

sh 'git push'

回答by s d

This thread was really helpful. My Jenkins credentials are username/password so I used:

这个线程真的很有帮助。我的 Jenkins 凭据是用户名/密码,所以我使用了:

withCredentials([usernamePassword(credentialsId: 'fixed', usernameVariable: 'username', passwordVariable: 'password')]){
                {
                    sh("git push http://$username:[email protected]/repo")
                }

The username and password are both obscured in the log:

用户名和密码都隐藏在日志中:

+ git push http://****:****@git.corp.mycompany.com/repo

回答by Litty Philip

Yes, it is!! After struggling for days, I ended up with these simple code block for scripted pipeline script which worked for me.

是的!!经过几天的努力,我最终得到了这些对我有用的脚本化管道脚本的简单代码块。

withCredentials([sshUserPrivateKey(credentialsId: '<credential-id>', keyFileVariable: 'SSH_KEY')]) {
   sh("git push origin <local-branch>:<remote-branch>")
}

Enjoyy!!

好享受!!

回答by Gregorio Melo

I've had to do a similar task and managed to get it to work with a variation of this: https://issues.jenkins-ci.org/browse/JENKINS-28335?focusedCommentId=320383&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-320383

我不得不做一个类似的任务并设法让它与这个变体一起工作:https: //issues.jenkins-ci.org/browse/JENKINS-28335?focusedCommentId=320383&page=com.atlassian.jira。 plugin.system.issuetabpanels%3Acomment-tabpanel#comment-320383

withCredentials([sshUserPrivateKey(credentialsId: 'ci', keyFileVariable: 'SSH_KEY')]) {
    sh 'echo ssh -i $SSH_KEY -l git -o StrictHostKeyChecking=no \"\$@\" > local_ssh.sh'
    sh 'chmod +x local_ssh.sh'
    withEnv(['GIT_SSH=./local_ssh.sh']) {
        sh 'git push origin develop'
    }
}

Whereas ciis the id of the credential you setup within Jenkins. The path to the ssh key becomes available as the environment variable SSH_KEYand local_ssh.sh is added to current directory.

ci是您在 Jenkins 中设置的凭据的 ID。当环境变量SSH_KEY和 local_ssh.sh 添加到当前目录时,ssh 密钥的路径变得可用。

回答by NeverFall

In my case, I want to push to a CodeCommit repository through SSH. sshagentdoesn't work because it does not set User. This eventually did the job:

就我而言,我想通过 SSH 推送到 CodeCommit 存储库。sshagent不起作用,因为它没有设置User。这最终完成了工作:

withCredentials([sshUserPrivateKey(credentialsId: CODECOMMIT_CREDENTIALS_ID, keyFileVariable: 'SSH_KEY', usernameVariable: 'SSH_USER')]) {
    withEnv(["GIT_SSH_COMMAND=ssh -o StrictHostKeyChecking=no -o User=${SSH_USER} -i ${SSH_KEY}"]) {
        sh 'git push ${CODECOMMIT_URL} ${COMMIT_ID}:refs/heads/${BRANCH}'
    }
}

回答by Martynas Petu?ka

Got this working with sshagent on blue ocean (which uses https authorisation)

在蓝海(使用 https 授权)上与 sshagent 一起使用

sshagent(credentials: ["406ef572-9598-45ee-8d39-9c9a227a9227"]) {
                    def repository = "git@" + env.GIT_URL.replaceFirst(".+://", "").replaceFirst("/", ":")
                    sh("git remote set-url origin $repository")
                    sh("git tag --force build-${env.BRANCH_NAME}")
                    sh("git push --force origin build-${env.BRANCH_NAME}")
                }

回答by J Blackburn

Litty Philips' answer got me most of the way but I also needed to define GIT_SSH_COMMAND.

Litty Philips 的回答让我了解了大部分情况,但我还需要定义 GIT_SSH_COMMAND。

withCredentials([sshUserPrivateKey(credentialsId: '<credential-id>', keyFileVariable: 'SSH_KEY')]) {
   sh """
   GIT_SSH_COMMAND = "ssh -i $SSH_KEY"
   git push origin <local-branch>:<remote-branch>
   """
}