How to push to git on EC2
Solution 1:
To copy your local ssh key to amazon try this
cat ~/.ssh/id_?sa.pub | ssh -i amazon-generated-key.pem ec2-user@amazon-instance-public-dns "cat >> .ssh/authorized_keys"
replacing the names of the key and amazon ec2 public dns, of course.
you will then be able to setup your remote on amazon
Solution 2:
The instructions listed here were more useful to me.
From the link:
Adjust your ~/.ssh/config
and add:
Host example
Hostname example.com
User myuser
IdentityFile ~/.ssh/other_id_rsa
Now use the ssh host alias as your repository:
$ git remote add origin example:repository.git
$ git pull origin master
And it should use the other_id_rsa
key!
Solution 3:
On your local machine, edit your ~/.ssh/config and add:
Host example
Hostname example.com
User myuser
IdentityFile ~/.ssh/YOURPRIVATEKEY
You should be able to login to your instance with "ssh example". Remember your private key should be chmod 400. Once you can ssh in without using "ssh -i mykey.pem username@host", do the following.
On your EC2 instance, initialize a bare repository, which is used to push to exclusively. The convention is to add the extention ".git" to the folder name. This may appear different than your local repo that normally has as .git folder inside of your "project" folder. Bare repositories (by definition) don't have a working tree attached to them, so you can't easily add files to them as you would in a normal non-bare repository. This is just they way it is done. On your ec2 instance:
mkdir project_folder.git
cd project_folder.git
git init --bare
Now, back on your local machine, use the ssh host alias when setting up your remote.
git remote add ec2 EXAMPLEHOSTFROMSSHCONFIG:/path/to/project_folder.git
Now, you should be able to do:
git push ec2 master
Now your code is being pushed to the server with no problems. But the problem at this point, is that your www folder on the ec2 instance does not contain the actual "working files" your web-server needs to execute. So, you need to setup a "hook" script that will execute when you push to ec2. This script will populate the appropriate folder on your ec2 instance with your actual project files.
So, on your ec2 instance, go into your project_folder.git/hooks directory. Then create a file called "post-receive" and chmod 775 it (it must be executable). Then insert this bash script:
#!/bin/bash
while read oldrev newrev ref
do
branch=`echo $ref | cut -d/ -f3`
if [ "ec2" == "$branch" -o "master" == "$branch" ]; then
git --work-tree=/var/www/example.com/public_html/ checkout -f $branch
echo 'Changes pushed to Amazon EC2 PROD.'
fi
done
Now, on your local machine, do a "git push ec2 master" and it should push the code to your bare repo, and then the post-receive hook script will checkout your files into the appropriate folder that your webserver is configured to read.