How to create a Gitlab webhook to update a mirror repo on Github?

≡放荡痞女 提交于 2019-11-28 03:23:48

You don't need a webhook for that. A regular post-receive hook will work very well.

To create and use such a hook you just have to login on the server where your gitlab is installed and create an ssh key for git user.

sudo -u git ssh-keygen -f /home/git/.ssh/reponame_key

(do not type any passphrase when prompted)

Go to your github account and add the public key (it's been created as /home/git/ssh/reponame_key.pub) to your project as a deploy key. have a look at https://help.github.com/articles/managing-deploy-keys if you need help with that.

Once that is done, you just have to configure the connection between your git server and github's: add an alias to git user's ssh configuration (add following lines to /home/git/.ssh/config - create it if it's not present)

Host reponame  
IdentityFile /home/git/.ssh/reponame_key  
HostName github.com  
User git 

Now add the new remote (using the alias you just created) to your repository:

cd /home/git/repositories/namespace/reponame.git

git remote add --mirror github reponame:youruser/reponame.git

Now that everything is in place you'll have to create the actual hook:

cd /home/git/repositories/namespace/reponame.git/hooks

echo "exec git push --quiet github &" >> post-receive

chmod 755 post-receive

The lastcommand is very important because git will check if a hook is executable before running it.

That's it!

(Replace reponame, namespace and youruser according to your real accounts and enjoy).

Last note: if you want your name andavatar near commits on github, make sure that the email address you are using on gitlab is one of the addresses inked to your github account as well. You'll see your gitlab username otherwise.

If you aren't hosting your own GitLab, GitLab.com has introduced this feature directly, without any workarounds.

  1. From within a project use the gear icon to select Mirror Repository
  2. Scroll down to Push to a remote repository
  3. Checkmark Remote mirror repository: Automatically update the remote mirror's branches, tags, and commits from this repository every hour.
  4. Enter the repository you want to update; for GitHub you can include your username and password in the URL, like so: https://yourgithubusername:yourgithubpassword@github.com/agaric/guts_discuss_resource.git —as noted in the comments, it is much better securitywise to use your GitHub access token here instead of login credentials; will update the answer when i've tested.

For WebHooks processing I'm using sinatra web server.

require 'sinatra'
post '/pew' do
  puts JSON.parse request.body.read
  # here can be placed signal code to run commit processing script
end

register webhook for push events(or other) to http://localhost:4567/pew within GitLab and since this moment on each commit gitlab will be sending commit info to url.

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