Jenkins Pipeline Git Push

馋奶兔 提交于 2021-02-04 18:58:48

问题


Is there as way to have a stage like so in a Jenkinsfile:

stage('Create Branch & Push Branch') {
            steps {
                script {
                    sh "git checkout -b release/${NEW_TAG}"
                    sh "git push --set-upstream
                }
            }
    }

Currently this leads to:

  • git push --set-upstream origin release/v1.0.3 fatal: could not read Username for 'https://github.com': No such device or address script returned exit code 128

The repository was originally cloned earlier in the pipeline using:

checkout poll: false, scm: [$class: 'GitSCM', branches: [[name: 'develop']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'CleanBeforeCheckout'], [$class: 'CleanCheckout'], [$class: 'CloneOption', depth: 0, noTags: false, reference: '', shallow: false]], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'ci-github', url: 'https://github.com/my-org/my-repo.git']]]

That part works ok (the clone), presumably because I can supply this step with the jenkins credential id for github.

Is there a way for me to do the same to push back to a repo that was cloned earlier in the build?


回答1:


I've made this work using:

withCredentials([usernamePassword(credentialsId: 'ci-github', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
                        sh('git push https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/my-org/my-repo.git')
                    }

After reading https://github.com/jenkinsci/pipeline-examples/blob/master/pipeline-examples/push-git-repo/pushGitRepo.groovy and https://issues.jenkins-ci.org/browse/JENKINS-28335.

An alternative approach using SSH keys appears to be :

sshagent(['credentiald-id-using-ssh-key']) 
 {
    sh('git command or program calling git inside') 
 }



回答2:


To get this working for blue ocean (which uses https connection) use the following:

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}")
                }


来源:https://stackoverflow.com/questions/53325544/jenkins-pipeline-git-push

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!