DEV Community

developer-help
developer-help

Posted on

Curious case of Git delete with jenkins pipeline

Hi Guys,

Today i want to share a unique use case of delete remote git branch command with jenkins pipeline. All a job is doing some work checkin to a branch, merge it with master and want to delete once everything is done.

It is simply captured with below set of command from commandline

git checkout branch
git commit
git push

git checkout master
git merge branch
git push
git branch -d branch//local branch delete
git push origin --delete branch

This is simple if you are doing it from the your dev machine, but not so with jenkins pipepline running in cloud with some cloud provider.

One of the key things to note hear is, git is not secured protocol and you can't directly communicate on top of it, because cloud providers rule will whitelist the delete command, because it can see the content.

So we have to use https to communicate with remote git repo.

I modified the command like this

withCredentials([[
$class: 'UsernamePasswordMultiBinding',
credentialsId: 'my-git-credential-id',
usernameVariable: 'GIT_USERNAME',
passwordVariable: 'GIT_PASSWORD'
]]) {
sh 'git push origin --delete branch'
}

considering this will go through, but this command keeps on hanging without any clues.

Now the second attempt was to change it like this circumventing whitelisting of the cloud provider.

withCredentials([[
$class: 'UsernamePasswordMultiBinding',
credentialsId: 'my-git-credential-id',
usernameVariable: 'GIT_USERNAME',
passwordVariable: 'GIT_PASSWORD'
]]) {
sh 'git push origin --delete branch https://${GIT_USERNAME}:${GIT_PASSWORD}@${GIT_URL_WITHOUT_HTTPS}'
}

But still it is not working, with all the thoughts being put through of why it is not working.

Than finally comes Eureka moment where i just interchanged order of commands, as with https url in git command flags are the last one to end the command with argument preceding them.

withCredentials([[
$class: 'UsernamePasswordMultiBinding',
credentialsId: 'my-git-credential-id',
usernameVariable: 'GIT_USERNAME',
passwordVariable: 'GIT_PASSWORD'
]]) {
sh 'git push https://${GIT_USERNAME}:${GIT_PASSWORD}@${GIT_URL_WITHOUT_HTTPS}'branch --delete
}

Top comments (0)