My requirement is that whenever developers are pushing to github, then before the push a CI build should trigger on Jenkins server. If that build fails, then push to github
After some research, I've found that it is possible to trigger jenkins build using github's webhooks, but it's not possible to reject the github push request if the jenkins' build fails. So, basically, we cannot control the github's push, atleast not in free github account.
This isn't generally the workflow possible with GitHub.
You would rather use a "guarded commits" model with 2 GitHub repo:
that's what the requirement is for my project, which can't be changed
In that case, It is best to follow Building a CI server which will:
That means the devs should push only to a "dev" branch, monitored by your server, and your CI engine would push those commits to the master branch if the compilation passes.
It's not possible to do exactly what you're asking for but it's possible to do something that should be close enough.
You can configure GitHub's hooks to invoke your CI server to run a build on every push. When the CI job is started, it should clone the repository and then forcibly push the branch to its previous state. If the build succeeds, push the branch again.
This requires your Jenkins job to have credentials that enable it to write to the repository.
However, you should understand that this method is prone to merge conflicts. It's possible that someone will push to the same branch while the first job is running (or worse, queued). You might have two jobs working on the same branch. Queued jobs are bound to cause problems, the least of which is that the branch will be updated on GitHub until the job runs and someone might pull the changes.
Having said this, my advice is that this workflow is not scalable. A possible alternative is to use protected branches and let your CI jobs merge feature branches into protected branches after successful builds (as long as it's a fast-forward merge).