The reason why the git pull
step fails is because on Ubuntu, Apache executes the script as the user www-data
. Thus, git
looks for the ssh keys associated with the user www-data
and failing to find them, is unable to complete the git pull
request.
On Ubuntu 16.04, the user www-data
is assigned the home directory /var/www
. This is the directory in which git
looks for the ssh keys to negotiate the transfer. Thus the solution is make GitHub believe that the user www-data
is real by assigning it a valid set of keys. To break down the steps:
Note: This assumes that you have sudo
access.
Create a directory /var/www/.ssh
owned by www-data:www-data
$ sudo mkdir -p /var/www/.ssh
$ sudo chown -R www-data:www-data /var/www/.ssh
Create ssh keys in the directory
$ cd /var/www/.ssh
$ sudo ssh-keygen -t rsa -b 2048
When ssh-keygen
asks for the directory to put the keys in, choose /var/www/id_rsa
Ensure that the persmissions and ownership of the keys is correct. chown
to www-data:www-data
as necessary.
$ ls -la /var/www/.ssh/
total 24K
drwxr-xr-x 2 www-data www-data 4.0K Apr 29 23:58 ./
drwxr-xr-x 5 root root 4.0K Apr 30 00:06 ../
-rw------- 1 www-data www-data 1.7K Apr 29 23:33 id_rsa
-rw-r--r-- 1 www-data www-data 394 Apr 29 23:33 id_rsa.pub
Copy the id_rsa.pub
key to the authorized ssh keys in the GitHub repository settings.
It is important to ensure that the git pull
works when performed as the user www-data
. Using ssh also needs adding the GitHub server identity to the known_hosts
file. However, the user www-data
does not have a login shell by default. So we have to use a simple trick:
$ sudo vi /etc/passwd
Find the line for www-data
and change the /usr/sbin/nologin
to /bin/bash
and save the file. The entry for www-data
should look similar to:
www-data:x:33:33:www-data:/var/www:/bin/bash
Change to the user www-data
$ sudo su
# su - www-data
Once you are logged in as www-data
, go to the git repository and perform a git pull
manually.
The ssh process will ask you to add the identity of the GitHub server to known_hosts
file and use the key pair under /var/www/.ssh
to complete the git pull
.
If it succeeds, you should be set. Try to push
a commit to GitHub from another computer and verify that the PHP script executes the pull
request.
Reset the /etc/passwd
file to it's original state with the login shell of the www-data
user as /usr/sbin/nologin