Code Monkey home page Code Monkey logo

git-deploy's Introduction

git-deploy

A PHP script to automatically pull from a repository to a web server (using a webhook on GitHub, GitLab, or Bitbucket).

You can configure which branch this script pulls from. This script is useful for both development and production servers.


On your server

SSH

Generate an SSH key and add it to your account so that git pull can be run without a password.

Configuration

Copy the git-deploy folder and its contents in to your public folder (typically public_html). Note that you can change the name of the folder if desired.

Rename git-deploy/deploy.sample.php to git-deploy/deploy.php, and update each variable to a value that suits your needs. Multiple copies of git-deploy/deploy.sample.php can be made for multiple projects or versions (you just need to change the webhook url to match the new name). An example of a live configuration is below.

define("TOKEN", "secret-token");
define("REMOTE_REPOSITORY", "[email protected]:username/custom-project.git");
define("DIR", "/var/www/vhosts/repositories/custom-project");
define("BRANCH", "refs/heads/master");
define("LOGFILE", "deploy.log");
define("GIT", "/usr/bin/git");
define("MAX_EXECUTION_TIME", 180);
define("BEFORE_PULL", "/usr/bin/git reset --hard @{u}");
define("AFTER_PULL", "/usr/bin/node ./node_modules/gulp/bin/gulp.js default");

Permissions

When deploy.php is called by the web-hook, the webserver user (www, www-data, apache, etc...) will attempt to run git pull .... Since you probably cloned into the repository as yourself, and your user therefore owns it, the webserver user needs to be given write access. It is suggested this be accomplished by changing the repository group to the webserver user's and giving the group write permissions:

  1. Open a terminal to the directory containing the repository on the server.
  2. run sudo chown -R $USER:webserverusername custom-project-repo-dir/.git/ to change the group of the repo.
  3. run sudo chmod -R g+s custom-project-repo-dir/.git/ to make the group assignment inherited for new files/dirs.
  4. run sudo chmod -R 775 custom-project-repo-dir/.git/ to set read & write for both owner and group.

On GitHub | GitLab | Bitbucket

GitHub

In your repository, navigate to Settings โ†’ Webhooks โ†’ Add webhook, and use the following settings:

  • Payload URL: https://www.yoursite.com/git-deploy/deploy.php
  • Content type: application/json
  • Secret: The value of TOKEN in config.php
  • Which events would you like to trigger this webhook?: ๐Ÿ”˜ Just the push event
  • Active: โ˜‘๏ธ

Click "Add webhook" to save your settings, and the script should start working.

Example screenshot showing GitHub webhook settings

GitLab

In your repository, navigate to Settings โ†’ Integrations, and use the following settings:

Click "Add webhook" to save your settings, and the script should start working.

Example screenshot showing GitLab webhook settings

Bitbucket

In your repository, navigate to Settings โ†’ Webhooks โ†’ Add webhook, and use the following settings:

Click "Save" to save your settings, and the script should start working.

Example screenshot showing Bitbucket webhook settings

Integration with CI/CD

If you'd prefer to integrate git-deploy with your CI scripts rather than using traditional Webhooks, you can trigger the hook via the following wget command.

wget --quiet --output-document=- --content-on-error --header="Content-Type: application/json" --post-data='{"ref":"refs/heads/master"}' 'https://www.example.com/git-deploy/deploy.php?token=secret-token'

Additionally, you can add the parameters sha=COMMIT_HASH and reset=true to the URL in order to instruct git-deploy to reset to a specific commit. Note that this will overwrite any local changes you may have made. This can be useful for integration with things like GitLab's Environments feature.


I appreciate the collaboration of @JacobDB

git-deploy's People

Contributors

aaronalbers avatar evansharp avatar hucruz avatar jacobdb avatar paimpozhil avatar vicenteguerra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

git-deploy's Issues

error on runtime T_PAAMAYIM_NEKUDOTAYIM

This error msg found when run on php php-5.4.45 or below but no error on php-5.5.38 above

PHP message: PHP Parse error: syntax error, unexpected ')', expecting :: (T_PAAMAYIM_NEKUDOTAYIM) in xxxxxxxxxxxxxx/git-deploy/deployer.php on line 47

Update GitHub/GitLab/BitBucket instructions to reflect UI changes

GitHub and GitLab have both had some pretty major UI changes since the instructions in the README where set up. Screenshots need updated to match the newest UI, and instructions may need adjusted as well. Additionally, while BitBucket is listed as having instructions, no guide currently exists for this.

I'll take a look at updating these later this week.

Not working for private repository

Hi
I am trying to use this script for private repository, but its not working, although SSH is set up properly n gitlab but if I try to test

" fatal: could not read Username for 'https://gitlab.com': No such device or address HEAD is now at df699ba Add new file"

Git pull not being executed over SSH

I think this line needs to reference the REMOTE_REPOSITORY defined in the config (it's not referenced anywhere else in deployer.php). Without it git pull is executed over HTTPS giving the following error:

fatal: could not read Username for 'https://github.com': No such device or address

$result = shell_exec(GIT . " pull 2>&1");

[feature request] limit log file size

in my CI env, repo are constantly pushed and that makes deploy.log file increase in hundreds MB to GB

please add an option so we can limit how much max the log file size could grow

Not working

I have a problem, git deploy says *** AUTO PULL SUCCESFUL *** but no files have been pulled.

Host key verification failed.

Hello, I had a problem with my GIT server and I had to change its IP, so far everything worked perfectly but after I changed the IP it stopped working, I've updated the ssh know_hosts but I get the error in the image below
image

Git deploy is not working

Hello

I try the script but its not working in log it shows it pull but when i see the files no changes have been done

Issues with www-root user accessing git repo

Hey, thanks for the script. I think I've just about got it set up and am down to the last details. Upon setting up my github webhooks and testing, the debug.log file indicates that I have issues with my host key.

I'm assuming that this has to do with the SSH key that my www-root user is using to access my github repository. I have used ssh-keygen to generate rsa keys for both my www-root user as well as my normal user. For my normal user, git pull works fine, however when the webhook hits the deploy.php script, I receive the following error.

I tried generating the rsa key for my www-root user in it's home directory at /var/www/.ssh/ and adding the public key to github, but no cigar.

*** AUTO PULL INITIATED ***
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

*** AUTO PULL COMPLETE ***

Any thoughts? I'm not sure if this is an issue with this repo, but perhaps it's an opportunity for more clarification in the readme if it is something really simple.

SSH not allowed on some hosts

Not really an issue, more like a tip:
I tried to use git-deploy on a host but failed because SSH was not accessible for the apache/php user, so git pull resulted in an error: fatal: could not spawn fork.
I managed to get it working though, switching the remote to https, and applying git config credential.helper store. Note that this stores the credentials on disk, so make sure this applies to your use case.

Add troubleshooting guide

For people who aren't very familiar with servers, it'd be nice to have a troubleshooting guide, walking through common problems and how to resolve them. Of course, I believe this script is really only meant to be used by advanced users, so maybe this isn't strictly necessary.

Some ideas:

  • Fixing ownership & permissions
  • Determining location of git executable

Add config option for "post hook command"

I'm trying to get a project set up that automatically pulls and runs npm i && gulp --dist. To that end, it'd be great if there was an option for command(s) to run once the pull is finished. Something like define('EXECUTE', ['array', 'of', 'sequential', 'commands']); or define('EXECUTE', 'string of commands');.

I'll try to look in doing this myself, and submit a pull request if I'm successful.

Bitbucket v5.11.1 not working?

Hi, if I try to use it at Bitbucket it says:

=== ERROR: Pushed branch does not match BRANCH ===

my row for BRANCH is:
define("BRANCH", "refs/head/master");

and I have in the repo "master" as Branch, do you know where the failure is??

Thanks for your help!

Paths

Constant problems with the path

=== ERROR: DIR /D:/bkp-imobtotal/importacoes/ does not exist ===

=== ERROR: Pull failed using GIT /%ProgramFiles%/Git/git-bash.exe/ and DIR /bkp-imobtotal/importacoes/ ===
The filename, directory name, or volume label syntax is incorrect.

already chechek and are all valid paths...

Any hints?

"No output" error with github, works fine with gitlab

Github shows my webhook failing with this error:

=== ERROR: Pull failed using GIT /usr/bin/git and DIR /home/***/public_html/ ===
[no output]

It's using application/json.
I'm able to git pull via ssh (as the web user) without problem.
My public key was READ ONLY, so I changed it to READ+WRITE ... same error.
I had no problem getting this to work on another site on the same VPS, the only difference being that this site uses github, whereas the working one uses gitlab.

Any advice?

Local commits / uncommitted changes are always reset when using gitlab webhooks

When using gitlab webhooks the field "checkout_sha" will always be present. This causes the deployer to execute this block always which can have unwanted side effects.

if (!empty($sha)) {
                // write to the log
                fputs($file, "*** RESET TO HASH INITIATED ***" . "\n");

                exec(GIT . " reset --hard {$sha} 2>&1", $output, $exit);

Of course this makes sense since you do not want to have merge conflicts when using an auto deploy mechanism. In our case we have local sql-lite db running in the webapp that always got deleted although it was never checked in.

Already up to date bug

I have two branches (master/dev). I have git-deploy set up to use the dev branch.

I got this to work with one branch, however the second branch is not picking up any changes.

I made a code edit to a file in the dev branch, pushed it to gitlab. I can see in the deploy.log that it tried to deploy however it says everything is up-to-date. Am I missing something?

Improve wording in README

The grammar and wording in the README is a little confusing; I'm guessing English isn't your first language, so I'll go through and correct what I can and submit a pull request.

=== ERROR: DIR is not a repository ===

Hi, i am trying to set this git-deploy with shared hosting. a2hosting.

git is enabled and exec also enabled.

it does finds the directory.

here is how i did setup my directory in config.

define("DIR", "/home/{username}/repositories/pakistanihaider.me");

"{username}" is my account username

i created the related directory as well. and i did checked it finds the directory.

But git pull command is not being executed..??

What am i doing wrong here??

Support for https for private OAUTH accounts using personal access tokens

I am hitting a wall and suspect it is the fact that GitHub requires OAUTH accounts to authenticate using only https using personal access tokens. I tried changing the URL to the https URL structure of
https://[account]:[personalaccesstoken]@github.com/[account]/repo.git
but still receive a "fatal: could not read Username for 'https://github.com': No such device or address" error. Any chance of support for OAUTH accounts using this method?

Permission Denied

=== ERROR: Pull failed using GIT /usr/bin/git and DIR /var/www/html/repository ===
error: cannot open .git/FETCH_HEAD: Permission denied

Add native support for GitHub & GitLab secret tokens

The logic would be something like:

  1. Check for $_SERVER["HTTP_X_HUB_SIGNATURE"] (GitHub token)
  2. If no GitHub token exists, check for $_SERVER["HTTP_X_GITLAB_TOKEN"] (GitLab token)
  3. If no GitLab token exists, check for $_GET["token"]
  4. If any of the three tokens exist, compare the first one against the secret specified in config.php
  5. If no token exists, proceed with script

I'll submit a pull request for this some time this week.

Documentation:

Example:

always sh: 1: /usr/bin/git: not found

i follow this instruction
run sudo chown -R yourusername:webserverusername custom-project-repo-dir/ to change the group of the repo.
run sudo chmod -R g+s custom-project-repo-dir/ to make the group assignment inherited for new files/dirs.
run sudo chmod -R 775 custom-project-repo-dir/ to set read & write for both owner and group.

but, still not work "/usr/bin/git: not found". i try to run which git and get "/usr/bin/git". why?

Pull failed - permission denied

Hi,

I am getting this error, when call "git pull" from script:

=== ERROR: Pull failed using GIT /usr/bin/git and DIR /home/****/public_html/test.****.de/ ===
Permission denied (publickey).
fatal: Could not read from remote repository.

But when I execute "git pull" via ssh console, I dont get this error and the pull will execute.

I checked the user calling the script. It's the same user I'm signed in with via ssh.

Has anyone an idea?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.