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.
11 Answers
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
sshagent(['git-credentials-id']) {
sh "git push origin master"
}

- 942
- 11
- 14
-
2this is still asking for username and password – vinay Feb 12 '18 at 13:29
-
Make sure you have login via SSH enabled on your git and you have added the correct SSH keys to your Jenkins. This has worked for me and 6 other people without need for any additional config. – andrzej.szmukala Feb 13 '18 at 06:59
-
3Ensure you've actually cloned over ssh as well. If you're cloning over HTTPs, you need to use user/pass on the trip back as well. – Sebastian Lenartowicz Oct 29 '19 at 10:26
It is not possible at the moment because GitPublisher
plugin, 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 page and the dedicated GitPublisher Jira issue.
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.
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.

- 7,622
- 5
- 50
- 69
-
18Really? When I try the above answer (using ssh credential just live above) and try to do anything that communicates with the remote I 'Permission denied (publicly).' it is able to checkout the code from git as above, but the credentials are not cached – phil swenson Aug 30 '16 at 22:07
-
1Let's continue with your specific problem on your [dedicated question](http://stackoverflow.com/q/39237910/702954) – Pom12 Aug 31 '16 at 08:43
In my case I was forced to work with HTTPS. I solved it by:
- Creating a username/password credential bitbucketUsernamePassword.
- Using that credential to checkout.
- Setting credential.helper before doing checkout.
- Doing a git checkout branch to get a local branch tracking remote.
Then I am able to push things with git push after that.
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'

- 3,270
- 22
- 27
-
Thanks, this works great for https! I also had to add `sh "git config --global user.email"` && `sh "git config --global user.name"` to be able to commit and push. – mohifleur Oct 16 '20 at 23:23
This thread was really helpful. My Jenkins credentials are username/password so I used:
withCredentials([usernamePassword(credentialsId: 'fixed',
usernameVariable: 'username',
passwordVariable: 'password')]){
sh("git push http://$username:$password@git.corp.mycompany.com/repo")
}
The username and password are both obscured in the log:
+ git push http://****:****@git.corp.mycompany.com/repo

- 3,687
- 4
- 34
- 40

- 2,666
- 4
- 26
- 42
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
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 ci
is the id of the credential you setup within Jenkins. The path to the ssh key becomes available as the environment variable SSH_KEY
and local_ssh.sh is added to current directory.

- 763
- 7
- 11

- 141
- 1
- 3
-
this worked for me on "CloudBees Jenkins Enterprise 2.263.2.3-rolling" when nothing else here worked. hero! – simbo1905 Jan 26 '22 at 20:42
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!!

- 1,027
- 10
- 12
-
3
-
With respect to any SCM, there are two ways of authentication, https and ssh. For ssh authentication, keys are required. May be you are using this in some other manner. – Litty Philip Dec 03 '19 at 07:25
-
1For ssh it is of no use to have private key available in file named by SSH_KEY environment variable when nothing uses SSH_KEY within the withCredentials. This question has other answers that make use of SSH_KEY by sh("GIT_SSH_COMMAND='ssh -i ${SSH_KEY}' git ...") or such. Those can work. This answer contains no working solution. – Marko Kohtala Dec 06 '19 at 20:55
-
1The credentialId mentioned is a credential created in Jenkins as 'SSH Username with private key'. This is a pre-requisite and the rest is internally handled by Jenkins. I expected that this is already known to the answer seeker. And it has worked for me and an upvote of 4, I think means that it has worked for 4 of us. :) – Litty Philip Dec 10 '19 at 04:01
-
@LittyPhilip, are you sure? In my case, the command uses the key under "/var/jenkins_home/.ssh/id_rsa", which is the default one on the server and not the mentioned one in the Credentials Plugin. Is it possible that in your case both keys are equal? – a.ha Apr 26 '21 at 12:24
In my case, I want to push to a CodeCommit repository through SSH. sshagent
doesn't work because it does not set User
. This eventually did the job:
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}'
}
}

- 229
- 5
- 10
Found the solution with help of basic Jenkins and git functionality
stage('Git Push'){
steps{
script{
GIT_CREDS = credentials(<git creds id>)
sh '''
git add .
git commit -m "push to git"
git push https://${GIT_CREDS_USR}:${GIT_CREDS_PSW}@bitbucket.org/<your repo>.git <branch>
'''
}
}
}
https://www.jenkins.io/doc/book/using/using-credentials/ Username and password in command for git push

- 51
- 1
- 2
Litty Philips' answer got me most of the way but I also needed to define 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>
"""
}

- 6,214
- 1
- 23
- 60

- 41
- 1
-
1This snippet is also giving me an error that `GIT_SSH_COMMAND: not found` in the Jenkins declarative pipeline. But replacing the line of specifying the environment variable with the following line fixed that issue: `export GIT_SSH_COMMAND='ssh -i $SSH_KEY' `. It is working correctly. – AnjK Jun 21 '22 at 14:20
Lately, the git plugin add this command:
stage('git push') {
steps {
withCredentials([
gitUsernamePassword(credentialsId: 'github', gitToolName: 'Default')
]) {
sh "git push"
}
}
}
Could not find the related documentation. I found that out in the "Pipeline Syntax" helper found in any Pipeline job.

- 1,404
- 15
- 21
-
1[The doc of the _Credentials Binding Plugin_](https://www.jenkins.io/doc/pipeline/steps/credentials-binding/). – Gerold Broser Oct 29 '21 at 20:20
Got this working with sshagent on blue ocean (which uses https authorisation)
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}")
}

- 101
- 5